aboutsummaryrefslogtreecommitdiff
path: root/src/util
diff options
context:
space:
mode:
authorng0 <ng0@n0.is>2019-09-08 12:33:09 +0000
committerng0 <ng0@n0.is>2019-09-08 12:33:09 +0000
commitd41ed82a4ea0cc8e1674b6d5d2c49fd6462610bb (patch)
tree9efd18ea7d425652085ed0bd5e8e45604bc5f6b9 /src/util
parenta0fce305c565c0937d917a92712f15e9c5736260 (diff)
downloadgnunet-d41ed82a4ea0cc8e1674b6d5d2c49fd6462610bb.tar.gz
gnunet-d41ed82a4ea0cc8e1674b6d5d2c49fd6462610bb.zip
uncrustify as demanded.
Diffstat (limited to 'src/util')
-rw-r--r--src/util/bandwidth.c368
-rw-r--r--src/util/benchmark.c260
-rw-r--r--src/util/benchmark.h92
-rw-r--r--src/util/bio.c384
-rw-r--r--src/util/client.c891
-rw-r--r--src/util/common_allocation.c294
-rw-r--r--src/util/common_endian.c26
-rw-r--r--src/util/common_logging.c1083
-rw-r--r--src/util/configuration.c1351
-rw-r--r--src/util/configuration_loader.c66
-rw-r--r--src/util/container_bloomfilter.c552
-rw-r--r--src/util/container_heap.c329
-rw-r--r--src/util/container_meta_data.c975
-rw-r--r--src/util/container_multihashmap.c885
-rw-r--r--src/util/container_multihashmap32.c333
-rw-r--r--src/util/container_multipeermap.c831
-rw-r--r--src/util/container_multishortmap.c785
-rw-r--r--src/util/container_multiuuidmap.c795
-rw-r--r--src/util/crypto_abe.c335
-rw-r--r--src/util/crypto_crc.c63
-rw-r--r--src/util/crypto_ecc.c1416
-rw-r--r--src/util/crypto_ecc_dlog.c377
-rw-r--r--src/util/crypto_ecc_setup.c608
-rw-r--r--src/util/crypto_hash.c305
-rw-r--r--src/util/crypto_hash_file.c167
-rw-r--r--src/util/crypto_hkdf.c184
-rw-r--r--src/util/crypto_kdf.c136
-rw-r--r--src/util/crypto_mpi.c112
-rw-r--r--src/util/crypto_paillier.c423
-rw-r--r--src/util/crypto_random.c283
-rw-r--r--src/util/crypto_rsa.c1106
-rw-r--r--src/util/crypto_symmetric.c186
-rw-r--r--src/util/disk.c2507
-rw-r--r--src/util/disk.h8
-rw-r--r--src/util/dnsparser.c1292
-rw-r--r--src/util/dnsstub.c546
-rw-r--r--src/util/getopt.c1041
-rw-r--r--src/util/getopt_helpers.c766
-rw-r--r--src/util/gnunet-config-diff.c20
-rw-r--r--src/util/gnunet-config.c342
-rw-r--r--src/util/gnunet-ecc.c560
-rw-r--r--src/util/gnunet-helper-w32-console.c249
-rw-r--r--src/util/gnunet-helper-w32-console.h10
-rw-r--r--src/util/gnunet-qr.c258
-rw-r--r--src/util/gnunet-resolver.c146
-rw-r--r--src/util/gnunet-scrypt.c356
-rw-r--r--src/util/gnunet-service-resolver.c1241
-rw-r--r--src/util/gnunet-timeout-w32.c182
-rw-r--r--src/util/gnunet-timeout.c104
-rw-r--r--src/util/gnunet-uri.c149
-rw-r--r--src/util/helper.c562
-rw-r--r--src/util/load.c97
-rw-r--r--src/util/mq.c680
-rw-r--r--src/util/mst.c463
-rw-r--r--src/util/nc.c97
-rw-r--r--src/util/network.c1975
-rw-r--r--src/util/op.c157
-rw-r--r--src/util/os_installation.c1005
-rw-r--r--src/util/os_network.c560
-rw-r--r--src/util/os_priority.c2218
-rw-r--r--src/util/peer.c141
-rw-r--r--src/util/perf_crypto_asymmetric.c95
-rw-r--r--src/util/perf_crypto_ecc_dlog.c168
-rw-r--r--src/util/perf_crypto_hash.c84
-rw-r--r--src/util/perf_crypto_paillier.c90
-rw-r--r--src/util/perf_crypto_rsa.c266
-rw-r--r--src/util/perf_crypto_symmetric.c52
-rw-r--r--src/util/perf_malloc.c30
-rw-r--r--src/util/plugin.c246
-rw-r--r--src/util/proc_compat.c14
-rw-r--r--src/util/program.c354
-rw-r--r--src/util/regex.c970
-rw-r--r--src/util/resolver.h11
-rw-r--r--src/util/resolver_api.c1294
-rw-r--r--src/util/scheduler.c1923
-rw-r--r--src/util/service.c2247
-rw-r--r--src/util/signal.c64
-rw-r--r--src/util/socks.c549
-rw-r--r--src/util/speedup.c94
-rw-r--r--src/util/speedup.h10
-rw-r--r--src/util/strings.c2002
-rw-r--r--src/util/test_bio.c436
-rw-r--r--src/util/test_client.c154
-rw-r--r--src/util/test_common_allocation.c118
-rw-r--r--src/util/test_common_endian.c18
-rw-r--r--src/util/test_common_logging.c96
-rw-r--r--src/util/test_common_logging_dummy.c92
-rw-r--r--src/util/test_common_logging_runtime_loglevels.c493
-rw-r--r--src/util/test_configuration.c663
-rw-r--r--src/util/test_container_bloomfilter.c304
-rw-r--r--src/util/test_container_dll.c79
-rw-r--r--src/util/test_container_heap.c382
-rw-r--r--src/util/test_container_meta_data.c426
-rw-r--r--src/util/test_container_multihashmap.c126
-rw-r--r--src/util/test_container_multihashmap32.c92
-rw-r--r--src/util/test_container_multipeermap.c126
-rw-r--r--src/util/test_crypto_crc.c12
-rw-r--r--src/util/test_crypto_ecc_dlog.c174
-rw-r--r--src/util/test_crypto_ecdh_eddsa.c82
-rw-r--r--src/util/test_crypto_ecdhe.c58
-rw-r--r--src/util/test_crypto_ecdsa.c266
-rw-r--r--src/util/test_crypto_eddsa.c206
-rw-r--r--src/util/test_crypto_hash.c104
-rw-r--r--src/util/test_crypto_hash_context.c44
-rw-r--r--src/util/test_crypto_hkdf.c276
-rw-r--r--src/util/test_crypto_kdf.c47
-rw-r--r--src/util/test_crypto_paillier.c305
-rw-r--r--src/util/test_crypto_random.c37
-rw-r--r--src/util/test_crypto_rsa.c154
-rw-r--r--src/util/test_crypto_symmetric.c152
-rw-r--r--src/util/test_disk.c336
-rw-r--r--src/util/test_getopt.c167
-rw-r--r--src/util/test_hexcoder.c32
-rw-r--r--src/util/test_mq.c281
-rw-r--r--src/util/test_os_network.c68
-rw-r--r--src/util/test_os_start_process.c279
-rw-r--r--src/util/test_peer.c98
-rw-r--r--src/util/test_plugin.c40
-rw-r--r--src/util/test_plugin_plug.c14
-rw-r--r--src/util/test_program.c128
-rw-r--r--src/util/test_regex.c184
-rw-r--r--src/util/test_resolver_api.c421
-rw-r--r--src/util/test_scheduler.c182
-rw-r--r--src/util/test_scheduler_delay.c56
-rw-r--r--src/util/test_service.c196
-rw-r--r--src/util/test_socks.c255
-rw-r--r--src/util/test_speedup.c86
-rw-r--r--src/util/test_strings.c170
-rw-r--r--src/util/test_strings_to_data.c43
-rw-r--r--src/util/test_time.c260
-rw-r--r--src/util/test_tun.c66
-rw-r--r--src/util/time.c413
-rw-r--r--src/util/tun.c264
-rw-r--r--src/util/w32cat.c166
-rw-r--r--src/util/win.c1319
-rw-r--r--src/util/winproc.c369
136 files changed, 27884 insertions, 27827 deletions
diff --git a/src/util/bandwidth.c b/src/util/bandwidth.c
index bdac43b77..562eed01b 100644
--- a/src/util/bandwidth.c
+++ b/src/util/bandwidth.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/bandwidth.c 22 * @file util/bandwidth.c
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29 29
30#define LOG(kind, ...) GNUNET_log_from (kind, "util-bandwidth", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-bandwidth", __VA_ARGS__)
31 31
32/** 32/**
33 * Create a new bandwidth value. 33 * Create a new bandwidth value.
@@ -36,11 +36,11 @@
36 * @return the new bandwidth value 36 * @return the new bandwidth value
37 */ 37 */
38struct GNUNET_BANDWIDTH_Value32NBO 38struct GNUNET_BANDWIDTH_Value32NBO
39GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second) 39GNUNET_BANDWIDTH_value_init(uint32_t bytes_per_second)
40{ 40{
41 struct GNUNET_BANDWIDTH_Value32NBO ret; 41 struct GNUNET_BANDWIDTH_Value32NBO ret;
42 42
43 ret.value__ = htonl (bytes_per_second); 43 ret.value__ = htonl(bytes_per_second);
44 return ret; 44 return ret;
45} 45}
46 46
@@ -53,11 +53,11 @@ GNUNET_BANDWIDTH_value_init (uint32_t bytes_per_second)
53 * @return the min of b1 and b2 53 * @return the min of b1 and b2
54 */ 54 */
55struct GNUNET_BANDWIDTH_Value32NBO 55struct GNUNET_BANDWIDTH_Value32NBO
56GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1, 56GNUNET_BANDWIDTH_value_min(struct GNUNET_BANDWIDTH_Value32NBO b1,
57 struct GNUNET_BANDWIDTH_Value32NBO b2) 57 struct GNUNET_BANDWIDTH_Value32NBO b2)
58{ 58{
59 return GNUNET_BANDWIDTH_value_init ( 59 return GNUNET_BANDWIDTH_value_init(
60 GNUNET_MIN (ntohl (b1.value__), ntohl (b2.value__))); 60 GNUNET_MIN(ntohl(b1.value__), ntohl(b2.value__)));
61} 61}
62 62
63 63
@@ -69,11 +69,11 @@ GNUNET_BANDWIDTH_value_min (struct GNUNET_BANDWIDTH_Value32NBO b1,
69 * @return the min of b1 and b2 69 * @return the min of b1 and b2
70 */ 70 */
71struct GNUNET_BANDWIDTH_Value32NBO 71struct GNUNET_BANDWIDTH_Value32NBO
72GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1, 72GNUNET_BANDWIDTH_value_max(struct GNUNET_BANDWIDTH_Value32NBO b1,
73 struct GNUNET_BANDWIDTH_Value32NBO b2) 73 struct GNUNET_BANDWIDTH_Value32NBO b2)
74{ 74{
75 return GNUNET_BANDWIDTH_value_init ( 75 return GNUNET_BANDWIDTH_value_init(
76 GNUNET_MAX (ntohl (b1.value__), ntohl (b2.value__))); 76 GNUNET_MAX(ntohl(b1.value__), ntohl(b2.value__)));
77} 77}
78 78
79 79
@@ -85,10 +85,10 @@ GNUNET_BANDWIDTH_value_max (struct GNUNET_BANDWIDTH_Value32NBO b1,
85 * @return the sum of b1 and b2 85 * @return the sum of b1 and b2
86 */ 86 */
87struct GNUNET_BANDWIDTH_Value32NBO 87struct GNUNET_BANDWIDTH_Value32NBO
88GNUNET_BANDWIDTH_value_sum (struct GNUNET_BANDWIDTH_Value32NBO b1, 88GNUNET_BANDWIDTH_value_sum(struct GNUNET_BANDWIDTH_Value32NBO b1,
89 struct GNUNET_BANDWIDTH_Value32NBO b2) 89 struct GNUNET_BANDWIDTH_Value32NBO b2)
90{ 90{
91 return GNUNET_BANDWIDTH_value_init (ntohl (b1.value__) + ntohl (b2.value__)); 91 return GNUNET_BANDWIDTH_value_init(ntohl(b1.value__) + ntohl(b2.value__));
92} 92}
93 93
94 94
@@ -101,18 +101,18 @@ GNUNET_BANDWIDTH_value_sum (struct GNUNET_BANDWIDTH_Value32NBO b1,
101 * @return number of bytes available at bps until deadline 101 * @return number of bytes available at bps until deadline
102 */ 102 */
103uint64_t 103uint64_t
104GNUNET_BANDWIDTH_value_get_available_until ( 104GNUNET_BANDWIDTH_value_get_available_until(
105 struct GNUNET_BANDWIDTH_Value32NBO bps, 105 struct GNUNET_BANDWIDTH_Value32NBO bps,
106 struct GNUNET_TIME_Relative deadline) 106 struct GNUNET_TIME_Relative deadline)
107{ 107{
108 uint64_t b; 108 uint64_t b;
109 109
110 b = ntohl (bps.value__); 110 b = ntohl(bps.value__);
111 LOG (GNUNET_ERROR_TYPE_DEBUG, 111 LOG(GNUNET_ERROR_TYPE_DEBUG,
112 "Bandwidth has %llu bytes available until deadline in %s\n", 112 "Bandwidth has %llu bytes available until deadline in %s\n",
113 (unsigned long long) ((b * deadline.rel_value_us + 500000LL) / 113 (unsigned long long)((b * deadline.rel_value_us + 500000LL) /
114 1000000LL), 114 1000000LL),
115 GNUNET_STRINGS_relative_time_to_string (deadline, GNUNET_YES)); 115 GNUNET_STRINGS_relative_time_to_string(deadline, GNUNET_YES));
116 return (b * deadline.rel_value_us + 500000LL) / 1000000LL; 116 return (b * deadline.rel_value_us + 500000LL) / 1000000LL;
117} 117}
118 118
@@ -126,24 +126,24 @@ GNUNET_BANDWIDTH_value_get_available_until (
126 * @return how long it would take 126 * @return how long it would take
127 */ 127 */
128struct GNUNET_TIME_Relative 128struct GNUNET_TIME_Relative
129GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps, 129GNUNET_BANDWIDTH_value_get_delay_for(struct GNUNET_BANDWIDTH_Value32NBO bps,
130 uint64_t size) 130 uint64_t size)
131{ 131{
132 uint64_t b; 132 uint64_t b;
133 struct GNUNET_TIME_Relative ret; 133 struct GNUNET_TIME_Relative ret;
134 134
135 b = ntohl (bps.value__); 135 b = ntohl(bps.value__);
136 if (0 == b) 136 if (0 == b)
137 { 137 {
138 LOG (GNUNET_ERROR_TYPE_DEBUG, 138 LOG(GNUNET_ERROR_TYPE_DEBUG,
139 "Bandwidth suggests delay of infinity (zero bandwidth)\n"); 139 "Bandwidth suggests delay of infinity (zero bandwidth)\n");
140 return GNUNET_TIME_UNIT_FOREVER_REL; 140 return GNUNET_TIME_UNIT_FOREVER_REL;
141 } 141 }
142 ret.rel_value_us = size * 1000LL * 1000LL / b; 142 ret.rel_value_us = size * 1000LL * 1000LL / b;
143 LOG (GNUNET_ERROR_TYPE_DEBUG, 143 LOG(GNUNET_ERROR_TYPE_DEBUG,
144 "Bandwidth suggests delay of %s for %llu bytes of traffic\n", 144 "Bandwidth suggests delay of %s for %llu bytes of traffic\n",
145 GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES), 145 GNUNET_STRINGS_relative_time_to_string(ret, GNUNET_YES),
146 (unsigned long long) size); 146 (unsigned long long)size);
147 return ret; 147 return ret;
148} 148}
149 149
@@ -154,17 +154,17 @@ GNUNET_BANDWIDTH_value_get_delay_for (struct GNUNET_BANDWIDTH_Value32NBO bps,
154 * @param cls the `struct GNUNET_BANDWIDTH_Tracker` 154 * @param cls the `struct GNUNET_BANDWIDTH_Tracker`
155 */ 155 */
156static void 156static void
157excess_trigger (void *cls) 157excess_trigger(void *cls)
158{ 158{
159 struct GNUNET_BANDWIDTH_Tracker *av = cls; 159 struct GNUNET_BANDWIDTH_Tracker *av = cls;
160 160
161 av->excess_task = NULL; 161 av->excess_task = NULL;
162 if (NULL != av->excess_cb) 162 if (NULL != av->excess_cb)
163 { 163 {
164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 164 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
165 "Notifying application about excess bandwidth\n"); 165 "Notifying application about excess bandwidth\n");
166 av->excess_cb (av->excess_cb_cls); 166 av->excess_cb(av->excess_cb_cls);
167 } 167 }
168} 168}
169 169
170 170
@@ -172,7 +172,7 @@ excess_trigger (void *cls)
172 * Recalculate when we might need to call the excess callback. 172 * Recalculate when we might need to call the excess callback.
173 */ 173 */
174static void 174static void
175update_excess (struct GNUNET_BANDWIDTH_Tracker *av) 175update_excess(struct GNUNET_BANDWIDTH_Tracker *av)
176{ 176{
177 struct GNUNET_TIME_Relative delay; 177 struct GNUNET_TIME_Relative delay;
178 struct GNUNET_TIME_Absolute now; 178 struct GNUNET_TIME_Absolute now;
@@ -184,53 +184,53 @@ update_excess (struct GNUNET_BANDWIDTH_Tracker *av)
184 184
185 if (NULL == av->excess_cb) 185 if (NULL == av->excess_cb)
186 return; /* nothing to do */ 186 return; /* nothing to do */
187 now = GNUNET_TIME_absolute_get (); 187 now = GNUNET_TIME_absolute_get();
188 delta_time = now.abs_value_us - av->last_update__.abs_value_us; 188 delta_time = now.abs_value_us - av->last_update__.abs_value_us;
189 delta_avail = 189 delta_avail =
190 (delta_time * ((unsigned long long) av->available_bytes_per_s__) + 190 (delta_time * ((unsigned long long)av->available_bytes_per_s__) +
191 500000LL) / 191 500000LL) /
192 1000000LL; 192 1000000LL;
193 current_consumption = av->consumption_since_last_update__ - delta_avail; 193 current_consumption = av->consumption_since_last_update__ - delta_avail;
194 if (current_consumption > av->consumption_since_last_update__) 194 if (current_consumption > av->consumption_since_last_update__)
195 { 195 {
196 /* integer underflow, cap! */ 196 /* integer underflow, cap! */
197 current_consumption = INT64_MIN; 197 current_consumption = INT64_MIN;
198 } 198 }
199 /* negative current_consumption means that we have savings */ 199 /* negative current_consumption means that we have savings */
200 max_carry = ((uint64_t) av->available_bytes_per_s__) * av->max_carry_s__; 200 max_carry = ((uint64_t)av->available_bytes_per_s__) * av->max_carry_s__;
201 if (max_carry < GNUNET_MAX_MESSAGE_SIZE) 201 if (max_carry < GNUNET_MAX_MESSAGE_SIZE)
202 max_carry = GNUNET_MAX_MESSAGE_SIZE; 202 max_carry = GNUNET_MAX_MESSAGE_SIZE;
203 if (max_carry > INT64_MAX) 203 if (max_carry > INT64_MAX)
204 max_carry = INT64_MAX; 204 max_carry = INT64_MAX;
205 left_bytes = current_consumption + max_carry; 205 left_bytes = current_consumption + max_carry;
206 if (left_bytes < current_consumption) 206 if (left_bytes < current_consumption)
207 { 207 {
208 /* integer overflow, cap! */ 208 /* integer overflow, cap! */
209 left_bytes = INT64_MAX; 209 left_bytes = INT64_MAX;
210 } 210 }
211 /* left_bytes now contains the number of bytes needed until 211 /* left_bytes now contains the number of bytes needed until
212 we have more savings than allowed */ 212 we have more savings than allowed */
213 if (left_bytes < 0) 213 if (left_bytes < 0)
214 { 214 {
215 /* having excess already */ 215 /* having excess already */
216 delay = GNUNET_TIME_UNIT_ZERO; 216 delay = GNUNET_TIME_UNIT_ZERO;
217 } 217 }
218 else 218 else
219 { 219 {
220 double factor = 1.0 * left_bytes / (double) av->available_bytes_per_s__; 220 double factor = 1.0 * left_bytes / (double)av->available_bytes_per_s__;
221 delay = 221 delay =
222 GNUNET_TIME_relative_saturating_multiply (GNUNET_TIME_UNIT_SECONDS, 222 GNUNET_TIME_relative_saturating_multiply(GNUNET_TIME_UNIT_SECONDS,
223 (unsigned long long) factor); 223 (unsigned long long)factor);
224 } 224 }
225 GNUNET_log ( 225 GNUNET_log(
226 GNUNET_ERROR_TYPE_DEBUG, 226 GNUNET_ERROR_TYPE_DEBUG,
227 "At %llu bps it will take us %s for %lld bytes to reach excess threshold\n", 227 "At %llu bps it will take us %s for %lld bytes to reach excess threshold\n",
228 (unsigned long long) av->available_bytes_per_s__, 228 (unsigned long long)av->available_bytes_per_s__,
229 GNUNET_STRINGS_relative_time_to_string (delay, GNUNET_NO), 229 GNUNET_STRINGS_relative_time_to_string(delay, GNUNET_NO),
230 (long long) left_bytes); 230 (long long)left_bytes);
231 if (NULL != av->excess_task) 231 if (NULL != av->excess_task)
232 GNUNET_SCHEDULER_cancel (av->excess_task); 232 GNUNET_SCHEDULER_cancel(av->excess_task);
233 av->excess_task = GNUNET_SCHEDULER_add_delayed (delay, &excess_trigger, av); 233 av->excess_task = GNUNET_SCHEDULER_add_delayed(delay, &excess_trigger, av);
234} 234}
235 235
236 236
@@ -256,7 +256,7 @@ update_excess (struct GNUNET_BANDWIDTH_Tracker *av)
256 * @param excess_cb_cls closure for @a excess_cb 256 * @param excess_cb_cls closure for @a excess_cb
257 */ 257 */
258void 258void
259GNUNET_BANDWIDTH_tracker_init2 ( 259GNUNET_BANDWIDTH_tracker_init2(
260 struct GNUNET_BANDWIDTH_Tracker *av, 260 struct GNUNET_BANDWIDTH_Tracker *av,
261 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb, 261 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
262 void *update_cb_cls, 262 void *update_cb_cls,
@@ -268,17 +268,17 @@ GNUNET_BANDWIDTH_tracker_init2 (
268 av->update_cb = update_cb; 268 av->update_cb = update_cb;
269 av->update_cb_cls = update_cb_cls; 269 av->update_cb_cls = update_cb_cls;
270 av->consumption_since_last_update__ = 0; 270 av->consumption_since_last_update__ = 0;
271 av->last_update__ = GNUNET_TIME_absolute_get (); 271 av->last_update__ = GNUNET_TIME_absolute_get();
272 av->available_bytes_per_s__ = ntohl (bytes_per_second_limit.value__); 272 av->available_bytes_per_s__ = ntohl(bytes_per_second_limit.value__);
273 av->max_carry_s__ = max_carry_s; 273 av->max_carry_s__ = max_carry_s;
274 av->excess_cb = excess_cb; 274 av->excess_cb = excess_cb;
275 av->excess_cb_cls = excess_cb_cls; 275 av->excess_cb_cls = excess_cb_cls;
276 LOG (GNUNET_ERROR_TYPE_DEBUG, 276 LOG(GNUNET_ERROR_TYPE_DEBUG,
277 "Tracker %p initialized with %u Bps and max carry %u\n", 277 "Tracker %p initialized with %u Bps and max carry %u\n",
278 av, 278 av,
279 (unsigned int) av->available_bytes_per_s__, 279 (unsigned int)av->available_bytes_per_s__,
280 (unsigned int) max_carry_s); 280 (unsigned int)max_carry_s);
281 update_excess (av); 281 update_excess(av);
282} 282}
283 283
284 284
@@ -299,20 +299,20 @@ GNUNET_BANDWIDTH_tracker_init2 (
299 * may accumulate before it expires 299 * may accumulate before it expires
300 */ 300 */
301void 301void
302GNUNET_BANDWIDTH_tracker_init ( 302GNUNET_BANDWIDTH_tracker_init(
303 struct GNUNET_BANDWIDTH_Tracker *av, 303 struct GNUNET_BANDWIDTH_Tracker *av,
304 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb, 304 GNUNET_BANDWIDTH_TrackerUpdateCallback update_cb,
305 void *update_cb_cls, 305 void *update_cb_cls,
306 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit, 306 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit,
307 uint32_t max_carry_s) 307 uint32_t max_carry_s)
308{ 308{
309 GNUNET_BANDWIDTH_tracker_init2 (av, 309 GNUNET_BANDWIDTH_tracker_init2(av,
310 update_cb, 310 update_cb,
311 update_cb_cls, 311 update_cb_cls,
312 bytes_per_second_limit, 312 bytes_per_second_limit,
313 max_carry_s, 313 max_carry_s,
314 NULL, 314 NULL,
315 NULL); 315 NULL);
316} 316}
317 317
318 318
@@ -322,10 +322,10 @@ GNUNET_BANDWIDTH_tracker_init (
322 * @param av the respective trackers 322 * @param av the respective trackers
323 */ 323 */
324void 324void
325GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av) 325GNUNET_BANDWIDTH_tracker_notification_stop(struct GNUNET_BANDWIDTH_Tracker *av)
326{ 326{
327 if (NULL != av->excess_task) 327 if (NULL != av->excess_task)
328 GNUNET_SCHEDULER_cancel (av->excess_task); 328 GNUNET_SCHEDULER_cancel(av->excess_task);
329 av->excess_task = NULL; 329 av->excess_task = NULL;
330 av->excess_cb = NULL; 330 av->excess_cb = NULL;
331 av->excess_cb_cls = NULL; 331 av->excess_cb_cls = NULL;
@@ -341,7 +341,7 @@ GNUNET_BANDWIDTH_tracker_notification_stop (struct GNUNET_BANDWIDTH_Tracker *av)
341 * @param av tracker to update 341 * @param av tracker to update
342 */ 342 */
343static void 343static void
344update_tracker (struct GNUNET_BANDWIDTH_Tracker *av) 344update_tracker(struct GNUNET_BANDWIDTH_Tracker *av)
345{ 345{
346 struct GNUNET_TIME_Absolute now; 346 struct GNUNET_TIME_Absolute now;
347 uint64_t delta_time; 347 uint64_t delta_time;
@@ -349,39 +349,39 @@ update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
349 uint64_t left_bytes; 349 uint64_t left_bytes;
350 uint64_t max_carry; 350 uint64_t max_carry;
351 351
352 now = GNUNET_TIME_absolute_get (); 352 now = GNUNET_TIME_absolute_get();
353 delta_time = now.abs_value_us - av->last_update__.abs_value_us; 353 delta_time = now.abs_value_us - av->last_update__.abs_value_us;
354 delta_avail = 354 delta_avail =
355 (delta_time * ((unsigned long long) av->available_bytes_per_s__) + 355 (delta_time * ((unsigned long long)av->available_bytes_per_s__) +
356 500000LL) / 356 500000LL) /
357 1000000LL; 357 1000000LL;
358 av->consumption_since_last_update__ -= delta_avail; 358 av->consumption_since_last_update__ -= delta_avail;
359 av->last_update__ = now; 359 av->last_update__ = now;
360 if (av->consumption_since_last_update__ < 0) 360 if (av->consumption_since_last_update__ < 0)
361 { 361 {
362 left_bytes = -av->consumption_since_last_update__; 362 left_bytes = -av->consumption_since_last_update__;
363 max_carry = 363 max_carry =
364 ((unsigned long long) av->available_bytes_per_s__) * av->max_carry_s__; 364 ((unsigned long long)av->available_bytes_per_s__) * av->max_carry_s__;
365 if (max_carry < GNUNET_MAX_MESSAGE_SIZE) 365 if (max_carry < GNUNET_MAX_MESSAGE_SIZE)
366 max_carry = GNUNET_MAX_MESSAGE_SIZE; 366 max_carry = GNUNET_MAX_MESSAGE_SIZE;
367 if (max_carry > INT64_MAX) 367 if (max_carry > INT64_MAX)
368 max_carry = INT64_MAX; 368 max_carry = INT64_MAX;
369 if (max_carry > left_bytes) 369 if (max_carry > left_bytes)
370 av->consumption_since_last_update__ = -left_bytes; 370 av->consumption_since_last_update__ = -left_bytes;
371 else 371 else
372 av->consumption_since_last_update__ = -max_carry; 372 av->consumption_since_last_update__ = -max_carry;
373 } 373 }
374#if ! defined(GNUNET_CULL_LOGGING) 374#if !defined(GNUNET_CULL_LOGGING)
375 { 375 {
376 struct GNUNET_TIME_Relative delta; 376 struct GNUNET_TIME_Relative delta;
377 377
378 delta.rel_value_us = delta_time; 378 delta.rel_value_us = delta_time;
379 LOG (GNUNET_ERROR_TYPE_DEBUG, 379 LOG(GNUNET_ERROR_TYPE_DEBUG,
380 "Tracker %p updated, consumption at %lld at %u Bps, last update was %s ago\n", 380 "Tracker %p updated, consumption at %lld at %u Bps, last update was %s ago\n",
381 av, 381 av,
382 (long long) av->consumption_since_last_update__, 382 (long long)av->consumption_since_last_update__,
383 (unsigned int) av->available_bytes_per_s__, 383 (unsigned int)av->available_bytes_per_s__,
384 GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES)); 384 GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_YES));
385 } 385 }
386#endif 386#endif
387} 387}
@@ -399,48 +399,48 @@ update_tracker (struct GNUNET_BANDWIDTH_Tracker *av)
399 * @return #GNUNET_YES if this consumption is above the limit 399 * @return #GNUNET_YES if this consumption is above the limit
400 */ 400 */
401int 401int
402GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av, 402GNUNET_BANDWIDTH_tracker_consume(struct GNUNET_BANDWIDTH_Tracker *av,
403 ssize_t size) 403 ssize_t size)
404{ 404{
405 int64_t nc; 405 int64_t nc;
406 406
407 LOG (GNUNET_ERROR_TYPE_DEBUG, 407 LOG(GNUNET_ERROR_TYPE_DEBUG,
408 "Tracker %p consumes %d bytes\n", 408 "Tracker %p consumes %d bytes\n",
409 av, 409 av,
410 (int) size); 410 (int)size);
411 if (size > 0) 411 if (size > 0)
412 {
413 nc = av->consumption_since_last_update__ + size;
414 if (nc < av->consumption_since_last_update__)
415 { 412 {
416 /* integer overflow, very bad */ 413 nc = av->consumption_since_last_update__ + size;
417 GNUNET_break (0); 414 if (nc < av->consumption_since_last_update__)
418 return GNUNET_SYSERR; 415 {
416 /* integer overflow, very bad */
417 GNUNET_break(0);
418 return GNUNET_SYSERR;
419 }
420 av->consumption_since_last_update__ = nc;
421 update_tracker(av);
422 update_excess(av);
423 if (av->consumption_since_last_update__ > 0)
424 {
425 LOG(GNUNET_ERROR_TYPE_DEBUG,
426 "Tracker %p consumption %llu bytes above limit\n",
427 av,
428 (unsigned long long)av->consumption_since_last_update__);
429 return GNUNET_YES;
430 }
419 } 431 }
420 av->consumption_since_last_update__ = nc;
421 update_tracker (av);
422 update_excess (av);
423 if (av->consumption_since_last_update__ > 0)
424 {
425 LOG (GNUNET_ERROR_TYPE_DEBUG,
426 "Tracker %p consumption %llu bytes above limit\n",
427 av,
428 (unsigned long long) av->consumption_since_last_update__);
429 return GNUNET_YES;
430 }
431 }
432 else 432 else
433 {
434 nc = av->consumption_since_last_update__ + size;
435 if (nc > av->consumption_since_last_update__)
436 { 433 {
437 /* integer underflow, very bad */ 434 nc = av->consumption_since_last_update__ + size;
438 GNUNET_break (0); 435 if (nc > av->consumption_since_last_update__)
439 return GNUNET_SYSERR; 436 {
437 /* integer underflow, very bad */
438 GNUNET_break(0);
439 return GNUNET_SYSERR;
440 }
441 av->consumption_since_last_update__ = nc;
442 update_excess(av);
440 } 443 }
441 av->consumption_since_last_update__ = nc;
442 update_excess (av);
443 }
444 return GNUNET_NO; 444 return GNUNET_NO;
445} 445}
446 446
@@ -455,34 +455,34 @@ GNUNET_BANDWIDTH_tracker_consume (struct GNUNET_BANDWIDTH_Tracker *av,
455 * @return time in ms to wait for consumption to be OK 455 * @return time in ms to wait for consumption to be OK
456 */ 456 */
457struct GNUNET_TIME_Relative 457struct GNUNET_TIME_Relative
458GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av, 458GNUNET_BANDWIDTH_tracker_get_delay(struct GNUNET_BANDWIDTH_Tracker *av,
459 size_t size) 459 size_t size)
460{ 460{
461 struct GNUNET_TIME_Relative ret; 461 struct GNUNET_TIME_Relative ret;
462 int64_t bytes_needed; 462 int64_t bytes_needed;
463 463
464 if (0 == av->available_bytes_per_s__) 464 if (0 == av->available_bytes_per_s__)
465 { 465 {
466 LOG (GNUNET_ERROR_TYPE_DEBUG, "Tracker %p delay is infinity\n", av); 466 LOG(GNUNET_ERROR_TYPE_DEBUG, "Tracker %p delay is infinity\n", av);
467 return GNUNET_TIME_UNIT_FOREVER_REL; 467 return GNUNET_TIME_UNIT_FOREVER_REL;
468 } 468 }
469 update_tracker (av); 469 update_tracker(av);
470 bytes_needed = size + av->consumption_since_last_update__; 470 bytes_needed = size + av->consumption_since_last_update__;
471 if (bytes_needed <= 0) 471 if (bytes_needed <= 0)
472 { 472 {
473 LOG (GNUNET_ERROR_TYPE_DEBUG, 473 LOG(GNUNET_ERROR_TYPE_DEBUG,
474 "Tracker %p delay for %u bytes is zero\n", 474 "Tracker %p delay for %u bytes is zero\n",
475 av, 475 av,
476 (unsigned int) size); 476 (unsigned int)size);
477 return GNUNET_TIME_UNIT_ZERO; 477 return GNUNET_TIME_UNIT_ZERO;
478 } 478 }
479 ret.rel_value_us = (1000LL * 1000LL * bytes_needed) / 479 ret.rel_value_us = (1000LL * 1000LL * bytes_needed) /
480 (unsigned long long) av->available_bytes_per_s__; 480 (unsigned long long)av->available_bytes_per_s__;
481 LOG (GNUNET_ERROR_TYPE_DEBUG, 481 LOG(GNUNET_ERROR_TYPE_DEBUG,
482 "Tracker %p delay for %u bytes is %s\n", 482 "Tracker %p delay for %u bytes is %s\n",
483 av, 483 av,
484 (unsigned int) size, 484 (unsigned int)size,
485 GNUNET_STRINGS_relative_time_to_string (ret, GNUNET_YES)); 485 GNUNET_STRINGS_relative_time_to_string(ret, GNUNET_YES));
486 return ret; 486 return ret;
487} 487}
488 488
@@ -495,24 +495,24 @@ GNUNET_BANDWIDTH_tracker_get_delay (struct GNUNET_BANDWIDTH_Tracker *av,
495 * @return number of bytes available for consumption right now 495 * @return number of bytes available for consumption right now
496 */ 496 */
497int64_t 497int64_t
498GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av) 498GNUNET_BANDWIDTH_tracker_get_available(struct GNUNET_BANDWIDTH_Tracker *av)
499{ 499{
500 struct GNUNET_BANDWIDTH_Value32NBO bps; 500 struct GNUNET_BANDWIDTH_Value32NBO bps;
501 uint64_t avail; 501 uint64_t avail;
502 int64_t used; 502 int64_t used;
503 503
504 update_tracker (av); 504 update_tracker(av);
505 bps = GNUNET_BANDWIDTH_value_init (av->available_bytes_per_s__); 505 bps = GNUNET_BANDWIDTH_value_init(av->available_bytes_per_s__);
506 avail = 506 avail =
507 GNUNET_BANDWIDTH_value_get_available_until (bps, 507 GNUNET_BANDWIDTH_value_get_available_until(bps,
508 GNUNET_TIME_absolute_get_duration ( 508 GNUNET_TIME_absolute_get_duration(
509 av->last_update__)); 509 av->last_update__));
510 used = av->consumption_since_last_update__; 510 used = av->consumption_since_last_update__;
511 LOG (GNUNET_ERROR_TYPE_DEBUG, 511 LOG(GNUNET_ERROR_TYPE_DEBUG,
512 "Tracker %p available bandwidth is %lld bytes\n", 512 "Tracker %p available bandwidth is %lld bytes\n",
513 av, 513 av,
514 (long long) (int64_t) (avail - used)); 514 (long long)(int64_t)(avail - used));
515 return (int64_t) (avail - used); 515 return (int64_t)(avail - used);
516} 516}
517 517
518 518
@@ -523,26 +523,26 @@ GNUNET_BANDWIDTH_tracker_get_available (struct GNUNET_BANDWIDTH_Tracker *av)
523 * @param bytes_per_second_limit new limit to assume 523 * @param bytes_per_second_limit new limit to assume
524 */ 524 */
525void 525void
526GNUNET_BANDWIDTH_tracker_update_quota ( 526GNUNET_BANDWIDTH_tracker_update_quota(
527 struct GNUNET_BANDWIDTH_Tracker *av, 527 struct GNUNET_BANDWIDTH_Tracker *av,
528 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit) 528 struct GNUNET_BANDWIDTH_Value32NBO bytes_per_second_limit)
529{ 529{
530 uint32_t old_limit; 530 uint32_t old_limit;
531 uint32_t new_limit; 531 uint32_t new_limit;
532 532
533 new_limit = ntohl (bytes_per_second_limit.value__); 533 new_limit = ntohl(bytes_per_second_limit.value__);
534 LOG (GNUNET_ERROR_TYPE_DEBUG, 534 LOG(GNUNET_ERROR_TYPE_DEBUG,
535 "Tracker %p bandwidth changed to %u Bps\n", 535 "Tracker %p bandwidth changed to %u Bps\n",
536 av, 536 av,
537 (unsigned int) new_limit); 537 (unsigned int)new_limit);
538 update_tracker (av); 538 update_tracker(av);
539 old_limit = av->available_bytes_per_s__; 539 old_limit = av->available_bytes_per_s__;
540 av->available_bytes_per_s__ = new_limit; 540 av->available_bytes_per_s__ = new_limit;
541 if (NULL != av->update_cb) 541 if (NULL != av->update_cb)
542 av->update_cb (av->update_cb_cls); 542 av->update_cb(av->update_cb_cls);
543 if (old_limit > new_limit) 543 if (old_limit > new_limit)
544 update_tracker (av); /* maximum excess might be less now */ 544 update_tracker(av); /* maximum excess might be less now */
545 update_excess (av); 545 update_excess(av);
546} 546}
547 547
548 548
diff --git a/src/util/benchmark.c b/src/util/benchmark.c
index caf6cd64a..c01b7a515 100644
--- a/src/util/benchmark.c
+++ b/src/util/benchmark.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/benchmark.c 22 * @file util/benchmark.c
@@ -47,109 +47,109 @@ static pthread_once_t key_once = PTHREAD_ONCE_INIT;
47 * @param bd the benchmark data 47 * @param bd the benchmark data
48 */ 48 */
49static void 49static void
50write_benchmark_data (struct BenchmarkData *bd) 50write_benchmark_data(struct BenchmarkData *bd)
51{ 51{
52 struct GNUNET_DISK_FileHandle *fh; 52 struct GNUNET_DISK_FileHandle *fh;
53 pid_t pid = getpid (); 53 pid_t pid = getpid();
54 pid_t tid = syscall (SYS_gettid); 54 pid_t tid = syscall(SYS_gettid);
55 char *benchmark_dir; 55 char *benchmark_dir;
56 char *s; 56 char *s;
57 57
58 benchmark_dir = getenv ("GNUNET_BENCHMARK_DIR"); 58 benchmark_dir = getenv("GNUNET_BENCHMARK_DIR");
59 59
60 if (NULL == benchmark_dir) 60 if (NULL == benchmark_dir)
61 return; 61 return;
62 62
63 if (GNUNET_OK != GNUNET_DISK_directory_create (benchmark_dir)) 63 if (GNUNET_OK != GNUNET_DISK_directory_create(benchmark_dir))
64 { 64 {
65 GNUNET_break (0); 65 GNUNET_break(0);
66 return; 66 return;
67 } 67 }
68 68
69 GNUNET_asprintf (&s, "%s/gnunet-benchmark-ops-%s-%llu-%llu.txt", 69 GNUNET_asprintf(&s, "%s/gnunet-benchmark-ops-%s-%llu-%llu.txt",
70 benchmark_dir, 70 benchmark_dir,
71 (pid == tid) ? "main" : "thread", 71 (pid == tid) ? "main" : "thread",
72 (unsigned long long) pid, 72 (unsigned long long)pid,
73 (unsigned long long) tid); 73 (unsigned long long)tid);
74 74
75 fh = GNUNET_DISK_file_open (s, 75 fh = GNUNET_DISK_file_open(s,
76 (GNUNET_DISK_OPEN_WRITE | 76 (GNUNET_DISK_OPEN_WRITE |
77 GNUNET_DISK_OPEN_TRUNCATE | 77 GNUNET_DISK_OPEN_TRUNCATE |
78 GNUNET_DISK_OPEN_CREATE), 78 GNUNET_DISK_OPEN_CREATE),
79 (GNUNET_DISK_PERM_USER_READ | 79 (GNUNET_DISK_PERM_USER_READ |
80 GNUNET_DISK_PERM_USER_WRITE)); 80 GNUNET_DISK_PERM_USER_WRITE));
81 GNUNET_assert (NULL != fh); 81 GNUNET_assert(NULL != fh);
82 GNUNET_free (s); 82 GNUNET_free(s);
83 83
84#define WRITE_BENCHMARK_OP(opname) do { \ 84#define WRITE_BENCHMARK_OP(opname) do { \
85 GNUNET_asprintf (&s, "op " #opname " count %llu time_us %llu\n", \ 85 GNUNET_asprintf(&s, "op " #opname " count %llu time_us %llu\n", \
86 (unsigned long long) bd->opname##_count, \ 86 (unsigned long long)bd->opname ## _count, \
87 (unsigned long long) bd->opname##_time.rel_value_us); \ 87 (unsigned long long)bd->opname ## _time.rel_value_us); \
88 GNUNET_assert (GNUNET_SYSERR != GNUNET_DISK_file_write_blocking (fh, s, strlen (s))); \ 88 GNUNET_assert(GNUNET_SYSERR != GNUNET_DISK_file_write_blocking(fh, s, strlen(s))); \
89 GNUNET_free (s); \ 89 GNUNET_free(s); \
90} while (0) 90 } while (0)
91 91
92 WRITE_BENCHMARK_OP (ecc_ecdh); 92 WRITE_BENCHMARK_OP(ecc_ecdh);
93 WRITE_BENCHMARK_OP (ecdh_eddsa); 93 WRITE_BENCHMARK_OP(ecdh_eddsa);
94 WRITE_BENCHMARK_OP (ecdhe_key_create); 94 WRITE_BENCHMARK_OP(ecdhe_key_create);
95 WRITE_BENCHMARK_OP (ecdhe_key_get_public); 95 WRITE_BENCHMARK_OP(ecdhe_key_get_public);
96 WRITE_BENCHMARK_OP (ecdsa_ecdh); 96 WRITE_BENCHMARK_OP(ecdsa_ecdh);
97 WRITE_BENCHMARK_OP (ecdsa_key_create); 97 WRITE_BENCHMARK_OP(ecdsa_key_create);
98 WRITE_BENCHMARK_OP (ecdsa_key_get_public); 98 WRITE_BENCHMARK_OP(ecdsa_key_get_public);
99 WRITE_BENCHMARK_OP (ecdsa_sign); 99 WRITE_BENCHMARK_OP(ecdsa_sign);
100 WRITE_BENCHMARK_OP (ecdsa_verify); 100 WRITE_BENCHMARK_OP(ecdsa_verify);
101 WRITE_BENCHMARK_OP (eddsa_ecdh); 101 WRITE_BENCHMARK_OP(eddsa_ecdh);
102 WRITE_BENCHMARK_OP (eddsa_key_create); 102 WRITE_BENCHMARK_OP(eddsa_key_create);
103 WRITE_BENCHMARK_OP (eddsa_key_get_public); 103 WRITE_BENCHMARK_OP(eddsa_key_get_public);
104 WRITE_BENCHMARK_OP (eddsa_sign); 104 WRITE_BENCHMARK_OP(eddsa_sign);
105 WRITE_BENCHMARK_OP (eddsa_verify); 105 WRITE_BENCHMARK_OP(eddsa_verify);
106 WRITE_BENCHMARK_OP (hash); 106 WRITE_BENCHMARK_OP(hash);
107 WRITE_BENCHMARK_OP (hash_context_finish); 107 WRITE_BENCHMARK_OP(hash_context_finish);
108 WRITE_BENCHMARK_OP (hash_context_read); 108 WRITE_BENCHMARK_OP(hash_context_read);
109 WRITE_BENCHMARK_OP (hash_context_start); 109 WRITE_BENCHMARK_OP(hash_context_start);
110 WRITE_BENCHMARK_OP (hkdf); 110 WRITE_BENCHMARK_OP(hkdf);
111 WRITE_BENCHMARK_OP (rsa_blind); 111 WRITE_BENCHMARK_OP(rsa_blind);
112 WRITE_BENCHMARK_OP (rsa_private_key_create); 112 WRITE_BENCHMARK_OP(rsa_private_key_create);
113 WRITE_BENCHMARK_OP (rsa_private_key_get_public); 113 WRITE_BENCHMARK_OP(rsa_private_key_get_public);
114 WRITE_BENCHMARK_OP (rsa_sign_blinded); 114 WRITE_BENCHMARK_OP(rsa_sign_blinded);
115 WRITE_BENCHMARK_OP (rsa_unblind); 115 WRITE_BENCHMARK_OP(rsa_unblind);
116 WRITE_BENCHMARK_OP (rsa_verify); 116 WRITE_BENCHMARK_OP(rsa_verify);
117 117
118#undef WRITE_BENCHMARK_OP 118#undef WRITE_BENCHMARK_OP
119 119
120 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); 120 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
121 121
122 GNUNET_asprintf (&s, "%s/gnunet-benchmark-urls-%s-%llu-%llu.txt", 122 GNUNET_asprintf(&s, "%s/gnunet-benchmark-urls-%s-%llu-%llu.txt",
123 benchmark_dir, 123 benchmark_dir,
124 (pid == tid) ? "main" : "thread", 124 (pid == tid) ? "main" : "thread",
125 (unsigned long long) pid, 125 (unsigned long long)pid,
126 (unsigned long long) tid); 126 (unsigned long long)tid);
127 127
128 fh = GNUNET_DISK_file_open (s, 128 fh = GNUNET_DISK_file_open(s,
129 (GNUNET_DISK_OPEN_WRITE | 129 (GNUNET_DISK_OPEN_WRITE |
130 GNUNET_DISK_OPEN_TRUNCATE | 130 GNUNET_DISK_OPEN_TRUNCATE |
131 GNUNET_DISK_OPEN_CREATE), 131 GNUNET_DISK_OPEN_CREATE),
132 (GNUNET_DISK_PERM_USER_READ | 132 (GNUNET_DISK_PERM_USER_READ |
133 GNUNET_DISK_PERM_USER_WRITE)); 133 GNUNET_DISK_PERM_USER_WRITE));
134 GNUNET_assert (NULL != fh); 134 GNUNET_assert(NULL != fh);
135 GNUNET_free (s); 135 GNUNET_free(s);
136 136
137 for (unsigned int i = 0; i < bd->urd_len; i++) 137 for (unsigned int i = 0; i < bd->urd_len; i++)
138 { 138 {
139 struct UrlRequestData *urd = &bd->urd[i]; 139 struct UrlRequestData *urd = &bd->urd[i];
140 GNUNET_asprintf (&s, "url %s status %u count %llu time_us %llu time_us_max %llu bytes_sent %llu bytes_received %llu\n", 140 GNUNET_asprintf(&s, "url %s status %u count %llu time_us %llu time_us_max %llu bytes_sent %llu bytes_received %llu\n",
141 urd->request_url, 141 urd->request_url,
142 urd->status, 142 urd->status,
143 (unsigned long long) urd->count, 143 (unsigned long long)urd->count,
144 (unsigned long long) urd->time.rel_value_us, 144 (unsigned long long)urd->time.rel_value_us,
145 (unsigned long long) urd->time_max.rel_value_us, 145 (unsigned long long)urd->time_max.rel_value_us,
146 (unsigned long long) urd->bytes_sent, 146 (unsigned long long)urd->bytes_sent,
147 (unsigned long long) urd->bytes_received); 147 (unsigned long long)urd->bytes_received);
148 GNUNET_assert (GNUNET_SYSERR != GNUNET_DISK_file_write_blocking (fh, s, strlen (s))); 148 GNUNET_assert(GNUNET_SYSERR != GNUNET_DISK_file_write_blocking(fh, s, strlen(s)));
149 GNUNET_free (s); 149 GNUNET_free(s);
150 } 150 }
151 151
152 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); 152 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
153} 153}
154 154
155 155
@@ -157,13 +157,13 @@ write_benchmark_data (struct BenchmarkData *bd)
157 * Called when the main thread exits and benchmark data for it was created. 157 * Called when the main thread exits and benchmark data for it was created.
158 */ 158 */
159static void 159static void
160main_thread_destructor () 160main_thread_destructor()
161{ 161{
162 struct BenchmarkData *bd; 162 struct BenchmarkData *bd;
163 163
164 bd = pthread_getspecific (key); 164 bd = pthread_getspecific(key);
165 if (NULL != bd) 165 if (NULL != bd)
166 write_benchmark_data (bd); 166 write_benchmark_data(bd);
167} 167}
168 168
169 169
@@ -173,16 +173,16 @@ main_thread_destructor ()
173 * @param cls closure 173 * @param cls closure
174 */ 174 */
175static void 175static void
176thread_destructor (void *cls) 176thread_destructor(void *cls)
177{ 177{
178 struct BenchmarkData *bd = cls; 178 struct BenchmarkData *bd = cls;
179 179
180 // main thread will be handled by atexit 180 // main thread will be handled by atexit
181 if (getpid () == (pid_t) syscall (SYS_gettid)) 181 if (getpid() == (pid_t)syscall(SYS_gettid))
182 return; 182 return;
183 183
184 GNUNET_assert (NULL != bd); 184 GNUNET_assert(NULL != bd);
185 write_benchmark_data (bd); 185 write_benchmark_data(bd);
186} 186}
187 187
188 188
@@ -190,9 +190,9 @@ thread_destructor (void *cls)
190 * Initialize the thread-local variable key for benchmark data. 190 * Initialize the thread-local variable key for benchmark data.
191 */ 191 */
192static void 192static void
193make_key () 193make_key()
194{ 194{
195 (void) pthread_key_create (&key, &thread_destructor); 195 (void)pthread_key_create(&key, &thread_destructor);
196} 196}
197 197
198 198
@@ -203,22 +203,22 @@ make_key ()
203 * @return benchmark data for the current thread 203 * @return benchmark data for the current thread
204 */ 204 */
205struct BenchmarkData * 205struct BenchmarkData *
206get_benchmark_data (void) 206get_benchmark_data(void)
207{ 207{
208 struct BenchmarkData *bd; 208 struct BenchmarkData *bd;
209 209
210 (void) pthread_once (&key_once, &make_key); 210 (void)pthread_once(&key_once, &make_key);
211 211
212 if (NULL == (bd = pthread_getspecific (key))) 212 if (NULL == (bd = pthread_getspecific(key)))
213 {
214 bd = GNUNET_new (struct BenchmarkData);
215 (void) pthread_setspecific (key, bd);
216 if (getpid () == (pid_t) syscall (SYS_gettid))
217 { 213 {
218 // We're the main thread! 214 bd = GNUNET_new(struct BenchmarkData);
219 atexit (main_thread_destructor); 215 (void)pthread_setspecific(key, bd);
216 if (getpid() == (pid_t)syscall(SYS_gettid))
217 {
218 // We're the main thread!
219 atexit(main_thread_destructor);
220 }
220 } 221 }
221 }
222 return bd; 222 return bd;
223} 223}
224 224
@@ -233,53 +233,53 @@ get_benchmark_data (void)
233 * @param status http status code 233 * @param status http status code
234 */ 234 */
235struct UrlRequestData * 235struct UrlRequestData *
236get_url_benchmark_data (char *url, unsigned int status) 236get_url_benchmark_data(char *url, unsigned int status)
237{ 237{
238 char trunc[MAX_BENCHMARK_URL_LEN]; 238 char trunc[MAX_BENCHMARK_URL_LEN];
239 struct BenchmarkData *bd; 239 struct BenchmarkData *bd;
240 240
241 if (NULL == url) 241 if (NULL == url)
242 { 242 {
243 /* Should not happen unless curl barfs */ 243 /* Should not happen unless curl barfs */
244 GNUNET_break (0); 244 GNUNET_break(0);
245 url = "<empty>"; 245 url = "<empty>";
246 } 246 }
247 247
248 memcpy (trunc, url, MAX_BENCHMARK_URL_LEN); 248 memcpy(trunc, url, MAX_BENCHMARK_URL_LEN);
249 trunc[MAX_BENCHMARK_URL_LEN - 1] = 0; 249 trunc[MAX_BENCHMARK_URL_LEN - 1] = 0;
250 250
251 /* We're not interested in what's after the query string */ 251 /* We're not interested in what's after the query string */
252 for (size_t i = 0; i < strlen (trunc); i++) 252 for (size_t i = 0; i < strlen(trunc); i++)
253 {
254 if (trunc[i] == '?')
255 { 253 {
256 trunc[i] = 0; 254 if (trunc[i] == '?')
257 break; 255 {
256 trunc[i] = 0;
257 break;
258 }
258 } 259 }
259 }
260 260
261 bd = get_benchmark_data (); 261 bd = get_benchmark_data();
262 262
263 GNUNET_assert (bd->urd_len <= bd->urd_capacity); 263 GNUNET_assert(bd->urd_len <= bd->urd_capacity);
264 264
265 for (unsigned int i = 0; i < bd->urd_len; i++) 265 for (unsigned int i = 0; i < bd->urd_len; i++)
266 { 266 {
267 if ( (0 == strcmp (trunc, bd->urd[i].request_url)) && 267 if ((0 == strcmp(trunc, bd->urd[i].request_url)) &&
268 (bd->urd[i].status == status) ) 268 (bd->urd[i].status == status))
269 return &bd->urd[i]; 269 return &bd->urd[i];
270 } 270 }
271 271
272 { 272 {
273 struct UrlRequestData urd = { 0 }; 273 struct UrlRequestData urd = { 0 };
274 274
275 memcpy (&urd.request_url, trunc, MAX_BENCHMARK_URL_LEN); 275 memcpy(&urd.request_url, trunc, MAX_BENCHMARK_URL_LEN);
276 urd.status = status; 276 urd.status = status;
277 277
278 if (bd->urd_len == bd->urd_capacity) 278 if (bd->urd_len == bd->urd_capacity)
279 { 279 {
280 bd->urd_capacity = 2 * (bd->urd_capacity + 1); 280 bd->urd_capacity = 2 * (bd->urd_capacity + 1);
281 bd->urd = GNUNET_realloc (bd->urd, bd->urd_capacity * sizeof (struct UrlRequestData)); 281 bd->urd = GNUNET_realloc(bd->urd, bd->urd_capacity * sizeof(struct UrlRequestData));
282 } 282 }
283 283
284 bd->urd[bd->urd_len++] = urd; 284 bd->urd[bd->urd_len++] = urd;
285 return &bd->urd[bd->urd_len - 1]; 285 return &bd->urd[bd->urd_len - 1];
diff --git a/src/util/benchmark.h b/src/util/benchmark.h
index 4148ac655..6816b47af 100644
--- a/src/util/benchmark.h
+++ b/src/util/benchmark.h
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/benchmark.h 22 * @file util/benchmark.h
@@ -37,18 +37,18 @@
37 37
38#if ENABLE_BENCHMARK 38#if ENABLE_BENCHMARK
39#define BENCHMARK_START(opname) \ 39#define BENCHMARK_START(opname) \
40 struct GNUNET_TIME_Absolute _benchmark_##opname##_start = GNUNET_TIME_absolute_get () 40 struct GNUNET_TIME_Absolute _benchmark_ ## opname ## _start = GNUNET_TIME_absolute_get()
41#define BENCHMARK_END(opname) do { \ 41#define BENCHMARK_END(opname) do { \
42 { \ 42 { \
43 struct GNUNET_TIME_Absolute _benchmark_##opname##_end = GNUNET_TIME_absolute_get (); \ 43 struct GNUNET_TIME_Absolute _benchmark_ ## opname ## _end = GNUNET_TIME_absolute_get(); \
44 struct BenchmarkData *bd = get_benchmark_data (); \ 44 struct BenchmarkData *bd = get_benchmark_data(); \
45 bd->opname##_count++; \ 45 bd->opname ## _count++; \
46 bd->opname##_time = \ 46 bd->opname ## _time = \
47 GNUNET_TIME_relative_add (bd->opname##_time, \ 47 GNUNET_TIME_relative_add(bd->opname ## _time, \
48 GNUNET_TIME_absolute_get_difference (_benchmark_##opname##_start, \ 48 GNUNET_TIME_absolute_get_difference(_benchmark_ ## opname ## _start, \
49 _benchmark_##opname##_end)); \ 49 _benchmark_ ## opname ## _end)); \
50 } \ 50 } \
51} while (0) 51 } while (0)
52#else 52#else
53#define BENCHMARK_START(opname) do { } while (0) 53#define BENCHMARK_START(opname) do { } while (0)
54#define BENCHMARK_END(opname) do { } while (0) 54#define BENCHMARK_END(opname) do { } while (0)
@@ -58,8 +58,7 @@
58/** 58/**
59 * Struct for benchmark data for one URL. 59 * Struct for benchmark data for one URL.
60 */ 60 */
61struct UrlRequestData 61struct UrlRequestData {
62{
63 /** 62 /**
64 * Request URL, truncated (but 0-terminated). 63 * Request URL, truncated (but 0-terminated).
65 */ 64 */
@@ -69,7 +68,7 @@ struct UrlRequestData
69 * HTTP status code. 68 * HTTP status code.
70 */ 69 */
71 unsigned int status; 70 unsigned int status;
72 71
73 /** 72 /**
74 * How often was the URL requested? 73 * How often was the URL requested?
75 */ 74 */
@@ -102,39 +101,38 @@ struct UrlRequestData
102}; 101};
103 102
104#define GNUNET_DECLARE_BENCHMARK_OP(opname) \ 103#define GNUNET_DECLARE_BENCHMARK_OP(opname) \
105 uint64_t opname##_count; \ 104 uint64_t opname ## _count; \
106 struct GNUNET_TIME_Relative opname##_time 105 struct GNUNET_TIME_Relative opname ## _time
107 106
108/** 107/**
109 * Thread-local struct for benchmarking data. 108 * Thread-local struct for benchmarking data.
110 */ 109 */
111struct BenchmarkData 110struct BenchmarkData {
112{ 111 GNUNET_DECLARE_BENCHMARK_OP(ecc_ecdh);
113 GNUNET_DECLARE_BENCHMARK_OP (ecc_ecdh); 112 GNUNET_DECLARE_BENCHMARK_OP(ecdh_eddsa);
114 GNUNET_DECLARE_BENCHMARK_OP (ecdh_eddsa); 113 GNUNET_DECLARE_BENCHMARK_OP(ecdhe_key_create);
115 GNUNET_DECLARE_BENCHMARK_OP (ecdhe_key_create); 114 GNUNET_DECLARE_BENCHMARK_OP(ecdhe_key_get_public);
116 GNUNET_DECLARE_BENCHMARK_OP (ecdhe_key_get_public); 115 GNUNET_DECLARE_BENCHMARK_OP(ecdsa_ecdh);
117 GNUNET_DECLARE_BENCHMARK_OP (ecdsa_ecdh); 116 GNUNET_DECLARE_BENCHMARK_OP(ecdsa_key_create);
118 GNUNET_DECLARE_BENCHMARK_OP (ecdsa_key_create); 117 GNUNET_DECLARE_BENCHMARK_OP(ecdsa_key_get_public);
119 GNUNET_DECLARE_BENCHMARK_OP (ecdsa_key_get_public); 118 GNUNET_DECLARE_BENCHMARK_OP(ecdsa_sign);
120 GNUNET_DECLARE_BENCHMARK_OP (ecdsa_sign); 119 GNUNET_DECLARE_BENCHMARK_OP(ecdsa_verify);
121 GNUNET_DECLARE_BENCHMARK_OP (ecdsa_verify); 120 GNUNET_DECLARE_BENCHMARK_OP(eddsa_ecdh);
122 GNUNET_DECLARE_BENCHMARK_OP (eddsa_ecdh); 121 GNUNET_DECLARE_BENCHMARK_OP(eddsa_key_create);
123 GNUNET_DECLARE_BENCHMARK_OP (eddsa_key_create); 122 GNUNET_DECLARE_BENCHMARK_OP(eddsa_key_get_public);
124 GNUNET_DECLARE_BENCHMARK_OP (eddsa_key_get_public); 123 GNUNET_DECLARE_BENCHMARK_OP(eddsa_sign);
125 GNUNET_DECLARE_BENCHMARK_OP (eddsa_sign); 124 GNUNET_DECLARE_BENCHMARK_OP(eddsa_verify);
126 GNUNET_DECLARE_BENCHMARK_OP (eddsa_verify); 125 GNUNET_DECLARE_BENCHMARK_OP(hash);
127 GNUNET_DECLARE_BENCHMARK_OP (hash); 126 GNUNET_DECLARE_BENCHMARK_OP(hash_context_finish);
128 GNUNET_DECLARE_BENCHMARK_OP (hash_context_finish); 127 GNUNET_DECLARE_BENCHMARK_OP(hash_context_read);
129 GNUNET_DECLARE_BENCHMARK_OP (hash_context_read); 128 GNUNET_DECLARE_BENCHMARK_OP(hash_context_start);
130 GNUNET_DECLARE_BENCHMARK_OP (hash_context_start); 129 GNUNET_DECLARE_BENCHMARK_OP(hkdf);
131 GNUNET_DECLARE_BENCHMARK_OP (hkdf); 130 GNUNET_DECLARE_BENCHMARK_OP(rsa_blind);
132 GNUNET_DECLARE_BENCHMARK_OP (rsa_blind); 131 GNUNET_DECLARE_BENCHMARK_OP(rsa_private_key_create);
133 GNUNET_DECLARE_BENCHMARK_OP (rsa_private_key_create); 132 GNUNET_DECLARE_BENCHMARK_OP(rsa_private_key_get_public);
134 GNUNET_DECLARE_BENCHMARK_OP (rsa_private_key_get_public); 133 GNUNET_DECLARE_BENCHMARK_OP(rsa_sign_blinded);
135 GNUNET_DECLARE_BENCHMARK_OP (rsa_sign_blinded); 134 GNUNET_DECLARE_BENCHMARK_OP(rsa_unblind);
136 GNUNET_DECLARE_BENCHMARK_OP (rsa_unblind); 135 GNUNET_DECLARE_BENCHMARK_OP(rsa_verify);
137 GNUNET_DECLARE_BENCHMARK_OP (rsa_verify);
138 136
139 struct UrlRequestData *urd; 137 struct UrlRequestData *urd;
140 138
@@ -153,7 +151,7 @@ struct BenchmarkData
153 * @return benchmark data for the current thread 151 * @return benchmark data for the current thread
154 */ 152 */
155struct BenchmarkData * 153struct BenchmarkData *
156get_benchmark_data (void); 154get_benchmark_data(void);
157 155
158/** 156/**
159 * Get benchmark data for a URL. If the URL is too long, it's truncated 157 * Get benchmark data for a URL. If the URL is too long, it's truncated
@@ -165,6 +163,6 @@ get_benchmark_data (void);
165 * @param status http status code 163 * @param status http status code
166 */ 164 */
167struct UrlRequestData * 165struct UrlRequestData *
168get_url_benchmark_data (char *url, unsigned int status); 166get_url_benchmark_data(char *url, unsigned int status);
169 167
170#endif /* BENCHMARK_H_ */ 168#endif /* BENCHMARK_H_ */
diff --git a/src/util/bio.c b/src/util/bio.c
index 1df249e40..5cbeee084 100644
--- a/src/util/bio.c
+++ b/src/util/bio.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/bio.c 21 * @file util/bio.c
22 * @brief functions for buffering IO 22 * @brief functions for buffering IO
@@ -25,7 +25,7 @@
25#include "platform.h" 25#include "platform.h"
26#include "gnunet_util_lib.h" 26#include "gnunet_util_lib.h"
27 27
28#define LOG(kind, ...) GNUNET_log_from (kind, "util-bio", __VA_ARGS__) 28#define LOG(kind, ...) GNUNET_log_from(kind, "util-bio", __VA_ARGS__)
29 29
30#ifndef PATH_MAX 30#ifndef PATH_MAX
31/** 31/**
@@ -50,8 +50,7 @@
50/** 50/**
51 * Handle for buffered reading. 51 * Handle for buffered reading.
52 */ 52 */
53struct GNUNET_BIO_ReadHandle 53struct GNUNET_BIO_ReadHandle {
54{
55 /** 54 /**
56 * Underlying file abstraction. 55 * Underlying file abstraction.
57 */ 56 */
@@ -91,16 +90,16 @@ struct GNUNET_BIO_ReadHandle
91 * @return IO handle on success, NULL on error 90 * @return IO handle on success, NULL on error
92 */ 91 */
93struct GNUNET_BIO_ReadHandle * 92struct GNUNET_BIO_ReadHandle *
94GNUNET_BIO_read_open (const char *fn) 93GNUNET_BIO_read_open(const char *fn)
95{ 94{
96 struct GNUNET_DISK_FileHandle *fd; 95 struct GNUNET_DISK_FileHandle *fd;
97 struct GNUNET_BIO_ReadHandle *h; 96 struct GNUNET_BIO_ReadHandle *h;
98 97
99 fd = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE); 98 fd = GNUNET_DISK_file_open(fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
100 if (NULL == fd) 99 if (NULL == fd)
101 return NULL; 100 return NULL;
102 h = GNUNET_malloc (sizeof (struct GNUNET_BIO_ReadHandle) + BIO_BUFFER_SIZE); 101 h = GNUNET_malloc(sizeof(struct GNUNET_BIO_ReadHandle) + BIO_BUFFER_SIZE);
103 h->buffer = (char *) &h[1]; 102 h->buffer = (char *)&h[1];
104 h->size = BIO_BUFFER_SIZE; 103 h->size = BIO_BUFFER_SIZE;
105 h->fd = fd; 104 h->fd = fd;
106 return h; 105 return h;
@@ -116,7 +115,7 @@ GNUNET_BIO_read_open (const char *fn)
116 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 115 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
117 */ 116 */
118int 117int
119GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg) 118GNUNET_BIO_read_close(struct GNUNET_BIO_ReadHandle *h, char **emsg)
120{ 119{
121 int err; 120 int err;
122 121
@@ -124,9 +123,9 @@ GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg)
124 if (emsg != NULL) 123 if (emsg != NULL)
125 *emsg = h->emsg; 124 *emsg = h->emsg;
126 else 125 else
127 GNUNET_free_non_null (h->emsg); 126 GNUNET_free_non_null(h->emsg);
128 GNUNET_DISK_file_close (h->fd); 127 GNUNET_DISK_file_close(h->fd);
129 GNUNET_free (h); 128 GNUNET_free(h);
130 return err; 129 return err;
131} 130}
132 131
@@ -141,10 +140,10 @@ GNUNET_BIO_read_close (struct GNUNET_BIO_ReadHandle *h, char **emsg)
141 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 140 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
142 */ 141 */
143int 142int
144GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h, 143GNUNET_BIO_read(struct GNUNET_BIO_ReadHandle *h,
145 const char *what, 144 const char *what,
146 void *result, 145 void *result,
147 size_t len) 146 size_t len)
148{ 147{
149 char *dst = result; 148 char *dst = result;
150 size_t min; 149 size_t min;
@@ -155,41 +154,42 @@ GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h,
155 return GNUNET_SYSERR; 154 return GNUNET_SYSERR;
156 pos = 0; 155 pos = 0;
157 do 156 do
158 {
159 /* first, use buffer */
160 min = h->have - h->pos;
161 if (min > 0)
162 {
163 if (min > len - pos)
164 min = len - pos;
165 GNUNET_memcpy (&dst[pos], &h->buffer[h->pos], min);
166 h->pos += min;
167 pos += min;
168 }
169 if (pos == len)
170 return GNUNET_OK; /* done! */
171 GNUNET_assert (((off_t) h->have) == h->pos);
172 /* fill buffer */
173 ret = GNUNET_DISK_file_read (h->fd, h->buffer, h->size);
174 if (-1 == ret)
175 {
176 GNUNET_asprintf (&h->emsg,
177 _ ("Error reading `%s': %s"),
178 what,
179 strerror (errno));
180 return GNUNET_SYSERR;
181 }
182 if (0 == ret)
183 { 157 {
184 GNUNET_asprintf (&h->emsg, 158 /* first, use buffer */
185 _ ("Error reading `%s': %s"), 159 min = h->have - h->pos;
186 what, 160 if (min > 0)
187 _ ("End of file")); 161 {
188 return GNUNET_SYSERR; 162 if (min > len - pos)
163 min = len - pos;
164 GNUNET_memcpy(&dst[pos], &h->buffer[h->pos], min);
165 h->pos += min;
166 pos += min;
167 }
168 if (pos == len)
169 return GNUNET_OK; /* done! */
170 GNUNET_assert(((off_t)h->have) == h->pos);
171 /* fill buffer */
172 ret = GNUNET_DISK_file_read(h->fd, h->buffer, h->size);
173 if (-1 == ret)
174 {
175 GNUNET_asprintf(&h->emsg,
176 _("Error reading `%s': %s"),
177 what,
178 strerror(errno));
179 return GNUNET_SYSERR;
180 }
181 if (0 == ret)
182 {
183 GNUNET_asprintf(&h->emsg,
184 _("Error reading `%s': %s"),
185 what,
186 _("End of file"));
187 return GNUNET_SYSERR;
188 }
189 h->pos = 0;
190 h->have = ret;
189 } 191 }
190 h->pos = 0; 192 while (pos < len); /* should always be true */
191 h->have = ret;
192 } while (pos < len); /* should always be true */
193 return GNUNET_OK; 193 return GNUNET_OK;
194} 194}
195 195
@@ -205,16 +205,16 @@ GNUNET_BIO_read (struct GNUNET_BIO_ReadHandle *h,
205 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 205 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
206 */ 206 */
207int 207int
208GNUNET_BIO_read_fn (struct GNUNET_BIO_ReadHandle *h, 208GNUNET_BIO_read_fn(struct GNUNET_BIO_ReadHandle *h,
209 const char *file, 209 const char *file,
210 int line, 210 int line,
211 void *result, 211 void *result,
212 size_t len) 212 size_t len)
213{ 213{
214 char what[PATH_MAX + 1024]; 214 char what[PATH_MAX + 1024];
215 215
216 GNUNET_snprintf (what, sizeof (what), "%s:%d", file, line); 216 GNUNET_snprintf(what, sizeof(what), "%s:%d", file, line);
217 return GNUNET_BIO_read (h, what, result, len); 217 return GNUNET_BIO_read(h, what, result, len);
218} 218}
219 219
220 220
@@ -229,45 +229,45 @@ GNUNET_BIO_read_fn (struct GNUNET_BIO_ReadHandle *h,
229 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 229 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
230 */ 230 */
231int 231int
232GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h, 232GNUNET_BIO_read_string(struct GNUNET_BIO_ReadHandle *h,
233 const char *what, 233 const char *what,
234 char **result, 234 char **result,
235 size_t max_length) 235 size_t max_length)
236{ 236{
237 char *buf; 237 char *buf;
238 uint32_t big; 238 uint32_t big;
239 239
240 if (GNUNET_OK != GNUNET_BIO_read_int32 (h, &big)) 240 if (GNUNET_OK != GNUNET_BIO_read_int32(h, &big))
241 { 241 {
242 GNUNET_free_non_null (h->emsg); 242 GNUNET_free_non_null(h->emsg);
243 GNUNET_asprintf (&h->emsg, _ ("Error reading length of string `%s'"), what); 243 GNUNET_asprintf(&h->emsg, _("Error reading length of string `%s'"), what);
244 return GNUNET_SYSERR; 244 return GNUNET_SYSERR;
245 } 245 }
246 if (0 == big) 246 if (0 == big)
247 { 247 {
248 *result = NULL; 248 *result = NULL;
249 return GNUNET_OK; 249 return GNUNET_OK;
250 } 250 }
251 if (big > max_length) 251 if (big > max_length)
252 { 252 {
253 GNUNET_asprintf (&h->emsg, 253 GNUNET_asprintf(&h->emsg,
254 _ ("String `%s' longer than allowed (%u > %u)"), 254 _("String `%s' longer than allowed (%u > %u)"),
255 what, 255 what,
256 big, 256 big,
257 max_length); 257 max_length);
258 return GNUNET_SYSERR; 258 return GNUNET_SYSERR;
259 } 259 }
260 buf = GNUNET_malloc (big); 260 buf = GNUNET_malloc(big);
261 *result = buf; 261 *result = buf;
262 buf[--big] = '\0'; 262 buf[--big] = '\0';
263 if (0 == big) 263 if (0 == big)
264 return GNUNET_OK; 264 return GNUNET_OK;
265 if (GNUNET_OK != GNUNET_BIO_read (h, what, buf, big)) 265 if (GNUNET_OK != GNUNET_BIO_read(h, what, buf, big))
266 { 266 {
267 GNUNET_free (buf); 267 GNUNET_free(buf);
268 *result = NULL; 268 *result = NULL;
269 return GNUNET_SYSERR; 269 return GNUNET_SYSERR;
270 } 270 }
271 return GNUNET_OK; 271 return GNUNET_OK;
272} 272}
273 273
@@ -281,44 +281,44 @@ GNUNET_BIO_read_string (struct GNUNET_BIO_ReadHandle *h,
281 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 281 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
282 */ 282 */
283int 283int
284GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h, 284GNUNET_BIO_read_meta_data(struct GNUNET_BIO_ReadHandle *h,
285 const char *what, 285 const char *what,
286 struct GNUNET_CONTAINER_MetaData **result) 286 struct GNUNET_CONTAINER_MetaData **result)
287{ 287{
288 uint32_t size; 288 uint32_t size;
289 char *buf; 289 char *buf;
290 struct GNUNET_CONTAINER_MetaData *meta; 290 struct GNUNET_CONTAINER_MetaData *meta;
291 291
292 if (GNUNET_OK != GNUNET_BIO_read_int32 (h, (int32_t *) &size)) 292 if (GNUNET_OK != GNUNET_BIO_read_int32(h, (int32_t *)&size))
293 return GNUNET_SYSERR; 293 return GNUNET_SYSERR;
294 if (size == 0) 294 if (size == 0)
295 { 295 {
296 *result = NULL; 296 *result = NULL;
297 return GNUNET_OK; 297 return GNUNET_OK;
298 } 298 }
299 if (size > MAX_META_DATA) 299 if (size > MAX_META_DATA)
300 { 300 {
301 GNUNET_asprintf (&h->emsg, 301 GNUNET_asprintf(&h->emsg,
302 _ ("Serialized metadata `%s' larger than allowed (%u>%u)"), 302 _("Serialized metadata `%s' larger than allowed (%u>%u)"),
303 what, 303 what,
304 size, 304 size,
305 MAX_META_DATA); 305 MAX_META_DATA);
306 return GNUNET_SYSERR; 306 return GNUNET_SYSERR;
307 } 307 }
308 buf = GNUNET_malloc (size); 308 buf = GNUNET_malloc(size);
309 if (GNUNET_OK != GNUNET_BIO_read (h, what, buf, size)) 309 if (GNUNET_OK != GNUNET_BIO_read(h, what, buf, size))
310 { 310 {
311 GNUNET_free (buf); 311 GNUNET_free(buf);
312 return GNUNET_SYSERR; 312 return GNUNET_SYSERR;
313 } 313 }
314 meta = GNUNET_CONTAINER_meta_data_deserialize (buf, size); 314 meta = GNUNET_CONTAINER_meta_data_deserialize(buf, size);
315 if (NULL == meta) 315 if (NULL == meta)
316 { 316 {
317 GNUNET_free (buf); 317 GNUNET_free(buf);
318 GNUNET_asprintf (&h->emsg, _ ("Metadata `%s' failed to deserialize"), what); 318 GNUNET_asprintf(&h->emsg, _("Metadata `%s' failed to deserialize"), what);
319 return GNUNET_SYSERR; 319 return GNUNET_SYSERR;
320 } 320 }
321 GNUNET_free (buf); 321 GNUNET_free(buf);
322 *result = meta; 322 *result = meta;
323 return GNUNET_OK; 323 return GNUNET_OK;
324} 324}
@@ -334,16 +334,16 @@ GNUNET_BIO_read_meta_data (struct GNUNET_BIO_ReadHandle *h,
334 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 334 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
335 */ 335 */
336int 336int
337GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h, 337GNUNET_BIO_read_int32__(struct GNUNET_BIO_ReadHandle *h,
338 const char *file, 338 const char *file,
339 int line, 339 int line,
340 int32_t *i) 340 int32_t *i)
341{ 341{
342 int32_t big; 342 int32_t big;
343 343
344 if (GNUNET_OK != GNUNET_BIO_read_fn (h, file, line, &big, sizeof (int32_t))) 344 if (GNUNET_OK != GNUNET_BIO_read_fn(h, file, line, &big, sizeof(int32_t)))
345 return GNUNET_SYSERR; 345 return GNUNET_SYSERR;
346 *i = ntohl (big); 346 *i = ntohl(big);
347 return GNUNET_OK; 347 return GNUNET_OK;
348} 348}
349 349
@@ -358,16 +358,16 @@ GNUNET_BIO_read_int32__ (struct GNUNET_BIO_ReadHandle *h,
358 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 358 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
359 */ 359 */
360int 360int
361GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h, 361GNUNET_BIO_read_int64__(struct GNUNET_BIO_ReadHandle *h,
362 const char *file, 362 const char *file,
363 int line, 363 int line,
364 int64_t *i) 364 int64_t *i)
365{ 365{
366 int64_t big; 366 int64_t big;
367 367
368 if (GNUNET_OK != GNUNET_BIO_read_fn (h, file, line, &big, sizeof (int64_t))) 368 if (GNUNET_OK != GNUNET_BIO_read_fn(h, file, line, &big, sizeof(int64_t)))
369 return GNUNET_SYSERR; 369 return GNUNET_SYSERR;
370 *i = GNUNET_ntohll (big); 370 *i = GNUNET_ntohll(big);
371 return GNUNET_OK; 371 return GNUNET_OK;
372} 372}
373 373
@@ -375,8 +375,7 @@ GNUNET_BIO_read_int64__ (struct GNUNET_BIO_ReadHandle *h,
375/** 375/**
376 * Handle for buffered writing. 376 * Handle for buffered writing.
377 */ 377 */
378struct GNUNET_BIO_WriteHandle 378struct GNUNET_BIO_WriteHandle {
379{
380 /** 379 /**
381 * Underlying file handle. 380 * Underlying file handle.
382 */ 381 */
@@ -406,21 +405,21 @@ struct GNUNET_BIO_WriteHandle
406 * @return IO handle on success, NULL on error 405 * @return IO handle on success, NULL on error
407 */ 406 */
408struct GNUNET_BIO_WriteHandle * 407struct GNUNET_BIO_WriteHandle *
409GNUNET_BIO_write_open (const char *fn) 408GNUNET_BIO_write_open(const char *fn)
410{ 409{
411 struct GNUNET_DISK_FileHandle *fd; 410 struct GNUNET_DISK_FileHandle *fd;
412 struct GNUNET_BIO_WriteHandle *h; 411 struct GNUNET_BIO_WriteHandle *h;
413 412
414 fd = 413 fd =
415 GNUNET_DISK_file_open (fn, 414 GNUNET_DISK_file_open(fn,
416 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | 415 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE |
417 GNUNET_DISK_OPEN_CREATE, 416 GNUNET_DISK_OPEN_CREATE,
418 GNUNET_DISK_PERM_USER_READ | 417 GNUNET_DISK_PERM_USER_READ |
419 GNUNET_DISK_PERM_USER_WRITE); 418 GNUNET_DISK_PERM_USER_WRITE);
420 if (NULL == fd) 419 if (NULL == fd)
421 return NULL; 420 return NULL;
422 h = GNUNET_malloc (sizeof (struct GNUNET_BIO_WriteHandle) + BIO_BUFFER_SIZE); 421 h = GNUNET_malloc(sizeof(struct GNUNET_BIO_WriteHandle) + BIO_BUFFER_SIZE);
423 h->buffer = (char *) &h[1]; 422 h->buffer = (char *)&h[1];
424 h->size = BIO_BUFFER_SIZE; 423 h->size = BIO_BUFFER_SIZE;
425 h->fd = fd; 424 h->fd = fd;
426 return h; 425 return h;
@@ -434,14 +433,14 @@ GNUNET_BIO_write_open (const char *fn)
434 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 433 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
435 */ 434 */
436int 435int
437GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h) 436GNUNET_BIO_write_close(struct GNUNET_BIO_WriteHandle *h)
438{ 437{
439 int ret; 438 int ret;
440 439
441 ret = GNUNET_SYSERR; 440 ret = GNUNET_SYSERR;
442 if ((NULL != h->fd) && (GNUNET_OK == (ret = GNUNET_BIO_flush (h)))) 441 if ((NULL != h->fd) && (GNUNET_OK == (ret = GNUNET_BIO_flush(h))))
443 GNUNET_DISK_file_close (h->fd); 442 GNUNET_DISK_file_close(h->fd);
444 GNUNET_free (h); 443 GNUNET_free(h);
445 return ret; 444 return ret;
446} 445}
447 446
@@ -454,17 +453,17 @@ GNUNET_BIO_write_close (struct GNUNET_BIO_WriteHandle *h)
454 * the file is closed 453 * the file is closed
455 */ 454 */
456int 455int
457GNUNET_BIO_flush (struct GNUNET_BIO_WriteHandle *h) 456GNUNET_BIO_flush(struct GNUNET_BIO_WriteHandle *h)
458{ 457{
459 ssize_t ret; 458 ssize_t ret;
460 459
461 ret = GNUNET_DISK_file_write (h->fd, h->buffer, h->have); 460 ret = GNUNET_DISK_file_write(h->fd, h->buffer, h->have);
462 if (ret != (ssize_t) h->have) 461 if (ret != (ssize_t)h->have)
463 { 462 {
464 GNUNET_DISK_file_close (h->fd); 463 GNUNET_DISK_file_close(h->fd);
465 h->fd = NULL; 464 h->fd = NULL;
466 return GNUNET_SYSERR; /* error */ 465 return GNUNET_SYSERR; /* error */
467 } 466 }
468 h->have = 0; 467 h->have = 0;
469 return GNUNET_OK; 468 return GNUNET_OK;
470} 469}
@@ -479,9 +478,9 @@ GNUNET_BIO_flush (struct GNUNET_BIO_WriteHandle *h)
479 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 478 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
480 */ 479 */
481int 480int
482GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h, 481GNUNET_BIO_write(struct GNUNET_BIO_WriteHandle *h,
483 const void *buffer, 482 const void *buffer,
484 size_t n) 483 size_t n)
485{ 484{
486 const char *src = buffer; 485 const char *src = buffer;
487 size_t min; 486 size_t min;
@@ -491,21 +490,22 @@ GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h,
491 return GNUNET_SYSERR; 490 return GNUNET_SYSERR;
492 pos = 0; 491 pos = 0;
493 do 492 do
494 { 493 {
495 /* first, just use buffer */ 494 /* first, just use buffer */
496 min = h->size - h->have; 495 min = h->size - h->have;
497 if (min > n - pos) 496 if (min > n - pos)
498 min = n - pos; 497 min = n - pos;
499 GNUNET_memcpy (&h->buffer[h->have], &src[pos], min); 498 GNUNET_memcpy(&h->buffer[h->have], &src[pos], min);
500 pos += min; 499 pos += min;
501 h->have += min; 500 h->have += min;
502 if (pos == n) 501 if (pos == n)
503 return GNUNET_OK; /* done */ 502 return GNUNET_OK; /* done */
504 GNUNET_assert (h->have == h->size); 503 GNUNET_assert(h->have == h->size);
505 if (GNUNET_OK != GNUNET_BIO_flush (h)) 504 if (GNUNET_OK != GNUNET_BIO_flush(h))
506 return GNUNET_SYSERR; /* error */ 505 return GNUNET_SYSERR; /* error */
507 } while (pos < n); /* should always be true */ 506 }
508 GNUNET_break (0); 507 while (pos < n); /* should always be true */
508 GNUNET_break(0);
509 return GNUNET_OK; 509 return GNUNET_OK;
510} 510}
511 511
@@ -518,15 +518,15 @@ GNUNET_BIO_write (struct GNUNET_BIO_WriteHandle *h,
518 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 518 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
519 */ 519 */
520int 520int
521GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h, const char *s) 521GNUNET_BIO_write_string(struct GNUNET_BIO_WriteHandle *h, const char *s)
522{ 522{
523 uint32_t slen; 523 uint32_t slen;
524 524
525 slen = (uint32_t) ((s == NULL) ? 0 : strlen (s) + 1); 525 slen = (uint32_t)((s == NULL) ? 0 : strlen(s) + 1);
526 if (GNUNET_OK != GNUNET_BIO_write_int32 (h, slen)) 526 if (GNUNET_OK != GNUNET_BIO_write_int32(h, slen))
527 return GNUNET_SYSERR; 527 return GNUNET_SYSERR;
528 if (0 != slen) 528 if (0 != slen)
529 return GNUNET_BIO_write (h, s, slen - 1); 529 return GNUNET_BIO_write(h, s, slen - 1);
530 return GNUNET_OK; 530 return GNUNET_OK;
531} 531}
532 532
@@ -539,32 +539,32 @@ GNUNET_BIO_write_string (struct GNUNET_BIO_WriteHandle *h, const char *s)
539 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 539 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
540 */ 540 */
541int 541int
542GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h, 542GNUNET_BIO_write_meta_data(struct GNUNET_BIO_WriteHandle *h,
543 const struct GNUNET_CONTAINER_MetaData *m) 543 const struct GNUNET_CONTAINER_MetaData *m)
544{ 544{
545 ssize_t size; 545 ssize_t size;
546 char *buf; 546 char *buf;
547 547
548 if (m == NULL) 548 if (m == NULL)
549 return GNUNET_BIO_write_int32 (h, 0); 549 return GNUNET_BIO_write_int32(h, 0);
550 buf = NULL; 550 buf = NULL;
551 size = GNUNET_CONTAINER_meta_data_serialize ( 551 size = GNUNET_CONTAINER_meta_data_serialize(
552 m, 552 m,
553 &buf, 553 &buf,
554 MAX_META_DATA, 554 MAX_META_DATA,
555 GNUNET_CONTAINER_META_DATA_SERIALIZE_PART); 555 GNUNET_CONTAINER_META_DATA_SERIALIZE_PART);
556 if (size == -1) 556 if (size == -1)
557 { 557 {
558 GNUNET_free (buf); 558 GNUNET_free(buf);
559 return GNUNET_SYSERR; 559 return GNUNET_SYSERR;
560 } 560 }
561 if ((GNUNET_OK != GNUNET_BIO_write_int32 (h, (uint32_t) size)) || 561 if ((GNUNET_OK != GNUNET_BIO_write_int32(h, (uint32_t)size)) ||
562 (GNUNET_OK != GNUNET_BIO_write (h, buf, size))) 562 (GNUNET_OK != GNUNET_BIO_write(h, buf, size)))
563 { 563 {
564 GNUNET_free (buf); 564 GNUNET_free(buf);
565 return GNUNET_SYSERR; 565 return GNUNET_SYSERR;
566 } 566 }
567 GNUNET_free (buf); 567 GNUNET_free(buf);
568 return GNUNET_OK; 568 return GNUNET_OK;
569} 569}
570 570
@@ -577,12 +577,12 @@ GNUNET_BIO_write_meta_data (struct GNUNET_BIO_WriteHandle *h,
577 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 577 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
578 */ 578 */
579int 579int
580GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h, int32_t i) 580GNUNET_BIO_write_int32(struct GNUNET_BIO_WriteHandle *h, int32_t i)
581{ 581{
582 int32_t big; 582 int32_t big;
583 583
584 big = htonl (i); 584 big = htonl(i);
585 return GNUNET_BIO_write (h, &big, sizeof (int32_t)); 585 return GNUNET_BIO_write(h, &big, sizeof(int32_t));
586} 586}
587 587
588 588
@@ -594,12 +594,12 @@ GNUNET_BIO_write_int32 (struct GNUNET_BIO_WriteHandle *h, int32_t i)
594 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 594 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
595 */ 595 */
596int 596int
597GNUNET_BIO_write_int64 (struct GNUNET_BIO_WriteHandle *h, int64_t i) 597GNUNET_BIO_write_int64(struct GNUNET_BIO_WriteHandle *h, int64_t i)
598{ 598{
599 int64_t big; 599 int64_t big;
600 600
601 big = GNUNET_htonll (i); 601 big = GNUNET_htonll(i);
602 return GNUNET_BIO_write (h, &big, sizeof (int64_t)); 602 return GNUNET_BIO_write(h, &big, sizeof(int64_t));
603} 603}
604 604
605 605
diff --git a/src/util/client.c b/src/util/client.c
index 313cc23af..e3585af2e 100644
--- a/src/util/client.c
+++ b/src/util/client.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/client.c 22 * @file util/client.c
@@ -33,7 +33,7 @@
33#include "gnunet_socks.h" 33#include "gnunet_socks.h"
34 34
35 35
36#define LOG(kind,...) GNUNET_log_from (kind, "util-client",__VA_ARGS__) 36#define LOG(kind, ...) GNUNET_log_from(kind, "util-client", __VA_ARGS__)
37 37
38/** 38/**
39 * Timeout we use on TCP connect before trying another 39 * Timeout we use on TCP connect before trying another
@@ -41,7 +41,7 @@
41 * is this value divided by the number of address families. 41 * is this value divided by the number of address families.
42 * Default is 5s. 42 * Default is 5s.
43 */ 43 */
44#define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) 44#define CONNECT_RETRY_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
45 45
46 46
47 47
@@ -55,9 +55,7 @@ struct ClientState;
55 * During connect, we try multiple possible IP addresses 55 * During connect, we try multiple possible IP addresses
56 * to find out which one might work. 56 * to find out which one might work.
57 */ 57 */
58struct AddressProbe 58struct AddressProbe {
59{
60
61 /** 59 /**
62 * This is a linked list. 60 * This is a linked list.
63 */ 61 */
@@ -98,9 +96,7 @@ struct AddressProbe
98/** 96/**
99 * Internal state for a client connected to a GNUnet service. 97 * Internal state for a client connected to a GNUnet service.
100 */ 98 */
101struct ClientState 99struct ClientState {
102{
103
104 /** 100 /**
105 * The connection handle, NULL if not live 101 * The connection handle, NULL if not live
106 */ 102 */
@@ -200,7 +196,6 @@ struct ClientState
200 * deferred. 196 * deferred.
201 */ 197 */
202 int in_destroy; 198 int in_destroy;
203
204}; 199};
205 200
206 201
@@ -210,7 +205,7 @@ struct ClientState
210 * @param cls the `struct ClientState` to try to connect to the service 205 * @param cls the `struct ClientState` to try to connect to the service
211 */ 206 */
212static void 207static void
213start_connect (void *cls); 208start_connect(void *cls);
214 209
215 210
216/** 211/**
@@ -220,26 +215,26 @@ start_connect (void *cls);
220 * @param cstate the connection we tried to establish 215 * @param cstate the connection we tried to establish
221 */ 216 */
222static void 217static void
223connect_fail_continuation (struct ClientState *cstate) 218connect_fail_continuation(struct ClientState *cstate)
224{ 219{
225 GNUNET_break (NULL == cstate->ap_head); 220 GNUNET_break(NULL == cstate->ap_head);
226 GNUNET_break (NULL == cstate->ap_tail); 221 GNUNET_break(NULL == cstate->ap_tail);
227 GNUNET_break (NULL == cstate->dns_active); 222 GNUNET_break(NULL == cstate->dns_active);
228 GNUNET_break (NULL == cstate->sock); 223 GNUNET_break(NULL == cstate->sock);
229 GNUNET_assert (NULL == cstate->send_task); 224 GNUNET_assert(NULL == cstate->send_task);
230 GNUNET_assert (NULL == cstate->recv_task); 225 GNUNET_assert(NULL == cstate->recv_task);
231 // GNUNET_assert (NULL == cstate->proxy_handshake); 226 // GNUNET_assert (NULL == cstate->proxy_handshake);
232 227
233 cstate->back_off = GNUNET_TIME_STD_BACKOFF (cstate->back_off); 228 cstate->back_off = GNUNET_TIME_STD_BACKOFF(cstate->back_off);
234 LOG (GNUNET_ERROR_TYPE_DEBUG, 229 LOG(GNUNET_ERROR_TYPE_DEBUG,
235 "Failed to establish connection to `%s', no further addresses to try, will try again in %s.\n", 230 "Failed to establish connection to `%s', no further addresses to try, will try again in %s.\n",
236 cstate->service_name, 231 cstate->service_name,
237 GNUNET_STRINGS_relative_time_to_string (cstate->back_off, 232 GNUNET_STRINGS_relative_time_to_string(cstate->back_off,
238 GNUNET_YES)); 233 GNUNET_YES));
239 cstate->retry_task 234 cstate->retry_task
240 = GNUNET_SCHEDULER_add_delayed (cstate->back_off, 235 = GNUNET_SCHEDULER_add_delayed(cstate->back_off,
241 &start_connect, 236 &start_connect,
242 cstate); 237 cstate);
243} 238}
244 239
245 240
@@ -249,7 +244,7 @@ connect_fail_continuation (struct ClientState *cstate)
249 * @param cls the `struct ClientState` with the `msg` to transmit 244 * @param cls the `struct ClientState` with the `msg` to transmit
250 */ 245 */
251static void 246static void
252transmit_ready (void *cls) 247transmit_ready(void *cls)
253{ 248{
254 struct ClientState *cstate = cls; 249 struct ClientState *cstate = cls;
255 ssize_t ret; 250 ssize_t ret;
@@ -260,55 +255,56 @@ transmit_ready (void *cls)
260 cstate->send_task = NULL; 255 cstate->send_task = NULL;
261 if (GNUNET_YES == cstate->in_destroy) 256 if (GNUNET_YES == cstate->in_destroy)
262 return; 257 return;
263 pos = (const char *) cstate->msg; 258 pos = (const char *)cstate->msg;
264 len = ntohs (cstate->msg->size); 259 len = ntohs(cstate->msg->size);
265 GNUNET_assert (cstate->msg_off < len); 260 GNUNET_assert(cstate->msg_off < len);
266 LOG (GNUNET_ERROR_TYPE_DEBUG, 261 LOG(GNUNET_ERROR_TYPE_DEBUG,
267 "message of type %u trying to send with socket %p (MQ: %p\n", 262 "message of type %u trying to send with socket %p (MQ: %p\n",
268 ntohs(cstate->msg->type), 263 ntohs(cstate->msg->type),
269 cstate->sock, 264 cstate->sock,
270 cstate->mq); 265 cstate->mq);
271 266
272 RETRY: 267RETRY:
273 ret = GNUNET_NETWORK_socket_send (cstate->sock, 268 ret = GNUNET_NETWORK_socket_send(cstate->sock,
274 &pos[cstate->msg_off], 269 &pos[cstate->msg_off],
275 len - cstate->msg_off); 270 len - cstate->msg_off);
276 if (-1 == ret) 271 if (-1 == ret)
277 { 272 {
278 LOG (GNUNET_ERROR_TYPE_WARNING, 273 LOG(GNUNET_ERROR_TYPE_WARNING,
279 "Error during sending message of type %u\n", 274 "Error during sending message of type %u\n",
280 ntohs(cstate->msg->type)); 275 ntohs(cstate->msg->type));
281 if (EINTR == errno){ 276 if (EINTR == errno)
282 LOG (GNUNET_ERROR_TYPE_DEBUG, 277 {
283 "Retrying message of type %u\n", 278 LOG(GNUNET_ERROR_TYPE_DEBUG,
284 ntohs(cstate->msg->type)); 279 "Retrying message of type %u\n",
285 goto RETRY; 280 ntohs(cstate->msg->type));
281 goto RETRY;
282 }
283 GNUNET_MQ_inject_error(cstate->mq,
284 GNUNET_MQ_ERROR_WRITE);
285 return;
286 } 286 }
287 GNUNET_MQ_inject_error (cstate->mq,
288 GNUNET_MQ_ERROR_WRITE);
289 return;
290 }
291 notify_in_flight = (0 == cstate->msg_off); 287 notify_in_flight = (0 == cstate->msg_off);
292 cstate->msg_off += ret; 288 cstate->msg_off += ret;
293 if (cstate->msg_off < len) 289 if (cstate->msg_off < len)
294 { 290 {
295 LOG (GNUNET_ERROR_TYPE_DEBUG, 291 LOG(GNUNET_ERROR_TYPE_DEBUG,
296 "rescheduling message of type %u\n", 292 "rescheduling message of type %u\n",
297 ntohs(cstate->msg->type)); 293 ntohs(cstate->msg->type));
298 cstate->send_task 294 cstate->send_task
299 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, 295 = GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
300 cstate->sock, 296 cstate->sock,
301 &transmit_ready, 297 &transmit_ready,
302 cstate); 298 cstate);
303 if (notify_in_flight) 299 if (notify_in_flight)
304 GNUNET_MQ_impl_send_in_flight (cstate->mq); 300 GNUNET_MQ_impl_send_in_flight(cstate->mq);
305 return; 301 return;
306 } 302 }
307 LOG (GNUNET_ERROR_TYPE_DEBUG, 303 LOG(GNUNET_ERROR_TYPE_DEBUG,
308 "sending message of type %u successful\n", 304 "sending message of type %u successful\n",
309 ntohs(cstate->msg->type)); 305 ntohs(cstate->msg->type));
310 cstate->msg = NULL; 306 cstate->msg = NULL;
311 GNUNET_MQ_impl_send_continue (cstate->mq); 307 GNUNET_MQ_impl_send_continue(cstate->mq);
312} 308}
313 309
314 310
@@ -323,20 +319,20 @@ transmit_ready (void *cls)
323 * #GNUNET_SYSERR to stop further processing due to error 319 * #GNUNET_SYSERR to stop further processing due to error
324 */ 320 */
325static int 321static int
326recv_message (void *cls, 322recv_message(void *cls,
327 const struct GNUNET_MessageHeader *msg) 323 const struct GNUNET_MessageHeader *msg)
328{ 324{
329 struct ClientState *cstate = cls; 325 struct ClientState *cstate = cls;
330 326
331 if (GNUNET_YES == cstate->in_destroy) 327 if (GNUNET_YES == cstate->in_destroy)
332 return GNUNET_NO; 328 return GNUNET_NO;
333 LOG (GNUNET_ERROR_TYPE_DEBUG, 329 LOG(GNUNET_ERROR_TYPE_DEBUG,
334 "Received message of type %u and size %u from %s\n", 330 "Received message of type %u and size %u from %s\n",
335 ntohs (msg->type), 331 ntohs(msg->type),
336 ntohs (msg->size), 332 ntohs(msg->size),
337 cstate->service_name); 333 cstate->service_name);
338 GNUNET_MQ_inject_message (cstate->mq, 334 GNUNET_MQ_inject_message(cstate->mq,
339 msg); 335 msg);
340 if (GNUNET_YES == cstate->in_destroy) 336 if (GNUNET_YES == cstate->in_destroy)
341 return GNUNET_NO; 337 return GNUNET_NO;
342 return GNUNET_OK; 338 return GNUNET_OK;
@@ -349,20 +345,20 @@ recv_message (void *cls,
349 * @param cstate handle of the client state to process 345 * @param cstate handle of the client state to process
350 */ 346 */
351static void 347static void
352cancel_aps (struct ClientState *cstate) 348cancel_aps(struct ClientState *cstate)
353{ 349{
354 struct AddressProbe *pos; 350 struct AddressProbe *pos;
355 351
356 while (NULL != (pos = cstate->ap_head)) 352 while (NULL != (pos = cstate->ap_head))
357 { 353 {
358 GNUNET_break (GNUNET_OK == 354 GNUNET_break(GNUNET_OK ==
359 GNUNET_NETWORK_socket_close (pos->sock)); 355 GNUNET_NETWORK_socket_close(pos->sock));
360 GNUNET_SCHEDULER_cancel (pos->task); 356 GNUNET_SCHEDULER_cancel(pos->task);
361 GNUNET_CONTAINER_DLL_remove (cstate->ap_head, 357 GNUNET_CONTAINER_DLL_remove(cstate->ap_head,
362 cstate->ap_tail, 358 cstate->ap_tail,
363 pos); 359 pos);
364 GNUNET_free (pos); 360 GNUNET_free(pos);
365 } 361 }
366} 362}
367 363
368 364
@@ -374,51 +370,51 @@ cancel_aps (struct ClientState *cstate)
374 * @param impl_state our `struct ClientState` 370 * @param impl_state our `struct ClientState`
375 */ 371 */
376static void 372static void
377connection_client_destroy_impl (struct GNUNET_MQ_Handle *mq, 373connection_client_destroy_impl(struct GNUNET_MQ_Handle *mq,
378 void *impl_state) 374 void *impl_state)
379{ 375{
380 struct ClientState *cstate = impl_state; 376 struct ClientState *cstate = impl_state;
381 377
382 (void) mq; 378 (void)mq;
383 if (NULL != cstate->dns_active) 379 if (NULL != cstate->dns_active)
384 { 380 {
385 GNUNET_RESOLVER_request_cancel (cstate->dns_active); 381 GNUNET_RESOLVER_request_cancel(cstate->dns_active);
386 cstate->dns_active = NULL; 382 cstate->dns_active = NULL;
387 } 383 }
388 if (NULL != cstate->send_task) 384 if (NULL != cstate->send_task)
389 { 385 {
390 GNUNET_SCHEDULER_cancel (cstate->send_task); 386 GNUNET_SCHEDULER_cancel(cstate->send_task);
391 cstate->send_task = NULL; 387 cstate->send_task = NULL;
392 } 388 }
393 if (NULL != cstate->retry_task) 389 if (NULL != cstate->retry_task)
394 { 390 {
395 GNUNET_SCHEDULER_cancel (cstate->retry_task); 391 GNUNET_SCHEDULER_cancel(cstate->retry_task);
396 cstate->retry_task = NULL; 392 cstate->retry_task = NULL;
397 } 393 }
398 if (GNUNET_SYSERR == cstate->in_destroy) 394 if (GNUNET_SYSERR == cstate->in_destroy)
399 { 395 {
400 /* defer destruction */ 396 /* defer destruction */
401 cstate->in_destroy = GNUNET_YES; 397 cstate->in_destroy = GNUNET_YES;
402 cstate->mq = NULL; 398 cstate->mq = NULL;
403 return; 399 return;
404 } 400 }
405 if (NULL != cstate->recv_task) 401 if (NULL != cstate->recv_task)
406 { 402 {
407 GNUNET_SCHEDULER_cancel (cstate->recv_task); 403 GNUNET_SCHEDULER_cancel(cstate->recv_task);
408 cstate->recv_task = NULL; 404 cstate->recv_task = NULL;
409 } 405 }
410 if (NULL != cstate->sock) 406 if (NULL != cstate->sock)
411 { 407 {
412 LOG (GNUNET_ERROR_TYPE_DEBUG, 408 LOG(GNUNET_ERROR_TYPE_DEBUG,
413 "destroying socket: %p\n", 409 "destroying socket: %p\n",
414 cstate->sock); 410 cstate->sock);
415 GNUNET_NETWORK_socket_close (cstate->sock); 411 GNUNET_NETWORK_socket_close(cstate->sock);
416 } 412 }
417 cancel_aps (cstate); 413 cancel_aps(cstate);
418 GNUNET_free (cstate->service_name); 414 GNUNET_free(cstate->service_name);
419 GNUNET_free_non_null (cstate->hostname); 415 GNUNET_free_non_null(cstate->hostname);
420 GNUNET_MST_destroy (cstate->mst); 416 GNUNET_MST_destroy(cstate->mst);
421 GNUNET_free (cstate); 417 GNUNET_free(cstate);
422} 418}
423 419
424 420
@@ -428,39 +424,39 @@ connection_client_destroy_impl (struct GNUNET_MQ_Handle *mq,
428 * @param cls `struct ClientState` with connection to read from 424 * @param cls `struct ClientState` with connection to read from
429 */ 425 */
430static void 426static void
431receive_ready (void *cls) 427receive_ready(void *cls)
432{ 428{
433 struct ClientState *cstate = cls; 429 struct ClientState *cstate = cls;
434 int ret; 430 int ret;
435 431
436 cstate->recv_task = NULL; 432 cstate->recv_task = NULL;
437 cstate->in_destroy = GNUNET_SYSERR; 433 cstate->in_destroy = GNUNET_SYSERR;
438 ret = GNUNET_MST_read (cstate->mst, 434 ret = GNUNET_MST_read(cstate->mst,
439 cstate->sock, 435 cstate->sock,
440 GNUNET_NO, 436 GNUNET_NO,
441 GNUNET_NO); 437 GNUNET_NO);
442 if (GNUNET_SYSERR == ret) 438 if (GNUNET_SYSERR == ret)
443 { 439 {
444 if (NULL != cstate->mq) 440 if (NULL != cstate->mq)
445 GNUNET_MQ_inject_error (cstate->mq, 441 GNUNET_MQ_inject_error(cstate->mq,
446 GNUNET_MQ_ERROR_READ); 442 GNUNET_MQ_ERROR_READ);
447 if (GNUNET_YES == cstate->in_destroy) 443 if (GNUNET_YES == cstate->in_destroy)
448 connection_client_destroy_impl (cstate->mq, 444 connection_client_destroy_impl(cstate->mq,
449 cstate); 445 cstate);
450 return; 446 return;
451 } 447 }
452 if (GNUNET_YES == cstate->in_destroy) 448 if (GNUNET_YES == cstate->in_destroy)
453 { 449 {
454 connection_client_destroy_impl (cstate->mq, 450 connection_client_destroy_impl(cstate->mq,
455 cstate); 451 cstate);
456 return; 452 return;
457 } 453 }
458 cstate->in_destroy = GNUNET_NO; 454 cstate->in_destroy = GNUNET_NO;
459 cstate->recv_task 455 cstate->recv_task
460 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 456 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
461 cstate->sock, 457 cstate->sock,
462 &receive_ready, 458 &receive_ready,
463 cstate); 459 cstate);
464} 460}
465 461
466 462
@@ -470,23 +466,23 @@ receive_ready (void *cls)
470 * @param cstate the connection we tried to establish 466 * @param cstate the connection we tried to establish
471 */ 467 */
472static void 468static void
473connect_success_continuation (struct ClientState *cstate) 469connect_success_continuation(struct ClientState *cstate)
474{ 470{
475 GNUNET_assert (NULL == cstate->recv_task); 471 GNUNET_assert(NULL == cstate->recv_task);
476 cstate->recv_task 472 cstate->recv_task
477 = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 473 = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
478 cstate->sock, 474 cstate->sock,
479 &receive_ready, 475 &receive_ready,
480 cstate); 476 cstate);
481 if (NULL != cstate->msg) 477 if (NULL != cstate->msg)
482 { 478 {
483 GNUNET_assert (NULL == cstate->send_task); 479 GNUNET_assert(NULL == cstate->send_task);
484 cstate->send_task 480 cstate->send_task
485 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, 481 = GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
486 cstate->sock, 482 cstate->sock,
487 &transmit_ready, 483 &transmit_ready,
488 cstate); 484 cstate);
489 } 485 }
490} 486}
491 487
492 488
@@ -498,8 +494,8 @@ connect_success_continuation (struct ClientState *cstate)
498 * @return NULL on error, socket connected to UNIX otherwise 494 * @return NULL on error, socket connected to UNIX otherwise
499 */ 495 */
500static struct GNUNET_NETWORK_Handle * 496static struct GNUNET_NETWORK_Handle *
501try_unixpath (const char *service_name, 497try_unixpath(const char *service_name,
502 const struct GNUNET_CONFIGURATION_Handle *cfg) 498 const struct GNUNET_CONFIGURATION_Handle *cfg)
503{ 499{
504#if AF_UNIX 500#if AF_UNIX
505 struct GNUNET_NETWORK_Handle *sock; 501 struct GNUNET_NETWORK_Handle *sock;
@@ -508,67 +504,67 @@ try_unixpath (const char *service_name,
508 504
509 unixpath = NULL; 505 unixpath = NULL;
510 if ((GNUNET_OK == 506 if ((GNUNET_OK ==
511 GNUNET_CONFIGURATION_get_value_filename (cfg, 507 GNUNET_CONFIGURATION_get_value_filename(cfg,
512 service_name, 508 service_name,
513 "UNIXPATH", 509 "UNIXPATH",
514 &unixpath)) && 510 &unixpath)) &&
515 (0 < strlen (unixpath))) 511 (0 < strlen(unixpath)))
516 {
517 /* We have a non-NULL unixpath, need to validate it */
518 if (strlen (unixpath) >= sizeof (s_un.sun_path))
519 { 512 {
520 LOG (GNUNET_ERROR_TYPE_WARNING, 513 /* We have a non-NULL unixpath, need to validate it */
521 _("UNIXPATH `%s' too long, maximum length is %llu\n"), 514 if (strlen(unixpath) >= sizeof(s_un.sun_path))
522 unixpath, 515 {
523 (unsigned long long) sizeof (s_un.sun_path)); 516 LOG(GNUNET_ERROR_TYPE_WARNING,
524 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath); 517 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
525 LOG (GNUNET_ERROR_TYPE_INFO, 518 unixpath,
526 _("Using `%s' instead\n"), 519 (unsigned long long)sizeof(s_un.sun_path));
527 unixpath); 520 unixpath = GNUNET_NETWORK_shorten_unixpath(unixpath);
528 if (NULL == unixpath) 521 LOG(GNUNET_ERROR_TYPE_INFO,
529 return NULL; 522 _("Using `%s' instead\n"),
530 } 523 unixpath);
531 memset (&s_un, 524 if (NULL == unixpath)
532 0, 525 return NULL;
533 sizeof (s_un)); 526 }
534 s_un.sun_family = AF_UNIX; 527 memset(&s_un,
535 GNUNET_strlcpy (s_un.sun_path, 528 0,
536 unixpath, 529 sizeof(s_un));
537 sizeof (s_un.sun_path)); 530 s_un.sun_family = AF_UNIX;
531 GNUNET_strlcpy(s_un.sun_path,
532 unixpath,
533 sizeof(s_un.sun_path));
538#ifdef LINUX 534#ifdef LINUX
539 { 535 {
540 int abstract; 536 int abstract;
541 537
542 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, 538 abstract = GNUNET_CONFIGURATION_get_value_yesno(cfg,
543 "TESTING", 539 "TESTING",
544 "USE_ABSTRACT_SOCKETS"); 540 "USE_ABSTRACT_SOCKETS");
545 if (GNUNET_YES == abstract) 541 if (GNUNET_YES == abstract)
546 s_un.sun_path[0] = '\0'; 542 s_un.sun_path[0] = '\0';
547 } 543 }
548#endif 544#endif
549#if HAVE_SOCKADDR_UN_SUN_LEN 545#if HAVE_SOCKADDR_UN_SUN_LEN
550 s_un.sun_len = (u_char) sizeof (struct sockaddr_un); 546 s_un.sun_len = (u_char)sizeof(struct sockaddr_un);
551#endif 547#endif
552 sock = GNUNET_NETWORK_socket_create (AF_UNIX, 548 sock = GNUNET_NETWORK_socket_create(AF_UNIX,
553 SOCK_STREAM, 549 SOCK_STREAM,
554 0); 550 0);
555 if ( (NULL != sock) && 551 if ((NULL != sock) &&
556 ( (GNUNET_OK == 552 ((GNUNET_OK ==
557 GNUNET_NETWORK_socket_connect (sock, 553 GNUNET_NETWORK_socket_connect(sock,
558 (struct sockaddr *) &s_un, 554 (struct sockaddr *)&s_un,
559 sizeof (s_un))) || 555 sizeof(s_un))) ||
560 (EINPROGRESS == errno) ) ) 556 (EINPROGRESS == errno)))
561 { 557 {
562 LOG (GNUNET_ERROR_TYPE_DEBUG, 558 LOG(GNUNET_ERROR_TYPE_DEBUG,
563 "Successfully connected to unixpath `%s'!\n", 559 "Successfully connected to unixpath `%s'!\n",
564 unixpath); 560 unixpath);
565 GNUNET_free (unixpath); 561 GNUNET_free(unixpath);
566 return sock; 562 return sock;
563 }
564 if (NULL != sock)
565 GNUNET_NETWORK_socket_close(sock);
567 } 566 }
568 if (NULL != sock) 567 GNUNET_free_non_null(unixpath);
569 GNUNET_NETWORK_socket_close (sock);
570 }
571 GNUNET_free_non_null (unixpath);
572#endif 568#endif
573 return NULL; 569 return NULL;
574} 570}
@@ -581,7 +577,7 @@ try_unixpath (const char *service_name,
581 * @param cls the `struct AddressProbe *` with the address that we are probing 577 * @param cls the `struct AddressProbe *` with the address that we are probing
582 */ 578 */
583static void 579static void
584connect_probe_continuation (void *cls) 580connect_probe_continuation(void *cls)
585{ 581{
586 struct AddressProbe *ap = cls; 582 struct AddressProbe *ap = cls;
587 struct ClientState *cstate = ap->cstate; 583 struct ClientState *cstate = ap->cstate;
@@ -590,40 +586,40 @@ connect_probe_continuation (void *cls)
590 socklen_t len; 586 socklen_t len;
591 587
592 ap->task = NULL; 588 ap->task = NULL;
593 GNUNET_assert (NULL != ap->sock); 589 GNUNET_assert(NULL != ap->sock);
594 GNUNET_CONTAINER_DLL_remove (cstate->ap_head, 590 GNUNET_CONTAINER_DLL_remove(cstate->ap_head,
595 cstate->ap_tail, 591 cstate->ap_tail,
596 ap); 592 ap);
597 len = sizeof (error); 593 len = sizeof(error);
598 error = 0; 594 error = 0;
599 tc = GNUNET_SCHEDULER_get_task_context (); 595 tc = GNUNET_SCHEDULER_get_task_context();
600 if ( (0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) || 596 if ((0 == (tc->reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) ||
601 (GNUNET_OK != 597 (GNUNET_OK !=
602 GNUNET_NETWORK_socket_getsockopt (ap->sock, 598 GNUNET_NETWORK_socket_getsockopt(ap->sock,
603 SOL_SOCKET, 599 SOL_SOCKET,
604 SO_ERROR, 600 SO_ERROR,
605 &error, 601 &error,
606 &len)) || 602 &len)) ||
607 (0 != error) ) 603 (0 != error))
608 { 604 {
609 GNUNET_break (GNUNET_OK == 605 GNUNET_break(GNUNET_OK ==
610 GNUNET_NETWORK_socket_close (ap->sock)); 606 GNUNET_NETWORK_socket_close(ap->sock));
611 GNUNET_free (ap); 607 GNUNET_free(ap);
612 if ( (NULL == cstate->ap_head) && 608 if ((NULL == cstate->ap_head) &&
613 // (NULL == cstate->proxy_handshake) && 609 // (NULL == cstate->proxy_handshake) &&
614 (NULL == cstate->dns_active) ) 610 (NULL == cstate->dns_active))
615 connect_fail_continuation (cstate); 611 connect_fail_continuation(cstate);
616 return; 612 return;
617 } 613 }
618 LOG (GNUNET_ERROR_TYPE_DEBUG, 614 LOG(GNUNET_ERROR_TYPE_DEBUG,
619 "Connection to `%s' succeeded!\n", 615 "Connection to `%s' succeeded!\n",
620 cstate->service_name); 616 cstate->service_name);
621 /* trigger jobs that waited for the connection */ 617 /* trigger jobs that waited for the connection */
622 GNUNET_assert (NULL == cstate->sock); 618 GNUNET_assert(NULL == cstate->sock);
623 cstate->sock = ap->sock; 619 cstate->sock = ap->sock;
624 GNUNET_free (ap); 620 GNUNET_free(ap);
625 cancel_aps (cstate); 621 cancel_aps(cstate);
626 connect_success_continuation (cstate); 622 connect_success_continuation(cstate);
627} 623}
628 624
629 625
@@ -636,80 +632,82 @@ connect_probe_continuation (void *cls)
636 * @param addrlen length of @a addr 632 * @param addrlen length of @a addr
637 */ 633 */
638static void 634static void
639try_connect_using_address (void *cls, 635try_connect_using_address(void *cls,
640 const struct sockaddr *addr, 636 const struct sockaddr *addr,
641 socklen_t addrlen) 637 socklen_t addrlen)
642{ 638{
643 struct ClientState *cstate = cls; 639 struct ClientState *cstate = cls;
644 struct AddressProbe *ap; 640 struct AddressProbe *ap;
645 641
646 if (NULL == addr) 642 if (NULL == addr)
647 { 643 {
648 cstate->dns_active = NULL; 644 cstate->dns_active = NULL;
649 if ( (NULL == cstate->ap_head) && 645 if ((NULL == cstate->ap_head) &&
650 // (NULL == cstate->proxy_handshake) && 646 // (NULL == cstate->proxy_handshake) &&
651 (NULL == cstate->sock) ) 647 (NULL == cstate->sock))
652 connect_fail_continuation (cstate); 648 connect_fail_continuation(cstate);
653 return; 649 return;
654 } 650 }
655 if (NULL != cstate->sock) 651 if (NULL != cstate->sock)
656 return; /* already connected */ 652 return; /* already connected */
657 /* try to connect */ 653 /* try to connect */
658 LOG (GNUNET_ERROR_TYPE_DEBUG, 654 LOG(GNUNET_ERROR_TYPE_DEBUG,
659 "Trying to connect using address `%s:%u'\n", 655 "Trying to connect using address `%s:%u'\n",
660 GNUNET_a2s (addr, 656 GNUNET_a2s(addr,
661 addrlen), 657 addrlen),
662 cstate->port); 658 cstate->port);
663 ap = GNUNET_malloc (sizeof (struct AddressProbe) + addrlen); 659 ap = GNUNET_malloc(sizeof(struct AddressProbe) + addrlen);
664 ap->addr = (const struct sockaddr *) &ap[1]; 660 ap->addr = (const struct sockaddr *)&ap[1];
665 GNUNET_memcpy (&ap[1], 661 GNUNET_memcpy(&ap[1],
666 addr, 662 addr,
667 addrlen); 663 addrlen);
668 ap->addrlen = addrlen; 664 ap->addrlen = addrlen;
669 ap->cstate = cstate; 665 ap->cstate = cstate;
670 666
671 switch (ap->addr->sa_family) 667 switch (ap->addr->sa_family)
672 { 668 {
673 case AF_INET: 669 case AF_INET:
674 ((struct sockaddr_in *) ap->addr)->sin_port = htons (cstate->port); 670 ((struct sockaddr_in *)ap->addr)->sin_port = htons(cstate->port);
675 break; 671 break;
676 case AF_INET6: 672
677 ((struct sockaddr_in6 *) ap->addr)->sin6_port = htons (cstate->port); 673 case AF_INET6:
678 break; 674 ((struct sockaddr_in6 *)ap->addr)->sin6_port = htons(cstate->port);
679 default: 675 break;
680 GNUNET_break (0); 676
681 GNUNET_free (ap); 677 default:
682 return; /* not supported by us */ 678 GNUNET_break(0);
683 } 679 GNUNET_free(ap);
684 ap->sock = GNUNET_NETWORK_socket_create (ap->addr->sa_family, 680 return; /* not supported by us */
685 SOCK_STREAM, 681 }
686 0); 682 ap->sock = GNUNET_NETWORK_socket_create(ap->addr->sa_family,
683 SOCK_STREAM,
684 0);
687 if (NULL == ap->sock) 685 if (NULL == ap->sock)
688 { 686 {
689 GNUNET_free (ap); 687 GNUNET_free(ap);
690 return; /* not supported by OS */ 688 return; /* not supported by OS */
691 } 689 }
692 if ( (GNUNET_OK != 690 if ((GNUNET_OK !=
693 GNUNET_NETWORK_socket_connect (ap->sock, 691 GNUNET_NETWORK_socket_connect(ap->sock,
694 ap->addr, 692 ap->addr,
695 ap->addrlen)) && 693 ap->addrlen)) &&
696 (EINPROGRESS != errno) ) 694 (EINPROGRESS != errno))
697 { 695 {
698 /* maybe refused / unsupported address, try next */ 696 /* maybe refused / unsupported address, try next */
699 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, 697 GNUNET_log_strerror(GNUNET_ERROR_TYPE_INFO,
700 "connect"); 698 "connect");
701 GNUNET_break (GNUNET_OK == 699 GNUNET_break(GNUNET_OK ==
702 GNUNET_NETWORK_socket_close (ap->sock)); 700 GNUNET_NETWORK_socket_close(ap->sock));
703 GNUNET_free (ap); 701 GNUNET_free(ap);
704 return; 702 return;
705 } 703 }
706 GNUNET_CONTAINER_DLL_insert (cstate->ap_head, 704 GNUNET_CONTAINER_DLL_insert(cstate->ap_head,
707 cstate->ap_tail, 705 cstate->ap_tail,
708 ap); 706 ap);
709 ap->task = GNUNET_SCHEDULER_add_write_net (CONNECT_RETRY_TIMEOUT, 707 ap->task = GNUNET_SCHEDULER_add_write_net(CONNECT_RETRY_TIMEOUT,
710 ap->sock, 708 ap->sock,
711 &connect_probe_continuation, 709 &connect_probe_continuation,
712 ap); 710 ap);
713} 711}
714 712
715 713
@@ -722,55 +720,56 @@ try_connect_using_address (void *cls,
722 * @return #GNUNET_OK if the configuration is valid, #GNUNET_SYSERR if not 720 * @return #GNUNET_OK if the configuration is valid, #GNUNET_SYSERR if not
723 */ 721 */
724static int 722static int
725test_service_configuration (const char *service_name, 723test_service_configuration(const char *service_name,
726 const struct GNUNET_CONFIGURATION_Handle *cfg) 724 const struct GNUNET_CONFIGURATION_Handle *cfg)
727{ 725{
728 int ret = GNUNET_SYSERR; 726 int ret = GNUNET_SYSERR;
729 char *hostname = NULL; 727 char *hostname = NULL;
730 unsigned long long port; 728 unsigned long long port;
729
731#if AF_UNIX 730#if AF_UNIX
732 char *unixpath = NULL; 731 char *unixpath = NULL;
733 732
734 if ((GNUNET_OK == 733 if ((GNUNET_OK ==
735 GNUNET_CONFIGURATION_get_value_filename (cfg, 734 GNUNET_CONFIGURATION_get_value_filename(cfg,
736 service_name, 735 service_name,
737 "UNIXPATH", 736 "UNIXPATH",
738 &unixpath)) && 737 &unixpath)) &&
739 (0 < strlen (unixpath))) 738 (0 < strlen(unixpath)))
740 ret = GNUNET_OK; 739 ret = GNUNET_OK;
741 else if ((GNUNET_OK == 740 else if ((GNUNET_OK ==
742 GNUNET_CONFIGURATION_have_value (cfg, 741 GNUNET_CONFIGURATION_have_value(cfg,
743 service_name, 742 service_name,
744 "UNIXPATH"))) 743 "UNIXPATH")))
745 { 744 {
746 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, 745 GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR,
747 service_name, 746 service_name,
748 "UNIXPATH", 747 "UNIXPATH",
749 _("not a valid filename")); 748 _("not a valid filename"));
750 return GNUNET_SYSERR; /* UNIXPATH specified but invalid! */ 749 return GNUNET_SYSERR; /* UNIXPATH specified but invalid! */
751 } 750 }
752 GNUNET_free_non_null (unixpath); 751 GNUNET_free_non_null(unixpath);
753#endif 752#endif
754 753
755 if ( (GNUNET_YES == 754 if ((GNUNET_YES ==
756 GNUNET_CONFIGURATION_have_value (cfg, 755 GNUNET_CONFIGURATION_have_value(cfg,
757 service_name, 756 service_name,
758 "PORT")) && 757 "PORT")) &&
759 (GNUNET_OK == 758 (GNUNET_OK ==
760 GNUNET_CONFIGURATION_get_value_number (cfg, 759 GNUNET_CONFIGURATION_get_value_number(cfg,
761 service_name, 760 service_name,
762 "PORT", 761 "PORT",
763 &port)) && 762 &port)) &&
764 (port <= 65535) && 763 (port <= 65535) &&
765 (0 != port) && 764 (0 != port) &&
766 (GNUNET_OK == 765 (GNUNET_OK ==
767 GNUNET_CONFIGURATION_get_value_string (cfg, 766 GNUNET_CONFIGURATION_get_value_string(cfg,
768 service_name, 767 service_name,
769 "HOSTNAME", 768 "HOSTNAME",
770 &hostname)) && 769 &hostname)) &&
771 (0 != strlen (hostname)) ) 770 (0 != strlen(hostname)))
772 ret = GNUNET_OK; 771 ret = GNUNET_OK;
773 GNUNET_free_non_null (hostname); 772 GNUNET_free_non_null(hostname);
774 return ret; 773 return ret;
775} 774}
776 775
@@ -781,7 +780,7 @@ test_service_configuration (const char *service_name,
781 * @param cls the `struct ClientState` to try to connect to the service 780 * @param cls the `struct ClientState` to try to connect to the service
782 */ 781 */
783static void 782static void
784start_connect (void *cls) 783start_connect(void *cls)
785{ 784{
786 struct ClientState *cstate = cls; 785 struct ClientState *cstate = cls;
787 786
@@ -789,41 +788,41 @@ start_connect (void *cls)
789#if 0 788#if 0
790 /* Never use a local source if a proxy is configured */ 789 /* Never use a local source if a proxy is configured */
791 if (GNUNET_YES == 790 if (GNUNET_YES ==
792 GNUNET_SOCKS_check_service (cstate->service_name, 791 GNUNET_SOCKS_check_service(cstate->service_name,
793 cstate->cfg)) 792 cstate->cfg))
794 { 793 {
795 socks_connect (cstate); 794 socks_connect(cstate);
796 return; 795 return;
797 } 796 }
798#endif 797#endif
799 798
800 if ( (0 == (cstate->attempts++ % 2)) || 799 if ((0 == (cstate->attempts++ % 2)) ||
801 (0 == cstate->port) || 800 (0 == cstate->port) ||
802 (NULL == cstate->hostname) ) 801 (NULL == cstate->hostname))
803 {
804 /* on even rounds, try UNIX first, or always
805 if we do not have a DNS name and TCP port. */
806 cstate->sock = try_unixpath (cstate->service_name,
807 cstate->cfg);
808 if (NULL != cstate->sock)
809 { 802 {
810 connect_success_continuation (cstate); 803 /* on even rounds, try UNIX first, or always
804 if we do not have a DNS name and TCP port. */
805 cstate->sock = try_unixpath(cstate->service_name,
806 cstate->cfg);
807 if (NULL != cstate->sock)
808 {
809 connect_success_continuation(cstate);
810 return;
811 }
812 }
813 if ((NULL == cstate->hostname) ||
814 (0 == cstate->port))
815 {
816 /* All options failed. Boo! */
817 connect_fail_continuation(cstate);
811 return; 818 return;
812 } 819 }
813 }
814 if ( (NULL == cstate->hostname) ||
815 (0 == cstate->port) )
816 {
817 /* All options failed. Boo! */
818 connect_fail_continuation (cstate);
819 return;
820 }
821 cstate->dns_active 820 cstate->dns_active
822 = GNUNET_RESOLVER_ip_get (cstate->hostname, 821 = GNUNET_RESOLVER_ip_get(cstate->hostname,
823 AF_UNSPEC, 822 AF_UNSPEC,
824 CONNECT_RETRY_TIMEOUT, 823 CONNECT_RETRY_TIMEOUT,
825 &try_connect_using_address, 824 &try_connect_using_address,
826 cstate); 825 cstate);
827} 826}
828 827
829 828
@@ -835,30 +834,30 @@ start_connect (void *cls)
835 * @param impl_state our `struct ClientState` 834 * @param impl_state our `struct ClientState`
836 */ 835 */
837static void 836static void
838connection_client_send_impl (struct GNUNET_MQ_Handle *mq, 837connection_client_send_impl(struct GNUNET_MQ_Handle *mq,
839 const struct GNUNET_MessageHeader *msg, 838 const struct GNUNET_MessageHeader *msg,
840 void *impl_state) 839 void *impl_state)
841{ 840{
842 struct ClientState *cstate = impl_state; 841 struct ClientState *cstate = impl_state;
843 842
844 (void) mq; 843 (void)mq;
845 /* only one message at a time allowed */ 844 /* only one message at a time allowed */
846 GNUNET_assert (NULL == cstate->msg); 845 GNUNET_assert(NULL == cstate->msg);
847 GNUNET_assert (NULL == cstate->send_task); 846 GNUNET_assert(NULL == cstate->send_task);
848 cstate->msg = msg; 847 cstate->msg = msg;
849 cstate->msg_off = 0; 848 cstate->msg_off = 0;
850 if (NULL == cstate->sock) 849 if (NULL == cstate->sock)
851 { 850 {
852 LOG (GNUNET_ERROR_TYPE_DEBUG, 851 LOG(GNUNET_ERROR_TYPE_DEBUG,
853 "message of type %u waiting for socket\n", 852 "message of type %u waiting for socket\n",
854 ntohs(msg->type)); 853 ntohs(msg->type));
855 return; /* still waiting for connection */ 854 return; /* still waiting for connection */
856 } 855 }
857 cstate->send_task 856 cstate->send_task
858 = GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, 857 = GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
859 cstate->sock, 858 cstate->sock,
860 &transmit_ready, 859 &transmit_ready,
861 cstate); 860 cstate);
862} 861}
863 862
864 863
@@ -869,20 +868,20 @@ connection_client_send_impl (struct GNUNET_MQ_Handle *mq,
869 * @param impl_state our `struct ClientState` 868 * @param impl_state our `struct ClientState`
870 */ 869 */
871static void 870static void
872connection_client_cancel_impl (struct GNUNET_MQ_Handle *mq, 871connection_client_cancel_impl(struct GNUNET_MQ_Handle *mq,
873 void *impl_state) 872 void *impl_state)
874{ 873{
875 struct ClientState *cstate = impl_state; 874 struct ClientState *cstate = impl_state;
876 875
877 (void) mq; 876 (void)mq;
878 GNUNET_assert (NULL != cstate->msg); 877 GNUNET_assert(NULL != cstate->msg);
879 GNUNET_assert (0 == cstate->msg_off); 878 GNUNET_assert(0 == cstate->msg_off);
880 cstate->msg = NULL; 879 cstate->msg = NULL;
881 if (NULL != cstate->send_task) 880 if (NULL != cstate->send_task)
882 { 881 {
883 GNUNET_SCHEDULER_cancel (cstate->send_task); 882 GNUNET_SCHEDULER_cancel(cstate->send_task);
884 cstate->send_task = NULL; 883 cstate->send_task = NULL;
885 } 884 }
886} 885}
887 886
888 887
@@ -898,57 +897,57 @@ connection_client_cancel_impl (struct GNUNET_MQ_Handle *mq,
898 * @return the message queue, NULL on error 897 * @return the message queue, NULL on error
899 */ 898 */
900struct GNUNET_MQ_Handle * 899struct GNUNET_MQ_Handle *
901GNUNET_CLIENT_connect (const struct GNUNET_CONFIGURATION_Handle *cfg, 900GNUNET_CLIENT_connect(const struct GNUNET_CONFIGURATION_Handle *cfg,
902 const char *service_name, 901 const char *service_name,
903 const struct GNUNET_MQ_MessageHandler *handlers, 902 const struct GNUNET_MQ_MessageHandler *handlers,
904 GNUNET_MQ_ErrorHandler error_handler, 903 GNUNET_MQ_ErrorHandler error_handler,
905 void *error_handler_cls) 904 void *error_handler_cls)
906{ 905{
907 struct ClientState *cstate; 906 struct ClientState *cstate;
908 907
909 if (GNUNET_OK != 908 if (GNUNET_OK !=
910 test_service_configuration (service_name, 909 test_service_configuration(service_name,
911 cfg)) 910 cfg))
912 return NULL; 911 return NULL;
913 cstate = GNUNET_new (struct ClientState); 912 cstate = GNUNET_new(struct ClientState);
914 cstate->service_name = GNUNET_strdup (service_name); 913 cstate->service_name = GNUNET_strdup(service_name);
915 cstate->cfg = cfg; 914 cstate->cfg = cfg;
916 cstate->retry_task = GNUNET_SCHEDULER_add_now (&start_connect, 915 cstate->retry_task = GNUNET_SCHEDULER_add_now(&start_connect,
917 cstate); 916 cstate);
918 cstate->mst = GNUNET_MST_create (&recv_message, 917 cstate->mst = GNUNET_MST_create(&recv_message,
919 cstate); 918 cstate);
920 if (GNUNET_YES == 919 if (GNUNET_YES ==
921 GNUNET_CONFIGURATION_have_value (cfg, 920 GNUNET_CONFIGURATION_have_value(cfg,
922 service_name, 921 service_name,
923 "PORT")) 922 "PORT"))
924 {
925 if (! ( (GNUNET_OK !=
926 GNUNET_CONFIGURATION_get_value_number (cfg,
927 service_name,
928 "PORT",
929 &cstate->port)) ||
930 (cstate->port > 65535) ||
931 (GNUNET_OK !=
932 GNUNET_CONFIGURATION_get_value_string (cfg,
933 service_name,
934 "HOSTNAME",
935 &cstate->hostname)) ) &&
936 (0 == strlen (cstate->hostname)) )
937 { 923 {
938 GNUNET_free (cstate->hostname); 924 if (!((GNUNET_OK !=
939 cstate->hostname = NULL; 925 GNUNET_CONFIGURATION_get_value_number(cfg,
940 LOG (GNUNET_ERROR_TYPE_WARNING, 926 service_name,
941 _("Need a non-empty hostname for service `%s'.\n"), 927 "PORT",
942 service_name); 928 &cstate->port)) ||
929 (cstate->port > 65535) ||
930 (GNUNET_OK !=
931 GNUNET_CONFIGURATION_get_value_string(cfg,
932 service_name,
933 "HOSTNAME",
934 &cstate->hostname))) &&
935 (0 == strlen(cstate->hostname)))
936 {
937 GNUNET_free(cstate->hostname);
938 cstate->hostname = NULL;
939 LOG(GNUNET_ERROR_TYPE_WARNING,
940 _("Need a non-empty hostname for service `%s'.\n"),
941 service_name);
942 }
943 } 943 }
944 } 944 cstate->mq = GNUNET_MQ_queue_for_callbacks(&connection_client_send_impl,
945 cstate->mq = GNUNET_MQ_queue_for_callbacks (&connection_client_send_impl, 945 &connection_client_destroy_impl,
946 &connection_client_destroy_impl, 946 &connection_client_cancel_impl,
947 &connection_client_cancel_impl, 947 cstate,
948 cstate, 948 handlers,
949 handlers, 949 error_handler,
950 error_handler, 950 error_handler_cls);
951 error_handler_cls);
952 return cstate->mq; 951 return cstate->mq;
953} 952}
954 953
diff --git a/src/util/common_allocation.c b/src/util/common_allocation.c
index 94890a7f4..fd5af7a91 100644
--- a/src/util/common_allocation.c
+++ b/src/util/common_allocation.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/common_allocation.c 22 * @file util/common_allocation.c
@@ -33,10 +33,10 @@
33#endif 33#endif
34 34
35#define LOG(kind, ...) \ 35#define LOG(kind, ...) \
36 GNUNET_log_from (kind, "util-common-allocation", __VA_ARGS__) 36 GNUNET_log_from(kind, "util-common-allocation", __VA_ARGS__)
37 37
38#define LOG_STRERROR(kind, syscall) \ 38#define LOG_STRERROR(kind, syscall) \
39 GNUNET_log_from_strerror (kind, "util-common-allocation", syscall) 39 GNUNET_log_from_strerror(kind, "util-common-allocation", syscall)
40 40
41#ifndef INT_MAX 41#ifndef INT_MAX
42#define INT_MAX 0x7FFFFFFF 42#define INT_MAX 0x7FFFFFFF
@@ -63,19 +63,19 @@ static LONG mem_used = 0;
63 * @return pointer to size bytes of memory 63 * @return pointer to size bytes of memory
64 */ 64 */
65void * 65void *
66GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber) 66GNUNET_xmalloc_(size_t size, const char *filename, int linenumber)
67{ 67{
68 void *ret; 68 void *ret;
69 69
70 /* As a security precaution, we generally do not allow very large 70 /* As a security precaution, we generally do not allow very large
71 * allocations using the default 'GNUNET_malloc()' macro */ 71 * allocations using the default 'GNUNET_malloc()' macro */
72 GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber); 72 GNUNET_assert_at(size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber);
73 ret = GNUNET_xmalloc_unchecked_ (size, filename, linenumber); 73 ret = GNUNET_xmalloc_unchecked_(size, filename, linenumber);
74 if (NULL == ret) 74 if (NULL == ret)
75 { 75 {
76 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "malloc"); 76 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "malloc");
77 GNUNET_assert (0); 77 GNUNET_assert(0);
78 } 78 }
79 return ret; 79 return ret;
80} 80}
81 81
@@ -95,23 +95,23 @@ GNUNET_xmalloc_ (size_t size, const char *filename, int linenumber)
95 * @return allocated memory, never NULL 95 * @return allocated memory, never NULL
96 */ 96 */
97void ** 97void **
98GNUNET_xnew_array_2d_ (size_t n, 98GNUNET_xnew_array_2d_(size_t n,
99 size_t m, 99 size_t m,
100 size_t elementSize, 100 size_t elementSize,
101 const char *filename, 101 const char *filename,
102 int linenumber) 102 int linenumber)
103{ 103{
104 /* use char pointer internally to avoid void pointer arithmetic warnings */ 104 /* use char pointer internally to avoid void pointer arithmetic warnings */
105 char **ret = GNUNET_xmalloc_ (n * sizeof (void *) + /* 1. dim header */ 105 char **ret = GNUNET_xmalloc_(n * sizeof(void *) + /* 1. dim header */
106 n * m * elementSize, /* element data */ 106 n * m * elementSize, /* element data */
107 filename, 107 filename,
108 linenumber); 108 linenumber);
109 109
110 for (size_t i = 0; i < n; i++) 110 for (size_t i = 0; i < n; i++)
111 ret[i] = (char *) ret + /* base address */ 111 ret[i] = (char *)ret + /* base address */
112 n * sizeof (void *) + /* skip 1. dim header */ 112 n * sizeof(void *) + /* skip 1. dim header */
113 i * m * elementSize; /* skip to 2. dim row header */ 113 i * m * elementSize; /* skip to 2. dim row header */
114 return (void **) ret; 114 return (void **)ret;
115} 115}
116 116
117 117
@@ -131,34 +131,34 @@ GNUNET_xnew_array_2d_ (size_t n,
131 * @return allocated memory, never NULL 131 * @return allocated memory, never NULL
132 */ 132 */
133void *** 133void ***
134GNUNET_xnew_array_3d_ (size_t n, 134GNUNET_xnew_array_3d_(size_t n,
135 size_t m, 135 size_t m,
136 size_t o, 136 size_t o,
137 size_t elementSize, 137 size_t elementSize,
138 const char *filename, 138 const char *filename,
139 int linenumber) 139 int linenumber)
140{ 140{
141 /* use char pointer internally to avoid void pointer arithmetic warnings */ 141 /* use char pointer internally to avoid void pointer arithmetic warnings */
142 char ***ret = GNUNET_xmalloc_ (n * sizeof (void **) + /* 1. dim header */ 142 char ***ret = GNUNET_xmalloc_(n * sizeof(void **) + /* 1. dim header */
143 n * m * sizeof (void *) + /* 2. dim header */ 143 n * m * sizeof(void *) + /* 2. dim header */
144 n * m * o * elementSize, /* element data */ 144 n * m * o * elementSize, /* element data */
145 filename, 145 filename,
146 linenumber); 146 linenumber);
147 147
148 for (size_t i = 0; i < n; i++) 148 for (size_t i = 0; i < n; i++)
149 { 149 {
150 /* need to cast to (char *) temporarily for byte level acuracy */ 150 /* need to cast to (char *) temporarily for byte level acuracy */
151 ret[i] = (char **) ((char *) ret + /* base address */ 151 ret[i] = (char **)((char *)ret + /* base address */
152 n * sizeof (void **) + /* skip 1. dim header */ 152 n * sizeof(void **) + /* skip 1. dim header */
153 i * m * sizeof (void *)); /* skip to 2. dim header */ 153 i * m * sizeof(void *)); /* skip to 2. dim header */
154 for (size_t j = 0; j < m; j++) 154 for (size_t j = 0; j < m; j++)
155 ret[i][j] = (char *) ret + /* base address */ 155 ret[i][j] = (char *)ret + /* base address */
156 n * sizeof (void **) + /* skip 1. dim header */ 156 n * sizeof(void **) + /* skip 1. dim header */
157 n * m * sizeof (void *) + /* skip 2. dim header */ 157 n * m * sizeof(void *) + /* skip 2. dim header */
158 i * m * o * elementSize + /* skip to 2. dim part */ 158 i * m * o * elementSize + /* skip to 2. dim part */
159 j * o * elementSize; /* skip to 3. dim row data */ 159 j * o * elementSize; /* skip to 3. dim row data */
160 } 160 }
161 return (void ***) ret; 161 return (void ***)ret;
162} 162}
163 163
164 164
@@ -174,34 +174,34 @@ GNUNET_xnew_array_3d_ (size_t n,
174 * @return allocated memory, never NULL 174 * @return allocated memory, never NULL
175 */ 175 */
176void * 176void *
177GNUNET_xmemdup_ (const void *buf, 177GNUNET_xmemdup_(const void *buf,
178 size_t size, 178 size_t size,
179 const char *filename, 179 const char *filename,
180 int linenumber) 180 int linenumber)
181{ 181{
182 void *ret; 182 void *ret;
183 183
184 /* As a security precaution, we generally do not allow very large 184 /* As a security precaution, we generally do not allow very large
185 * allocations here */ 185 * allocations here */
186 GNUNET_assert_at (size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber); 186 GNUNET_assert_at(size <= GNUNET_MAX_MALLOC_CHECKED, filename, linenumber);
187#ifdef W32_MEM_LIMIT 187#ifdef W32_MEM_LIMIT
188 size += sizeof (size_t); 188 size += sizeof(size_t);
189 if (mem_used + size > W32_MEM_LIMIT) 189 if (mem_used + size > W32_MEM_LIMIT)
190 return NULL; 190 return NULL;
191#endif 191#endif
192 GNUNET_assert_at (size < INT_MAX, filename, linenumber); 192 GNUNET_assert_at(size < INT_MAX, filename, linenumber);
193 ret = malloc (size); 193 ret = malloc(size);
194 if (ret == NULL) 194 if (ret == NULL)
195 { 195 {
196 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "malloc"); 196 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "malloc");
197 GNUNET_assert (0); 197 GNUNET_assert(0);
198 } 198 }
199#ifdef W32_MEM_LIMIT 199#ifdef W32_MEM_LIMIT
200 *((size_t *) ret) = size; 200 *((size_t *)ret) = size;
201 ret = &((size_t *) ret)[1]; 201 ret = &((size_t *)ret)[1];
202 mem_used += size; 202 mem_used += size;
203#endif 203#endif
204 GNUNET_memcpy (ret, buf, size); 204 GNUNET_memcpy(ret, buf, size);
205 return ret; 205 return ret;
206} 206}
207 207
@@ -216,26 +216,26 @@ GNUNET_xmemdup_ (const void *buf,
216 * @return pointer to size bytes of memory, NULL if we do not have enough memory 216 * @return pointer to size bytes of memory, NULL if we do not have enough memory
217 */ 217 */
218void * 218void *
219GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber) 219GNUNET_xmalloc_unchecked_(size_t size, const char *filename, int linenumber)
220{ 220{
221 void *result; 221 void *result;
222 222
223 (void) filename; 223 (void)filename;
224 (void) linenumber; 224 (void)linenumber;
225#ifdef W32_MEM_LIMIT 225#ifdef W32_MEM_LIMIT
226 size += sizeof (size_t); 226 size += sizeof(size_t);
227 if (mem_used + size > W32_MEM_LIMIT) 227 if (mem_used + size > W32_MEM_LIMIT)
228 return NULL; 228 return NULL;
229#endif 229#endif
230 230
231 result = malloc (size); 231 result = malloc(size);
232 if (NULL == result) 232 if (NULL == result)
233 return NULL; 233 return NULL;
234 memset (result, 0, size); 234 memset(result, 0, size);
235 235
236#ifdef W32_MEM_LIMIT 236#ifdef W32_MEM_LIMIT
237 *((size_t *) result) = size; 237 *((size_t *)result) = size;
238 result = &((size_t *) result)[1]; 238 result = &((size_t *)result)[1];
239 mem_used += size; 239 mem_used += size;
240#endif 240#endif
241 241
@@ -255,24 +255,24 @@ GNUNET_xmalloc_unchecked_ (size_t size, const char *filename, int linenumber)
255 * @return pointer to size bytes of memory 255 * @return pointer to size bytes of memory
256 */ 256 */
257void * 257void *
258GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber) 258GNUNET_xrealloc_(void *ptr, size_t n, const char *filename, int linenumber)
259{ 259{
260 (void) filename; 260 (void)filename;
261 (void) linenumber; 261 (void)linenumber;
262 262
263#ifdef W32_MEM_LIMIT 263#ifdef W32_MEM_LIMIT
264 n += sizeof (size_t); 264 n += sizeof(size_t);
265 ptr = &((size_t *) ptr)[-1]; 265 ptr = &((size_t *)ptr)[-1];
266 mem_used = mem_used - *((size_t *) ptr) + n; 266 mem_used = mem_used - *((size_t *)ptr) + n;
267#endif 267#endif
268 ptr = realloc (ptr, n); 268 ptr = realloc(ptr, n);
269 if ((NULL == ptr) && (n > 0)) 269 if ((NULL == ptr) && (n > 0))
270 { 270 {
271 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "realloc"); 271 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "realloc");
272 GNUNET_assert (0); 272 GNUNET_assert(0);
273 } 273 }
274#ifdef W32_MEM_LIMIT 274#ifdef W32_MEM_LIMIT
275 ptr = &((size_t *) ptr)[1]; 275 ptr = &((size_t *)ptr)[1];
276#endif 276#endif
277 return ptr; 277 return ptr;
278} 278}
@@ -286,15 +286,15 @@ GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber)
286#endif 286#endif
287 287
288#if WINDOWS 288#if WINDOWS
289#define M_SIZE(p) _msize (p) 289#define M_SIZE(p) _msize(p)
290#endif 290#endif
291#if HAVE_MALLOC_NP_H 291#if HAVE_MALLOC_NP_H
292#include <malloc_np.h> 292#include <malloc_np.h>
293#endif 293#endif
294#if HAVE_MALLOC_USABLE_SIZE 294#if HAVE_MALLOC_USABLE_SIZE
295#define M_SIZE(p) malloc_usable_size (p) 295#define M_SIZE(p) malloc_usable_size(p)
296#elif HAVE_MALLOC_SIZE 296#elif HAVE_MALLOC_SIZE
297#define M_SIZE(p) malloc_size (p) 297#define M_SIZE(p) malloc_size(p)
298#endif 298#endif
299 299
300/** 300/**
@@ -306,28 +306,28 @@ GNUNET_xrealloc_ (void *ptr, size_t n, const char *filename, int linenumber)
306 * @param linenumber where in the code was the call to GNUNET_free 306 * @param linenumber where in the code was the call to GNUNET_free
307 */ 307 */
308void 308void
309GNUNET_xfree_ (void *ptr, const char *filename, int linenumber) 309GNUNET_xfree_(void *ptr, const char *filename, int linenumber)
310{ 310{
311 GNUNET_assert_at (NULL != ptr, filename, linenumber); 311 GNUNET_assert_at(NULL != ptr, filename, linenumber);
312#ifdef W32_MEM_LIMIT 312#ifdef W32_MEM_LIMIT
313 ptr = &((size_t *) ptr)[-1]; 313 ptr = &((size_t *)ptr)[-1];
314 mem_used -= *((size_t *) ptr); 314 mem_used -= *((size_t *)ptr);
315#endif 315#endif
316#if defined(M_SIZE) 316#if defined(M_SIZE)
317#if ENABLE_POISONING 317#if ENABLE_POISONING
318 { 318 {
319 const uint64_t baadfood = GNUNET_ntohll (0xBAADF00DBAADF00DLL); 319 const uint64_t baadfood = GNUNET_ntohll(0xBAADF00DBAADF00DLL);
320 uint64_t *base = ptr; 320 uint64_t *base = ptr;
321 size_t s = M_SIZE (ptr); 321 size_t s = M_SIZE(ptr);
322 size_t i; 322 size_t i;
323 323
324 for (i = 0; i < s / 8; i++) 324 for (i = 0; i < s / 8; i++)
325 base[i] = baadfood; 325 base[i] = baadfood;
326 GNUNET_memcpy (&base[s / 8], &baadfood, s % 8); 326 GNUNET_memcpy(&base[s / 8], &baadfood, s % 8);
327 } 327 }
328#endif 328#endif
329#endif 329#endif
330 free (ptr); 330 free(ptr);
331} 331}
332 332
333 333
@@ -340,26 +340,26 @@ GNUNET_xfree_ (void *ptr, const char *filename, int linenumber)
340 * @return `strdup(@a str)` 340 * @return `strdup(@a str)`
341 */ 341 */
342char * 342char *
343GNUNET_xstrdup_ (const char *str, const char *filename, int linenumber) 343GNUNET_xstrdup_(const char *str, const char *filename, int linenumber)
344{ 344{
345 char *res; 345 char *res;
346 size_t slen; 346 size_t slen;
347 347
348 GNUNET_assert_at (str != NULL, filename, linenumber); 348 GNUNET_assert_at(str != NULL, filename, linenumber);
349 slen = strlen (str) + 1; 349 slen = strlen(str) + 1;
350 res = GNUNET_xmalloc_ (slen, filename, linenumber); 350 res = GNUNET_xmalloc_(slen, filename, linenumber);
351 GNUNET_memcpy (res, str, slen); 351 GNUNET_memcpy(res, str, slen);
352 return res; 352 return res;
353} 353}
354 354
355 355
356#if ! HAVE_STRNLEN 356#if !HAVE_STRNLEN
357static size_t 357static size_t
358strnlen (const char *s, size_t n) 358strnlen(const char *s, size_t n)
359{ 359{
360 const char *e; 360 const char *e;
361 361
362 e = memchr (s, '\0', n); 362 e = memchr(s, '\0', n);
363 if (NULL == e) 363 if (NULL == e)
364 return n; 364 return n;
365 return e - s; 365 return e - s;
@@ -377,19 +377,19 @@ strnlen (const char *s, size_t n)
377 * @return `strndup(@a str,@a len)` 377 * @return `strndup(@a str,@a len)`
378 */ 378 */
379char * 379char *
380GNUNET_xstrndup_ (const char *str, 380GNUNET_xstrndup_(const char *str,
381 size_t len, 381 size_t len,
382 const char *filename, 382 const char *filename,
383 int linenumber) 383 int linenumber)
384{ 384{
385 char *res; 385 char *res;
386 386
387 if (0 == len) 387 if (0 == len)
388 return GNUNET_strdup (""); 388 return GNUNET_strdup("");
389 GNUNET_assert_at (NULL != str, filename, linenumber); 389 GNUNET_assert_at(NULL != str, filename, linenumber);
390 len = strnlen (str, len); 390 len = strnlen(str, len);
391 res = GNUNET_xmalloc_ (len + 1, filename, linenumber); 391 res = GNUNET_xmalloc_(len + 1, filename, linenumber);
392 GNUNET_memcpy (res, str, len); 392 GNUNET_memcpy(res, str, len);
393 /* res[len] = '\0'; 'malloc' zeros out anyway */ 393 /* res[len] = '\0'; 'malloc' zeros out anyway */
394 return res; 394 return res;
395} 395}
@@ -408,35 +408,35 @@ GNUNET_xstrndup_ (const char *str,
408 * @param linenumber where in the code was the call to GNUNET_array_grow() 408 * @param linenumber where in the code was the call to GNUNET_array_grow()
409 */ 409 */
410void 410void
411GNUNET_xgrow_ (void **old, 411GNUNET_xgrow_(void **old,
412 size_t elementSize, 412 size_t elementSize,
413 unsigned int *oldCount, 413 unsigned int *oldCount,
414 unsigned int newCount, 414 unsigned int newCount,
415 const char *filename, 415 const char *filename,
416 int linenumber) 416 int linenumber)
417{ 417{
418 void *tmp; 418 void *tmp;
419 size_t size; 419 size_t size;
420 420
421 GNUNET_assert_at (INT_MAX / elementSize > newCount, filename, linenumber); 421 GNUNET_assert_at(INT_MAX / elementSize > newCount, filename, linenumber);
422 size = newCount * elementSize; 422 size = newCount * elementSize;
423 if (0 == size) 423 if (0 == size)
424 { 424 {
425 tmp = NULL; 425 tmp = NULL;
426 } 426 }
427 else 427 else
428 {
429 tmp = GNUNET_xmalloc_ (size, filename, linenumber);
430 if (NULL != *old)
431 { 428 {
432 GNUNET_memcpy (tmp, *old, elementSize * GNUNET_MIN (*oldCount, newCount)); 429 tmp = GNUNET_xmalloc_(size, filename, linenumber);
430 if (NULL != *old)
431 {
432 GNUNET_memcpy(tmp, *old, elementSize * GNUNET_MIN(*oldCount, newCount));
433 }
433 } 434 }
434 }
435 435
436 if (NULL != *old) 436 if (NULL != *old)
437 { 437 {
438 GNUNET_xfree_ (*old, filename, linenumber); 438 GNUNET_xfree_(*old, filename, linenumber);
439 } 439 }
440 *old = tmp; 440 *old = tmp;
441 *oldCount = newCount; 441 *oldCount = newCount;
442} 442}
@@ -451,19 +451,19 @@ GNUNET_xgrow_ (void **old,
451 * @return number of bytes in `*@a buf`, excluding 0-termination 451 * @return number of bytes in `*@a buf`, excluding 0-termination
452 */ 452 */
453int 453int
454GNUNET_asprintf (char **buf, const char *format, ...) 454GNUNET_asprintf(char **buf, const char *format, ...)
455{ 455{
456 int ret; 456 int ret;
457 va_list args; 457 va_list args;
458 458
459 va_start (args, format); 459 va_start(args, format);
460 ret = vsnprintf (NULL, 0, format, args); 460 ret = vsnprintf(NULL, 0, format, args);
461 va_end (args); 461 va_end(args);
462 GNUNET_assert (ret >= 0); 462 GNUNET_assert(ret >= 0);
463 *buf = GNUNET_malloc (ret + 1); 463 *buf = GNUNET_malloc(ret + 1);
464 va_start (args, format); 464 va_start(args, format);
465 ret = vsprintf (*buf, format, args); 465 ret = vsprintf(*buf, format, args);
466 va_end (args); 466 va_end(args);
467 return ret; 467 return ret;
468} 468}
469 469
@@ -478,15 +478,15 @@ GNUNET_asprintf (char **buf, const char *format, ...)
478 * @return number of bytes written to buf or negative value on error 478 * @return number of bytes written to buf or negative value on error
479 */ 479 */
480int 480int
481GNUNET_snprintf (char *buf, size_t size, const char *format, ...) 481GNUNET_snprintf(char *buf, size_t size, const char *format, ...)
482{ 482{
483 int ret; 483 int ret;
484 va_list args; 484 va_list args;
485 485
486 va_start (args, format); 486 va_start(args, format);
487 ret = vsnprintf (buf, size, format, args); 487 ret = vsnprintf(buf, size, format, args);
488 va_end (args); 488 va_end(args);
489 GNUNET_assert ((ret >= 0) && (((size_t) ret) < size)); 489 GNUNET_assert((ret >= 0) && (((size_t)ret) < size));
490 return ret; 490 return ret;
491} 491}
492 492
@@ -498,15 +498,15 @@ GNUNET_snprintf (char *buf, size_t size, const char *format, ...)
498 * @return duplicate of the message 498 * @return duplicate of the message
499 */ 499 */
500struct GNUNET_MessageHeader * 500struct GNUNET_MessageHeader *
501GNUNET_copy_message (const struct GNUNET_MessageHeader *msg) 501GNUNET_copy_message(const struct GNUNET_MessageHeader *msg)
502{ 502{
503 struct GNUNET_MessageHeader *ret; 503 struct GNUNET_MessageHeader *ret;
504 uint16_t msize; 504 uint16_t msize;
505 505
506 msize = ntohs (msg->size); 506 msize = ntohs(msg->size);
507 GNUNET_assert (msize >= sizeof (struct GNUNET_MessageHeader)); 507 GNUNET_assert(msize >= sizeof(struct GNUNET_MessageHeader));
508 ret = GNUNET_malloc (msize); 508 ret = GNUNET_malloc(msize);
509 GNUNET_memcpy (ret, msg, msize); 509 GNUNET_memcpy(ret, msg, msize);
510 return ret; 510 return ret;
511} 511}
512 512
diff --git a/src/util/common_endian.c b/src/util/common_endian.c
index d7daa2d79..6ec203dd9 100644
--- a/src/util/common_endian.c
+++ b/src/util/common_endian.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/common_endian.c 22 * @file util/common_endian.c
@@ -28,16 +28,16 @@
28#include "platform.h" 28#include "platform.h"
29#include "gnunet_crypto_lib.h" 29#include "gnunet_crypto_lib.h"
30 30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-common-endian",__VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-common-endian", __VA_ARGS__)
32 32
33 33
34uint64_t 34uint64_t
35GNUNET_htonll (uint64_t n) 35GNUNET_htonll(uint64_t n)
36{ 36{
37#if __BYTE_ORDER == __BIG_ENDIAN 37#if __BYTE_ORDER == __BIG_ENDIAN
38 return n; 38 return n;
39#elif __BYTE_ORDER == __LITTLE_ENDIAN 39#elif __BYTE_ORDER == __LITTLE_ENDIAN
40 return (((uint64_t) htonl (n)) << 32) + htonl (n >> 32); 40 return (((uint64_t)htonl(n)) << 32) + htonl(n >> 32);
41#else 41#else
42 #error byteorder undefined 42 #error byteorder undefined
43#endif 43#endif
@@ -45,12 +45,12 @@ GNUNET_htonll (uint64_t n)
45 45
46 46
47uint64_t 47uint64_t
48GNUNET_ntohll (uint64_t n) 48GNUNET_ntohll(uint64_t n)
49{ 49{
50#if __BYTE_ORDER == __BIG_ENDIAN 50#if __BYTE_ORDER == __BIG_ENDIAN
51 return n; 51 return n;
52#elif __BYTE_ORDER == __LITTLE_ENDIAN 52#elif __BYTE_ORDER == __LITTLE_ENDIAN
53 return (((uint64_t) ntohl (n)) << 32) + ntohl (n >> 32); 53 return (((uint64_t)ntohl(n)) << 32) + ntohl(n >> 32);
54#else 54#else
55 #error byteorder undefined 55 #error byteorder undefined
56#endif 56#endif
@@ -63,11 +63,11 @@ GNUNET_ntohll (uint64_t n)
63 * @return the same value in host byte order 63 * @return the same value in host byte order
64 */ 64 */
65double 65double
66GNUNET_hton_double (double d) 66GNUNET_hton_double(double d)
67{ 67{
68 double res; 68 double res;
69 uint64_t *in = (uint64_t *) &d; 69 uint64_t *in = (uint64_t *)&d;
70 uint64_t *out = (uint64_t *) &res; 70 uint64_t *out = (uint64_t *)&res;
71 71
72 out[0] = GNUNET_htonll(in[0]); 72 out[0] = GNUNET_htonll(in[0]);
73 73
@@ -81,11 +81,11 @@ GNUNET_hton_double (double d)
81 * @return the same value in host byte order 81 * @return the same value in host byte order
82 */ 82 */
83double 83double
84GNUNET_ntoh_double (double d) 84GNUNET_ntoh_double(double d)
85{ 85{
86 double res; 86 double res;
87 uint64_t *in = (uint64_t *) &d; 87 uint64_t *in = (uint64_t *)&d;
88 uint64_t *out = (uint64_t *) &res; 88 uint64_t *out = (uint64_t *)&res;
89 89
90 out[0] = GNUNET_ntohll(in[0]); 90 out[0] = GNUNET_ntohll(in[0]);
91 91
diff --git a/src/util/common_logging.c b/src/util/common_logging.c
index d3666ae7d..4c7a5291f 100644
--- a/src/util/common_logging.c
+++ b/src/util/common_logging.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/common_logging.c 22 * @file util/common_logging.c
@@ -77,8 +77,7 @@
77/** 77/**
78 * Linked list of active loggers. 78 * Linked list of active loggers.
79 */ 79 */
80struct CustomLogger 80struct CustomLogger {
81{
82 /** 81 /**
83 * This is a linked list. 82 * This is a linked list.
84 */ 83 */
@@ -167,8 +166,7 @@ static FILE *GNUNET_stderr;
167/** 166/**
168 * Represents a single logging definition 167 * Represents a single logging definition
169 */ 168 */
170struct LogDef 169struct LogDef {
171{
172 /** 170 /**
173 * Component name regex 171 * Component name regex
174 */ 172 */
@@ -211,7 +209,7 @@ struct LogDef
211}; 209};
212 210
213 211
214#if ! defined(GNUNET_CULL_LOGGING) 212#if !defined(GNUNET_CULL_LOGGING)
215/** 213/**
216 * Dynamic array of logging definitions 214 * Dynamic array of logging definitions
217 */ 215 */
@@ -259,21 +257,21 @@ static LARGE_INTEGER performance_frequency;
259 * @return GNUNET_GE_INVALID if log does not parse 257 * @return GNUNET_GE_INVALID if log does not parse
260 */ 258 */
261static enum GNUNET_ErrorType 259static enum GNUNET_ErrorType
262get_type (const char *log) 260get_type(const char *log)
263{ 261{
264 if (NULL == log) 262 if (NULL == log)
265 return GNUNET_ERROR_TYPE_UNSPECIFIED; 263 return GNUNET_ERROR_TYPE_UNSPECIFIED;
266 if (0 == strcasecmp (log, _ ("DEBUG"))) 264 if (0 == strcasecmp(log, _("DEBUG")))
267 return GNUNET_ERROR_TYPE_DEBUG; 265 return GNUNET_ERROR_TYPE_DEBUG;
268 if (0 == strcasecmp (log, _ ("INFO"))) 266 if (0 == strcasecmp(log, _("INFO")))
269 return GNUNET_ERROR_TYPE_INFO; 267 return GNUNET_ERROR_TYPE_INFO;
270 if (0 == strcasecmp (log, _ ("MESSAGE"))) 268 if (0 == strcasecmp(log, _("MESSAGE")))
271 return GNUNET_ERROR_TYPE_MESSAGE; 269 return GNUNET_ERROR_TYPE_MESSAGE;
272 if (0 == strcasecmp (log, _ ("WARNING"))) 270 if (0 == strcasecmp(log, _("WARNING")))
273 return GNUNET_ERROR_TYPE_WARNING; 271 return GNUNET_ERROR_TYPE_WARNING;
274 if (0 == strcasecmp (log, _ ("ERROR"))) 272 if (0 == strcasecmp(log, _("ERROR")))
275 return GNUNET_ERROR_TYPE_ERROR; 273 return GNUNET_ERROR_TYPE_ERROR;
276 if (0 == strcasecmp (log, _ ("NONE"))) 274 if (0 == strcasecmp(log, _("NONE")))
277 return GNUNET_ERROR_TYPE_NONE; 275 return GNUNET_ERROR_TYPE_NONE;
278 return GNUNET_ERROR_TYPE_INVALID; 276 return GNUNET_ERROR_TYPE_INVALID;
279} 277}
@@ -283,35 +281,35 @@ get_type (const char *log)
283 * Abort the process, generate a core dump if possible. 281 * Abort the process, generate a core dump if possible.
284 */ 282 */
285void 283void
286GNUNET_abort_ () 284GNUNET_abort_()
287{ 285{
288#if WINDOWS 286#if WINDOWS
289 DebugBreak (); 287 DebugBreak();
290#endif 288#endif
291 abort (); 289 abort();
292} 290}
293 291
294 292
295#if ! defined(GNUNET_CULL_LOGGING) 293#if !defined(GNUNET_CULL_LOGGING)
296/** 294/**
297 * Utility function - reallocates logdefs array to be twice as large. 295 * Utility function - reallocates logdefs array to be twice as large.
298 */ 296 */
299static void 297static void
300resize_logdefs () 298resize_logdefs()
301{ 299{
302 logdefs_size = (logdefs_size + 1) * 2; 300 logdefs_size = (logdefs_size + 1) * 2;
303 logdefs = GNUNET_realloc (logdefs, logdefs_size * sizeof (struct LogDef)); 301 logdefs = GNUNET_realloc(logdefs, logdefs_size * sizeof(struct LogDef));
304} 302}
305 303
306 304
307#if ! TALER_WALLET_ONLY 305#if !TALER_WALLET_ONLY
308/** 306/**
309 * Rotate logs, deleting the oldest log. 307 * Rotate logs, deleting the oldest log.
310 * 308 *
311 * @param new_name new name to add to the rotation 309 * @param new_name new name to add to the rotation
312 */ 310 */
313static void 311static void
314log_rotate (const char *new_name) 312log_rotate(const char *new_name)
315{ 313{
316 static char *rotation[ROTATION_KEEP]; 314 static char *rotation[ROTATION_KEEP];
317 static unsigned int rotation_off; 315 static unsigned int rotation_off;
@@ -321,13 +319,13 @@ log_rotate (const char *new_name)
321 return; /* not a real log file name */ 319 return; /* not a real log file name */
322 discard = rotation[rotation_off % ROTATION_KEEP]; 320 discard = rotation[rotation_off % ROTATION_KEEP];
323 if (NULL != discard) 321 if (NULL != discard)
324 { 322 {
325 /* Note: can't log errors during logging (recursion!), so this 323 /* Note: can't log errors during logging (recursion!), so this
326 operation MUST silently fail... */ 324 operation MUST silently fail... */
327 (void) unlink (discard); 325 (void)unlink(discard);
328 GNUNET_free (discard); 326 GNUNET_free(discard);
329 } 327 }
330 rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup (new_name); 328 rotation[rotation_off % ROTATION_KEEP] = GNUNET_strdup(new_name);
331 rotation_off++; 329 rotation_off++;
332} 330}
333 331
@@ -339,7 +337,7 @@ log_rotate (const char *new_name)
339 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 337 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
340 */ 338 */
341static int 339static int
342setup_log_file (const struct tm *tm) 340setup_log_file(const struct tm *tm)
343{ 341{
344 static char last_fn[PATH_MAX + 1]; 342 static char last_fn[PATH_MAX + 1];
345 char fn[PATH_MAX + 1]; 343 char fn[PATH_MAX + 1];
@@ -350,68 +348,68 @@ setup_log_file (const struct tm *tm)
350 348
351 if (NULL == log_file_name) 349 if (NULL == log_file_name)
352 return GNUNET_SYSERR; 350 return GNUNET_SYSERR;
353 if (0 == strftime (fn, sizeof (fn), log_file_name, tm)) 351 if (0 == strftime(fn, sizeof(fn), log_file_name, tm))
354 return GNUNET_SYSERR; 352 return GNUNET_SYSERR;
355 leftsquare = strrchr (fn, '['); 353 leftsquare = strrchr(fn, '[');
356 if ((NULL != leftsquare) && (']' == leftsquare[1])) 354 if ((NULL != leftsquare) && (']' == leftsquare[1]))
357 { 355 {
358 char *logfile_copy = GNUNET_strdup (fn); 356 char *logfile_copy = GNUNET_strdup(fn);
359 357
360 logfile_copy[leftsquare - fn] = '\0'; 358 logfile_copy[leftsquare - fn] = '\0';
361 logfile_copy[leftsquare - fn + 1] = '\0'; 359 logfile_copy[leftsquare - fn + 1] = '\0';
362 snprintf (fn, 360 snprintf(fn,
363 PATH_MAX, 361 PATH_MAX,
364 "%s%d%s", 362 "%s%d%s",
365 logfile_copy, 363 logfile_copy,
366 getpid (), 364 getpid(),
367 &logfile_copy[leftsquare - fn + 2]); 365 &logfile_copy[leftsquare - fn + 2]);
368 GNUNET_free (logfile_copy); 366 GNUNET_free(logfile_copy);
369 } 367 }
370 if (0 == strcmp (fn, last_fn)) 368 if (0 == strcmp(fn, last_fn))
371 return GNUNET_OK; /* no change */ 369 return GNUNET_OK; /* no change */
372 log_rotate (last_fn); 370 log_rotate(last_fn);
373 strcpy (last_fn, fn); 371 strcpy(last_fn, fn);
374 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (fn)) 372 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file(fn))
375 { 373 {
376 fprintf (stderr, 374 fprintf(stderr,
377 "Failed to create directory for `%s': %s\n", 375 "Failed to create directory for `%s': %s\n",
378 fn, 376 fn,
379 strerror (errno)); 377 strerror(errno));
380 return GNUNET_SYSERR; 378 return GNUNET_SYSERR;
381 } 379 }
382#if WINDOWS 380#if WINDOWS
383 altlog_fd = 381 altlog_fd =
384 open (fn, O_APPEND | O_BINARY | O_WRONLY | O_CREAT, _S_IREAD | _S_IWRITE); 382 open(fn, O_APPEND | O_BINARY | O_WRONLY | O_CREAT, _S_IREAD | _S_IWRITE);
385#else 383#else
386 altlog_fd = open (fn, 384 altlog_fd = open(fn,
387 O_APPEND | O_WRONLY | O_CREAT, 385 O_APPEND | O_WRONLY | O_CREAT,
388 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); 386 S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
389#endif 387#endif
390 if (-1 != altlog_fd) 388 if (-1 != altlog_fd)
391 {
392 if (NULL != GNUNET_stderr)
393 fclose (GNUNET_stderr);
394 dup_return = dup2 (altlog_fd, 2);
395 (void) close (altlog_fd);
396 if (-1 != dup_return)
397 { 389 {
398 altlog = fdopen (2, "ab"); 390 if (NULL != GNUNET_stderr)
399 if (NULL == altlog) 391 fclose(GNUNET_stderr);
400 { 392 dup_return = dup2(altlog_fd, 2);
401 (void) close (2); 393 (void)close(altlog_fd);
402 altlog_fd = -1; 394 if (-1 != dup_return)
403 } 395 {
396 altlog = fdopen(2, "ab");
397 if (NULL == altlog)
398 {
399 (void)close(2);
400 altlog_fd = -1;
401 }
402 }
403 else
404 {
405 altlog_fd = -1;
406 }
404 } 407 }
405 else 408 if (-1 == altlog_fd)
406 { 409 {
407 altlog_fd = -1; 410 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", fn);
411 return GNUNET_SYSERR;
408 } 412 }
409 }
410 if (-1 == altlog_fd)
411 {
412 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", fn);
413 return GNUNET_SYSERR;
414 }
415 GNUNET_stderr = altlog; 413 GNUNET_stderr = altlog;
416 return GNUNET_OK; 414 return GNUNET_OK;
417} 415}
@@ -431,44 +429,44 @@ setup_log_file (const struct tm *tm)
431 * @return 0 on success, regex-specific error otherwise 429 * @return 0 on success, regex-specific error otherwise
432 */ 430 */
433static int 431static int
434add_definition (const char *component, 432add_definition(const char *component,
435 const char *file, 433 const char *file,
436 const char *function, 434 const char *function,
437 int from_line, 435 int from_line,
438 int to_line, 436 int to_line,
439 int level, 437 int level,
440 int force) 438 int force)
441{ 439{
442 struct LogDef n; 440 struct LogDef n;
443 int r; 441 int r;
444 442
445 if (logdefs_size == logdefs_len) 443 if (logdefs_size == logdefs_len)
446 resize_logdefs (); 444 resize_logdefs();
447 memset (&n, 0, sizeof (n)); 445 memset(&n, 0, sizeof(n));
448 if (0 == strlen (component)) 446 if (0 == strlen(component))
449 component = (char *) ".*"; 447 component = (char *)".*";
450 r = regcomp (&n.component_regex, (const char *) component, REG_NOSUB); 448 r = regcomp(&n.component_regex, (const char *)component, REG_NOSUB);
451 if (0 != r) 449 if (0 != r)
452 { 450 {
453 return r; 451 return r;
454 } 452 }
455 if (0 == strlen (file)) 453 if (0 == strlen(file))
456 file = (char *) ".*"; 454 file = (char *)".*";
457 r = regcomp (&n.file_regex, (const char *) file, REG_NOSUB); 455 r = regcomp(&n.file_regex, (const char *)file, REG_NOSUB);
458 if (0 != r) 456 if (0 != r)
459 { 457 {
460 regfree (&n.component_regex); 458 regfree(&n.component_regex);
461 return r; 459 return r;
462 } 460 }
463 if ((NULL == function) || (0 == strlen (function))) 461 if ((NULL == function) || (0 == strlen(function)))
464 function = (char *) ".*"; 462 function = (char *)".*";
465 r = regcomp (&n.function_regex, (const char *) function, REG_NOSUB); 463 r = regcomp(&n.function_regex, (const char *)function, REG_NOSUB);
466 if (0 != r) 464 if (0 != r)
467 { 465 {
468 regfree (&n.component_regex); 466 regfree(&n.component_regex);
469 regfree (&n.file_regex); 467 regfree(&n.file_regex);
470 return r; 468 return r;
471 } 469 }
472 n.from_line = from_line; 470 n.from_line = from_line;
473 n.to_line = to_line; 471 n.to_line = to_line;
474 n.level = level; 472 n.level = level;
@@ -492,11 +490,11 @@ add_definition (const char *component,
492 * @return 0 to disallow the call, 1 to allow it 490 * @return 0 to disallow the call, 1 to allow it
493 */ 491 */
494int 492int
495GNUNET_get_log_call_status (int caller_level, 493GNUNET_get_log_call_status(int caller_level,
496 const char *comp, 494 const char *comp,
497 const char *file, 495 const char *file,
498 const char *function, 496 const char *function,
499 int line) 497 int line)
500{ 498{
501 struct LogDef *ld; 499 struct LogDef *ld;
502 int i; 500 int i;
@@ -515,18 +513,18 @@ GNUNET_get_log_call_status (int caller_level,
515 /* Only look for forced definitions? */ 513 /* Only look for forced definitions? */
516 force_only = min_level >= 0; 514 force_only = min_level >= 0;
517 for (i = 0; i < logdefs_len; i++) 515 for (i = 0; i < logdefs_len; i++)
518 {
519 ld = &logdefs[i];
520 if (((! force_only) || ld->force) &&
521 (line >= ld->from_line && line <= ld->to_line) &&
522 (0 == regexec (&ld->component_regex, comp, 0, NULL, 0)) &&
523 (0 == regexec (&ld->file_regex, file, 0, NULL, 0)) &&
524 (0 == regexec (&ld->function_regex, function, 0, NULL, 0)))
525 { 516 {
526 /* We're finished */ 517 ld = &logdefs[i];
527 return caller_level <= ld->level; 518 if (((!force_only) || ld->force) &&
519 (line >= ld->from_line && line <= ld->to_line) &&
520 (0 == regexec(&ld->component_regex, comp, 0, NULL, 0)) &&
521 (0 == regexec(&ld->file_regex, file, 0, NULL, 0)) &&
522 (0 == regexec(&ld->function_regex, function, 0, NULL, 0)))
523 {
524 /* We're finished */
525 return caller_level <= ld->level;
526 }
528 } 527 }
529 }
530 /* No matches - use global level, if defined */ 528 /* No matches - use global level, if defined */
531 if (min_level >= 0) 529 if (min_level >= 0)
532 return caller_level <= min_level; 530 return caller_level <= min_level;
@@ -562,7 +560,7 @@ GNUNET_get_log_call_status (int caller_level,
562 * @return number of added definitions 560 * @return number of added definitions
563 */ 561 */
564static int 562static int
565parse_definitions (const char *constname, int force) 563parse_definitions(const char *constname, int force)
566{ 564{
567 char *def; 565 char *def;
568 const char *tmp; 566 const char *tmp;
@@ -578,108 +576,116 @@ parse_definitions (const char *constname, int force)
578 int counter = 0; 576 int counter = 0;
579 int keep_looking = 1; 577 int keep_looking = 1;
580 578
581 tmp = getenv (constname); 579 tmp = getenv(constname);
582 if (NULL == tmp) 580 if (NULL == tmp)
583 return 0; 581 return 0;
584 def = GNUNET_strdup (tmp); 582 def = GNUNET_strdup(tmp);
585 from_line = 0; 583 from_line = 0;
586 to_line = INT_MAX; 584 to_line = INT_MAX;
587 for (p = def, state = 0, start = def; keep_looking; p++) 585 for (p = def, state = 0, start = def; keep_looking; p++)
588 {
589 switch (p[0])
590 { 586 {
591 case ';': /* found a field separator */ 587 switch (p[0])
592 p[0] = '\0';
593 switch (state)
594 {
595 case 0: /* within a component name */
596 comp = start;
597 break;
598 case 1: /* within a file name */
599 file = start;
600 break;
601 case 2: /* within a function name */
602 /* after a file name there must be a function name */
603 function = start;
604 break;
605 case 3: /* within a from-to line range */
606 if (strlen (start) > 0)
607 { 588 {
608 errno = 0; 589 case ';': /* found a field separator */
609 from_line = strtol (start, &t, 10); 590 p[0] = '\0';
610 if ((0 != errno) || (from_line < 0)) 591 switch (state)
611 {
612 GNUNET_free (def);
613 return counter;
614 }
615 if ((t < p) && ('-' == t[0]))
616 {
617 errno = 0;
618 start = t + 1;
619 to_line = strtol (start, &t, 10);
620 if ((0 != errno) || (to_line < 0) || (t != p))
621 { 592 {
622 GNUNET_free (def); 593 case 0: /* within a component name */
623 return counter; 594 comp = start;
595 break;
596
597 case 1: /* within a file name */
598 file = start;
599 break;
600
601 case 2: /* within a function name */
602 /* after a file name there must be a function name */
603 function = start;
604 break;
605
606 case 3: /* within a from-to line range */
607 if (strlen(start) > 0)
608 {
609 errno = 0;
610 from_line = strtol(start, &t, 10);
611 if ((0 != errno) || (from_line < 0))
612 {
613 GNUNET_free(def);
614 return counter;
615 }
616 if ((t < p) && ('-' == t[0]))
617 {
618 errno = 0;
619 start = t + 1;
620 to_line = strtol(start, &t, 10);
621 if ((0 != errno) || (to_line < 0) || (t != p))
622 {
623 GNUNET_free(def);
624 return counter;
625 }
626 }
627 else /* one number means "match this line only" */
628 to_line = from_line;
629 }
630 else /* default to 0-max */
631 {
632 from_line = 0;
633 to_line = INT_MAX;
634 }
635 break;
636
637 default:
638 fprintf(
639 stderr,
640 _("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
641 p);
642 break;
624 } 643 }
625 } 644 start = p + 1;
626 else /* one number means "match this line only" */ 645 state++;
627 to_line = from_line; 646 break;
628 } 647
629 else /* default to 0-max */ 648 case '\0': /* found EOL */
630 { 649 keep_looking = 0;
631 from_line = 0; 650
632 to_line = INT_MAX; 651 /* fall through to '/' */
633 } 652 case '/': /* found a definition separator */
634 break; 653 switch (state)
635 default: 654 {
636 fprintf ( 655 case 4: /* within a log level */
637 stderr, 656 p[0] = '\0';
638 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"), 657 state = 0;
639 p); 658 level = get_type((const char *)start);
640 break; 659 if ((GNUNET_ERROR_TYPE_INVALID == level) ||
641 } 660 (GNUNET_ERROR_TYPE_UNSPECIFIED == level) ||
642 start = p + 1; 661 (0 != add_definition(comp,
643 state++; 662 file,
644 break; 663 function,
645 case '\0': /* found EOL */ 664 from_line,
646 keep_looking = 0; 665 to_line,
647 /* fall through to '/' */ 666 level,
648 case '/': /* found a definition separator */ 667 force)))
649 switch (state) 668 {
650 { 669 GNUNET_free(def);
651 case 4: /* within a log level */ 670 return counter;
652 p[0] = '\0'; 671 }
653 state = 0; 672 counter++;
654 level = get_type ((const char *) start); 673 start = p + 1;
655 if ((GNUNET_ERROR_TYPE_INVALID == level) || 674 break;
656 (GNUNET_ERROR_TYPE_UNSPECIFIED == level) || 675
657 (0 != add_definition (comp, 676 default:
658 file, 677 fprintf(
659 function, 678 stderr,
660 from_line, 679 _("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
661 to_line, 680 p);
662 level, 681 break;
663 force))) 682 }
664 { 683
665 GNUNET_free (def); 684 default:
666 return counter; 685 break;
667 } 686 }
668 counter++;
669 start = p + 1;
670 break;
671 default:
672 fprintf (
673 stderr,
674 _ ("ERROR: Unable to parse log definition: Syntax error at `%s'.\n"),
675 p);
676 break;
677 }
678 default:
679 break;
680 } 687 }
681 } 688 GNUNET_free(def);
682 GNUNET_free (def);
683 return counter; 689 return counter;
684} 690}
685 691
@@ -688,15 +694,15 @@ parse_definitions (const char *constname, int force)
688 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG. 694 * Utility function - parses GNUNET_LOG and GNUNET_FORCE_LOG.
689 */ 695 */
690static void 696static void
691parse_all_definitions () 697parse_all_definitions()
692{ 698{
693 if (GNUNET_NO == gnunet_force_log_parsed) 699 if (GNUNET_NO == gnunet_force_log_parsed)
694 gnunet_force_log_present = 700 gnunet_force_log_present =
695 parse_definitions ("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO; 701 parse_definitions("GNUNET_FORCE_LOG", 1) > 0 ? GNUNET_YES : GNUNET_NO;
696 gnunet_force_log_parsed = GNUNET_YES; 702 gnunet_force_log_parsed = GNUNET_YES;
697 703
698 if (GNUNET_NO == gnunet_log_parsed) 704 if (GNUNET_NO == gnunet_log_parsed)
699 parse_definitions ("GNUNET_LOG", 0); 705 parse_definitions("GNUNET_LOG", 0);
700 gnunet_log_parsed = GNUNET_YES; 706 gnunet_log_parsed = GNUNET_YES;
701} 707}
702#endif 708#endif
@@ -711,43 +717,43 @@ parse_all_definitions ()
711 * @return #GNUNET_OK on success 717 * @return #GNUNET_OK on success
712 */ 718 */
713int 719int
714GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile) 720GNUNET_log_setup(const char *comp, const char *loglevel, const char *logfile)
715{ 721{
716 const char *env_logfile; 722 const char *env_logfile;
717 723
718 min_level = get_type (loglevel); 724 min_level = get_type(loglevel);
719#if ! defined(GNUNET_CULL_LOGGING) 725#if !defined(GNUNET_CULL_LOGGING)
720 parse_all_definitions (); 726 parse_all_definitions();
721#endif 727#endif
722#ifdef WINDOWS 728#ifdef WINDOWS
723 QueryPerformanceFrequency (&performance_frequency); 729 QueryPerformanceFrequency(&performance_frequency);
724#endif 730#endif
725 GNUNET_free_non_null (component); 731 GNUNET_free_non_null(component);
726 GNUNET_asprintf (&component, "%s-%d", comp, getpid ()); 732 GNUNET_asprintf(&component, "%s-%d", comp, getpid());
727 GNUNET_free_non_null (component_nopid); 733 GNUNET_free_non_null(component_nopid);
728 component_nopid = GNUNET_strdup (comp); 734 component_nopid = GNUNET_strdup(comp);
729 735
730 env_logfile = getenv ("GNUNET_FORCE_LOGFILE"); 736 env_logfile = getenv("GNUNET_FORCE_LOGFILE");
731 if ((NULL != env_logfile) && (strlen (env_logfile) > 0)) 737 if ((NULL != env_logfile) && (strlen(env_logfile) > 0))
732 logfile = env_logfile; 738 logfile = env_logfile;
733 if (NULL == logfile) 739 if (NULL == logfile)
734 return GNUNET_OK; 740 return GNUNET_OK;
735 GNUNET_free_non_null (log_file_name); 741 GNUNET_free_non_null(log_file_name);
736 log_file_name = GNUNET_STRINGS_filename_expand (logfile); 742 log_file_name = GNUNET_STRINGS_filename_expand(logfile);
737 if (NULL == log_file_name) 743 if (NULL == log_file_name)
738 return GNUNET_SYSERR; 744 return GNUNET_SYSERR;
739#if TALER_WALLET_ONLY || defined(GNUNET_CULL_LOGGING) 745#if TALER_WALLET_ONLY || defined(GNUNET_CULL_LOGGING)
740 /* log file option not allowed for wallet logic */ 746 /* log file option not allowed for wallet logic */
741 GNUNET_assert (NULL == logfile); 747 GNUNET_assert(NULL == logfile);
742 return GNUNET_OK; 748 return GNUNET_OK;
743#else 749#else
744 { 750 {
745 time_t t; 751 time_t t;
746 const struct tm *tm; 752 const struct tm *tm;
747 753
748 t = time (NULL); 754 t = time(NULL);
749 tm = gmtime (&t); 755 tm = gmtime(&t);
750 return setup_log_file (tm); 756 return setup_log_file(tm);
751 } 757 }
752#endif 758#endif
753} 759}
@@ -763,11 +769,11 @@ GNUNET_log_setup (const char *comp, const char *loglevel, const char *logfile)
763 * @param logger_cls closure for @a logger 769 * @param logger_cls closure for @a logger
764 */ 770 */
765void 771void
766GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls) 772GNUNET_logger_add(GNUNET_Logger logger, void *logger_cls)
767{ 773{
768 struct CustomLogger *entry; 774 struct CustomLogger *entry;
769 775
770 entry = GNUNET_new (struct CustomLogger); 776 entry = GNUNET_new(struct CustomLogger);
771 entry->logger = logger; 777 entry->logger = logger;
772 entry->logger_cls = logger_cls; 778 entry->logger_cls = logger_cls;
773 entry->next = loggers; 779 entry->next = loggers;
@@ -782,7 +788,7 @@ GNUNET_logger_add (GNUNET_Logger logger, void *logger_cls)
782 * @param logger_cls closure for @a logger 788 * @param logger_cls closure for @a logger
783 */ 789 */
784void 790void
785GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls) 791GNUNET_logger_remove(GNUNET_Logger logger, void *logger_cls)
786{ 792{
787 struct CustomLogger *pos; 793 struct CustomLogger *pos;
788 struct CustomLogger *prev; 794 struct CustomLogger *prev;
@@ -791,16 +797,16 @@ GNUNET_logger_remove (GNUNET_Logger logger, void *logger_cls)
791 pos = loggers; 797 pos = loggers;
792 while ((NULL != pos) && 798 while ((NULL != pos) &&
793 ((pos->logger != logger) || (pos->logger_cls != logger_cls))) 799 ((pos->logger != logger) || (pos->logger_cls != logger_cls)))
794 { 800 {
795 prev = pos; 801 prev = pos;
796 pos = pos->next; 802 pos = pos->next;
797 } 803 }
798 GNUNET_assert (NULL != pos); 804 GNUNET_assert(NULL != pos);
799 if (NULL == prev) 805 if (NULL == prev)
800 loggers = pos->next; 806 loggers = pos->next;
801 else 807 else
802 prev->next = pos->next; 808 prev->next = pos->next;
803 GNUNET_free (pos); 809 GNUNET_free(pos);
804} 810}
805 811
806#if WINDOWS 812#if WINDOWS
@@ -817,72 +823,72 @@ CRITICAL_SECTION output_message_cs;
817 * @param msg the actual message 823 * @param msg the actual message
818 */ 824 */
819static void 825static void
820output_message (enum GNUNET_ErrorType kind, 826output_message(enum GNUNET_ErrorType kind,
821 const char *comp, 827 const char *comp,
822 const char *datestr, 828 const char *datestr,
823 const char *msg) 829 const char *msg)
824{ 830{
825 struct CustomLogger *pos; 831 struct CustomLogger *pos;
826 832
827#if WINDOWS 833#if WINDOWS
828 EnterCriticalSection (&output_message_cs); 834 EnterCriticalSection(&output_message_cs);
829#endif 835#endif
830 /* only use the standard logger if no custom loggers are present */ 836 /* only use the standard logger if no custom loggers are present */
831 if ((NULL != GNUNET_stderr) && (NULL == loggers)) 837 if ((NULL != GNUNET_stderr) && (NULL == loggers))
832 {
833 if (kind == GNUNET_ERROR_TYPE_MESSAGE)
834 { 838 {
835 /* The idea here is to produce "normal" output messages 839 if (kind == GNUNET_ERROR_TYPE_MESSAGE)
836 * for end users while still having the power of the 840 {
837 * logging engine for developer needs. So ideally this 841 /* The idea here is to produce "normal" output messages
838 * is what it should look like when CLI tools are used 842 * for end users while still having the power of the
839 * interactively, yet the same message shouldn't look 843 * logging engine for developer needs. So ideally this
840 * this way if the output is going to logfiles or robots 844 * is what it should look like when CLI tools are used
841 * instead. 845 * interactively, yet the same message shouldn't look
842 */ 846 * this way if the output is going to logfiles or robots
843 fprintf (GNUNET_stderr, "* %s", msg); 847 * instead.
844 } 848 */
845 else if (GNUNET_YES == current_async_scope.have_scope) 849 fprintf(GNUNET_stderr, "* %s", msg);
846 { 850 }
847 static GNUNET_THREAD_LOCAL char id_buf[27]; 851 else if (GNUNET_YES == current_async_scope.have_scope)
848 char *end; 852 {
849 853 static GNUNET_THREAD_LOCAL char id_buf[27];
850 /* We're logging, so skip_log must be currently 0. */ 854 char *end;
851 skip_log = 100; 855
852 end = GNUNET_STRINGS_data_to_string (&current_async_scope.scope_id, 856 /* We're logging, so skip_log must be currently 0. */
853 sizeof (struct GNUNET_AsyncScopeId), 857 skip_log = 100;
854 id_buf, 858 end = GNUNET_STRINGS_data_to_string(&current_async_scope.scope_id,
855 sizeof (id_buf) - 1); 859 sizeof(struct GNUNET_AsyncScopeId),
856 GNUNET_assert (NULL != end); 860 id_buf,
857 *end = '\0'; 861 sizeof(id_buf) - 1);
858 skip_log = 0; 862 GNUNET_assert(NULL != end);
859 fprintf (GNUNET_stderr, 863 *end = '\0';
860 "%s %s(%s) %s %s", 864 skip_log = 0;
861 datestr, 865 fprintf(GNUNET_stderr,
862 comp, 866 "%s %s(%s) %s %s",
863 id_buf, 867 datestr,
864 GNUNET_error_type_to_string (kind), 868 comp,
865 msg); 869 id_buf,
866 } 870 GNUNET_error_type_to_string(kind),
867 else 871 msg);
868 { 872 }
869 fprintf (GNUNET_stderr, 873 else
870 "%s %s %s %s", 874 {
871 datestr, 875 fprintf(GNUNET_stderr,
872 comp, 876 "%s %s %s %s",
873 GNUNET_error_type_to_string (kind), 877 datestr,
874 msg); 878 comp,
879 GNUNET_error_type_to_string(kind),
880 msg);
881 }
882 fflush(GNUNET_stderr);
875 } 883 }
876 fflush (GNUNET_stderr);
877 }
878 pos = loggers; 884 pos = loggers;
879 while (NULL != pos) 885 while (NULL != pos)
880 { 886 {
881 pos->logger (pos->logger_cls, kind, comp, datestr, msg); 887 pos->logger(pos->logger_cls, kind, comp, datestr, msg);
882 pos = pos->next; 888 pos = pos->next;
883 } 889 }
884#if WINDOWS 890#if WINDOWS
885 LeaveCriticalSection (&output_message_cs); 891 LeaveCriticalSection(&output_message_cs);
886#endif 892#endif
887} 893}
888 894
@@ -893,7 +899,7 @@ output_message (enum GNUNET_ErrorType kind,
893 * @param datestr our current timestamp 899 * @param datestr our current timestamp
894 */ 900 */
895static void 901static void
896flush_bulk (const char *datestr) 902flush_bulk(const char *datestr)
897{ 903{
898 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256]; 904 char msg[DATE_STR_SIZE + BULK_TRACK_SIZE + 256];
899 int rev; 905 int rev;
@@ -903,31 +909,31 @@ flush_bulk (const char *datestr)
903 if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat)) 909 if ((0 == last_bulk_time.abs_value_us) || (0 == last_bulk_repeat))
904 return; 910 return;
905 rev = 0; 911 rev = 0;
906 last = memchr (last_bulk, '\0', BULK_TRACK_SIZE); 912 last = memchr(last_bulk, '\0', BULK_TRACK_SIZE);
907 if (last == NULL) 913 if (last == NULL)
908 last = &last_bulk[BULK_TRACK_SIZE - 1]; 914 last = &last_bulk[BULK_TRACK_SIZE - 1];
909 else if (last != last_bulk) 915 else if (last != last_bulk)
910 last--; 916 last--;
911 if (last[0] == '\n') 917 if (last[0] == '\n')
912 { 918 {
913 rev = 1; 919 rev = 1;
914 last[0] = '\0'; 920 last[0] = '\0';
915 } 921 }
916 ft = 922 ft =
917 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration ( 923 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(
918 last_bulk_time), 924 last_bulk_time),
919 GNUNET_YES); 925 GNUNET_YES);
920 snprintf (msg, 926 snprintf(msg,
921 sizeof (msg), 927 sizeof(msg),
922 _ ("Message `%.*s' repeated %u times in the last %s\n"), 928 _("Message `%.*s' repeated %u times in the last %s\n"),
923 BULK_TRACK_SIZE, 929 BULK_TRACK_SIZE,
924 last_bulk, 930 last_bulk,
925 last_bulk_repeat, 931 last_bulk_repeat,
926 ft); 932 ft);
927 if (rev == 1) 933 if (rev == 1)
928 last[0] = '\n'; 934 last[0] = '\n';
929 output_message (last_bulk_kind, last_bulk_comp, datestr, msg); 935 output_message(last_bulk_kind, last_bulk_comp, datestr, msg);
930 last_bulk_time = GNUNET_TIME_absolute_get (); 936 last_bulk_time = GNUNET_TIME_absolute_get();
931 last_bulk_repeat = 0; 937 last_bulk_repeat = 0;
932} 938}
933 939
@@ -939,21 +945,21 @@ flush_bulk (const char *datestr)
939 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero 945 * @param check_reset #GNUNET_YES to assert that the log skip counter is currently zero
940 */ 946 */
941void 947void
942GNUNET_log_skip (int n, int check_reset) 948GNUNET_log_skip(int n, int check_reset)
943{ 949{
944 int ok; 950 int ok;
945 951
946 if (0 == n) 952 if (0 == n)
947 { 953 {
948 ok = (0 == skip_log); 954 ok = (0 == skip_log);
949 skip_log = 0; 955 skip_log = 0;
950 if (check_reset) 956 if (check_reset)
951 GNUNET_break (ok); 957 GNUNET_break(ok);
952 } 958 }
953 else 959 else
954 { 960 {
955 skip_log += n; 961 skip_log += n;
956 } 962 }
957} 963}
958 964
959 965
@@ -963,7 +969,7 @@ GNUNET_log_skip (int n, int check_reset)
963 * @return number of log calls to be ignored 969 * @return number of log calls to be ignored
964 */ 970 */
965int 971int
966GNUNET_get_log_skip () 972GNUNET_get_log_skip()
967{ 973{
968 return skip_log; 974 return skip_log;
969} 975}
@@ -978,10 +984,10 @@ GNUNET_get_log_skip ()
978 * @param va arguments to the format string "message" 984 * @param va arguments to the format string "message"
979 */ 985 */
980static void 986static void
981mylog (enum GNUNET_ErrorType kind, 987mylog(enum GNUNET_ErrorType kind,
982 const char *comp, 988 const char *comp,
983 const char *message, 989 const char *message,
984 va_list va) 990 va_list va)
985{ 991{
986 char date[DATE_STR_SIZE]; 992 char date[DATE_STR_SIZE];
987 char date2[DATE_STR_SIZE]; 993 char date2[DATE_STR_SIZE];
@@ -989,11 +995,11 @@ mylog (enum GNUNET_ErrorType kind,
989 size_t size; 995 size_t size;
990 va_list vacp; 996 va_list vacp;
991 997
992 va_copy (vacp, va); 998 va_copy(vacp, va);
993 size = vsnprintf (NULL, 0, message, vacp) + 1; 999 size = vsnprintf(NULL, 0, message, vacp) + 1;
994 GNUNET_assert (0 != size); 1000 GNUNET_assert(0 != size);
995 va_end (vacp); 1001 va_end(vacp);
996 memset (date, 0, DATE_STR_SIZE); 1002 memset(date, 0, DATE_STR_SIZE);
997 { 1003 {
998 char buf[size]; 1004 char buf[size];
999 long long offset; 1005 long long offset;
@@ -1001,92 +1007,92 @@ mylog (enum GNUNET_ErrorType kind,
1001 LARGE_INTEGER pc; 1007 LARGE_INTEGER pc;
1002 time_t timetmp; 1008 time_t timetmp;
1003 1009
1004 offset = GNUNET_TIME_get_offset (); 1010 offset = GNUNET_TIME_get_offset();
1005 time (&timetmp); 1011 time(&timetmp);
1006 timetmp += offset / 1000; 1012 timetmp += offset / 1000;
1007 tmptr = localtime (&timetmp); 1013 tmptr = localtime(&timetmp);
1008 pc.QuadPart = 0; 1014 pc.QuadPart = 0;
1009 QueryPerformanceCounter (&pc); 1015 QueryPerformanceCounter(&pc);
1010 if (NULL == tmptr) 1016 if (NULL == tmptr)
1011 { 1017 {
1012 strcpy (date, "localtime error"); 1018 strcpy(date, "localtime error");
1013 } 1019 }
1014 else 1020 else
1015 { 1021 {
1016 if (0 == 1022 if (0 ==
1017 strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr)) 1023 strftime(date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%020llu", tmptr))
1018 abort (); 1024 abort();
1019 if (0 > snprintf (date, 1025 if (0 > snprintf(date,
1020 sizeof (date), 1026 sizeof(date),
1021 date2, 1027 date2,
1022 (long long) (pc.QuadPart / 1028 (long long)(pc.QuadPart /
1023 (performance_frequency.QuadPart / 1000)))) 1029 (performance_frequency.QuadPart / 1000))))
1024 abort (); 1030 abort();
1025 } 1031 }
1026#else 1032#else
1027 struct timeval timeofday; 1033 struct timeval timeofday;
1028 1034
1029 gettimeofday (&timeofday, NULL); 1035 gettimeofday(&timeofday, NULL);
1030 offset = GNUNET_TIME_get_offset (); 1036 offset = GNUNET_TIME_get_offset();
1031 if (offset > 0) 1037 if (offset > 0)
1032 {
1033 timeofday.tv_sec += offset / 1000LL;
1034 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1035 if (timeofday.tv_usec > 1000000LL)
1036 { 1038 {
1037 timeofday.tv_usec -= 1000000LL; 1039 timeofday.tv_sec += offset / 1000LL;
1038 timeofday.tv_sec++; 1040 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1041 if (timeofday.tv_usec > 1000000LL)
1042 {
1043 timeofday.tv_usec -= 1000000LL;
1044 timeofday.tv_sec++;
1045 }
1039 } 1046 }
1040 }
1041 else 1047 else
1042 {
1043 timeofday.tv_sec += offset / 1000LL;
1044 if (timeofday.tv_usec > -(offset % 1000LL) * 1000LL)
1045 { 1048 {
1046 timeofday.tv_usec += (offset % 1000LL) * 1000LL; 1049 timeofday.tv_sec += offset / 1000LL;
1050 if (timeofday.tv_usec > -(offset % 1000LL) * 1000LL)
1051 {
1052 timeofday.tv_usec += (offset % 1000LL) * 1000LL;
1053 }
1054 else
1055 {
1056 timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL;
1057 timeofday.tv_sec--;
1058 }
1047 } 1059 }
1048 else 1060 tmptr = localtime(&timeofday.tv_sec);
1061 if (NULL == tmptr)
1049 { 1062 {
1050 timeofday.tv_usec += 1000000LL + (offset % 1000LL) * 1000LL; 1063 strcpy(date, "localtime error");
1051 timeofday.tv_sec--;
1052 } 1064 }
1053 }
1054 tmptr = localtime (&timeofday.tv_sec);
1055 if (NULL == tmptr)
1056 {
1057 strcpy (date, "localtime error");
1058 }
1059 else 1065 else
1060 { 1066 {
1061 if (0 == strftime (date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr)) 1067 if (0 == strftime(date2, DATE_STR_SIZE, "%b %d %H:%M:%S-%%06u", tmptr))
1062 abort (); 1068 abort();
1063 if (0 > snprintf (date, sizeof (date), date2, timeofday.tv_usec)) 1069 if (0 > snprintf(date, sizeof(date), date2, timeofday.tv_usec))
1064 abort (); 1070 abort();
1065 } 1071 }
1066#endif 1072#endif
1067 vsnprintf (buf, size, message, va); 1073 vsnprintf(buf, size, message, va);
1068#if ! (defined(GNUNET_CULL_LOGGING) || TALER_WALLET_ONLY) 1074#if !(defined(GNUNET_CULL_LOGGING) || TALER_WALLET_ONLY)
1069 if (NULL != tmptr) 1075 if (NULL != tmptr)
1070 (void) setup_log_file (tmptr); 1076 (void)setup_log_file(tmptr);
1071#endif 1077#endif
1072 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) && 1078 if ((0 != (kind & GNUNET_ERROR_TYPE_BULK)) &&
1073 (0 != last_bulk_time.abs_value_us) && 1079 (0 != last_bulk_time.abs_value_us) &&
1074 (0 == strncmp (buf, last_bulk, sizeof (last_bulk)))) 1080 (0 == strncmp(buf, last_bulk, sizeof(last_bulk))))
1075 { 1081 {
1076 last_bulk_repeat++; 1082 last_bulk_repeat++;
1077 if ((GNUNET_TIME_absolute_get_duration (last_bulk_time).rel_value_us > 1083 if ((GNUNET_TIME_absolute_get_duration(last_bulk_time).rel_value_us >
1078 BULK_DELAY_THRESHOLD) || 1084 BULK_DELAY_THRESHOLD) ||
1079 (last_bulk_repeat > BULK_REPEAT_THRESHOLD)) 1085 (last_bulk_repeat > BULK_REPEAT_THRESHOLD))
1080 flush_bulk (date); 1086 flush_bulk(date);
1081 return; 1087 return;
1082 } 1088 }
1083 flush_bulk (date); 1089 flush_bulk(date);
1084 GNUNET_strlcpy (last_bulk, buf, sizeof (last_bulk)); 1090 GNUNET_strlcpy(last_bulk, buf, sizeof(last_bulk));
1085 last_bulk_repeat = 0; 1091 last_bulk_repeat = 0;
1086 last_bulk_kind = kind; 1092 last_bulk_kind = kind;
1087 last_bulk_time = GNUNET_TIME_absolute_get (); 1093 last_bulk_time = GNUNET_TIME_absolute_get();
1088 GNUNET_strlcpy (last_bulk_comp, comp, sizeof (last_bulk_comp)); 1094 GNUNET_strlcpy(last_bulk_comp, comp, sizeof(last_bulk_comp));
1089 output_message (kind, comp, date, buf); 1095 output_message(kind, comp, date, buf);
1090 } 1096 }
1091} 1097}
1092 1098
@@ -1099,13 +1105,13 @@ mylog (enum GNUNET_ErrorType kind,
1099 * @param ... arguments for format string 1105 * @param ... arguments for format string
1100 */ 1106 */
1101void 1107void
1102GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...) 1108GNUNET_log_nocheck(enum GNUNET_ErrorType kind, const char *message, ...)
1103{ 1109{
1104 va_list va; 1110 va_list va;
1105 1111
1106 va_start (va, message); 1112 va_start(va, message);
1107 mylog (kind, component, message, va); 1113 mylog(kind, component, message, va);
1108 va_end (va); 1114 va_end(va);
1109} 1115}
1110 1116
1111 1117
@@ -1119,10 +1125,10 @@ GNUNET_log_nocheck (enum GNUNET_ErrorType kind, const char *message, ...)
1119 * @param ... arguments for format string 1125 * @param ... arguments for format string
1120 */ 1126 */
1121void 1127void
1122GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind, 1128GNUNET_log_from_nocheck(enum GNUNET_ErrorType kind,
1123 const char *comp, 1129 const char *comp,
1124 const char *message, 1130 const char *message,
1125 ...) 1131 ...)
1126{ 1132{
1127 va_list va; 1133 va_list va;
1128 char comp_w_pid[128]; 1134 char comp_w_pid[128];
@@ -1130,10 +1136,10 @@ GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
1130 if (comp == NULL) 1136 if (comp == NULL)
1131 comp = component_nopid; 1137 comp = component_nopid;
1132 1138
1133 va_start (va, message); 1139 va_start(va, message);
1134 GNUNET_snprintf (comp_w_pid, sizeof (comp_w_pid), "%s-%d", comp, getpid ()); 1140 GNUNET_snprintf(comp_w_pid, sizeof(comp_w_pid), "%s-%d", comp, getpid());
1135 mylog (kind, comp_w_pid, message, va); 1141 mylog(kind, comp_w_pid, message, va);
1136 va_end (va); 1142 va_end(va);
1137} 1143}
1138 1144
1139 1145
@@ -1144,21 +1150,21 @@ GNUNET_log_from_nocheck (enum GNUNET_ErrorType kind,
1144 * @return string corresponding to the type 1150 * @return string corresponding to the type
1145 */ 1151 */
1146const char * 1152const char *
1147GNUNET_error_type_to_string (enum GNUNET_ErrorType kind) 1153GNUNET_error_type_to_string(enum GNUNET_ErrorType kind)
1148{ 1154{
1149 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0) 1155 if ((kind & GNUNET_ERROR_TYPE_ERROR) > 0)
1150 return _ ("ERROR"); 1156 return _("ERROR");
1151 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0) 1157 if ((kind & GNUNET_ERROR_TYPE_WARNING) > 0)
1152 return _ ("WARNING"); 1158 return _("WARNING");
1153 if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0) 1159 if ((kind & GNUNET_ERROR_TYPE_MESSAGE) > 0)
1154 return _ ("MESSAGE"); 1160 return _("MESSAGE");
1155 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0) 1161 if ((kind & GNUNET_ERROR_TYPE_INFO) > 0)
1156 return _ ("INFO"); 1162 return _("INFO");
1157 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0) 1163 if ((kind & GNUNET_ERROR_TYPE_DEBUG) > 0)
1158 return _ ("DEBUG"); 1164 return _("DEBUG");
1159 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0) 1165 if ((kind & ~GNUNET_ERROR_TYPE_BULK) == 0)
1160 return _ ("NONE"); 1166 return _("NONE");
1161 return _ ("INVALID"); 1167 return _("INVALID");
1162} 1168}
1163 1169
1164 1170
@@ -1169,13 +1175,13 @@ GNUNET_error_type_to_string (enum GNUNET_ErrorType kind)
1169 * @return string form; will be overwritten by next call to GNUNET_h2s. 1175 * @return string form; will be overwritten by next call to GNUNET_h2s.
1170 */ 1176 */
1171const char * 1177const char *
1172GNUNET_h2s (const struct GNUNET_HashCode *hc) 1178GNUNET_h2s(const struct GNUNET_HashCode *hc)
1173{ 1179{
1174 static GNUNET_THREAD_LOCAL struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1180 static GNUNET_THREAD_LOCAL struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1175 1181
1176 GNUNET_CRYPTO_hash_to_enc (hc, &ret); 1182 GNUNET_CRYPTO_hash_to_enc(hc, &ret);
1177 ret.encoding[8] = '\0'; 1183 ret.encoding[8] = '\0';
1178 return (const char *) ret.encoding; 1184 return (const char *)ret.encoding;
1179} 1185}
1180 1186
1181 1187
@@ -1190,13 +1196,13 @@ GNUNET_h2s (const struct GNUNET_HashCode *hc)
1190 * @return string form; will be overwritten by next call to GNUNET_h2s. 1196 * @return string form; will be overwritten by next call to GNUNET_h2s.
1191 */ 1197 */
1192const char * 1198const char *
1193GNUNET_h2s2 (const struct GNUNET_HashCode *hc) 1199GNUNET_h2s2(const struct GNUNET_HashCode *hc)
1194{ 1200{
1195 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1201 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1196 1202
1197 GNUNET_CRYPTO_hash_to_enc (hc, &ret); 1203 GNUNET_CRYPTO_hash_to_enc(hc, &ret);
1198 ret.encoding[8] = '\0'; 1204 ret.encoding[8] = '\0';
1199 return (const char *) ret.encoding; 1205 return (const char *)ret.encoding;
1200} 1206}
1201 1207
1202 1208
@@ -1210,15 +1216,15 @@ GNUNET_h2s2 (const struct GNUNET_HashCode *hc)
1210 * @return string 1216 * @return string
1211 */ 1217 */
1212const char * 1218const char *
1213GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p) 1219GNUNET_p2s(const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1214{ 1220{
1215 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1221 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1216 struct GNUNET_HashCode hc; 1222 struct GNUNET_HashCode hc;
1217 1223
1218 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc); 1224 GNUNET_CRYPTO_hash(p, sizeof(*p), &hc);
1219 GNUNET_CRYPTO_hash_to_enc (&hc, &ret); 1225 GNUNET_CRYPTO_hash_to_enc(&hc, &ret);
1220 ret.encoding[6] = '\0'; 1226 ret.encoding[6] = '\0';
1221 return (const char *) ret.encoding; 1227 return (const char *)ret.encoding;
1222} 1228}
1223 1229
1224 1230
@@ -1232,15 +1238,15 @@ GNUNET_p2s (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1232 * @return string 1238 * @return string
1233 */ 1239 */
1234const char * 1240const char *
1235GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p) 1241GNUNET_p2s2(const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1236{ 1242{
1237 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1243 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1238 struct GNUNET_HashCode hc; 1244 struct GNUNET_HashCode hc;
1239 1245
1240 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc); 1246 GNUNET_CRYPTO_hash(p, sizeof(*p), &hc);
1241 GNUNET_CRYPTO_hash_to_enc (&hc, &ret); 1247 GNUNET_CRYPTO_hash_to_enc(&hc, &ret);
1242 ret.encoding[6] = '\0'; 1248 ret.encoding[6] = '\0';
1243 return (const char *) ret.encoding; 1249 return (const char *)ret.encoding;
1244} 1250}
1245 1251
1246 1252
@@ -1254,15 +1260,15 @@ GNUNET_p2s2 (const struct GNUNET_CRYPTO_EddsaPublicKey *p)
1254 * @return string 1260 * @return string
1255 */ 1261 */
1256const char * 1262const char *
1257GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p) 1263GNUNET_e2s(const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1258{ 1264{
1259 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1265 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1260 struct GNUNET_HashCode hc; 1266 struct GNUNET_HashCode hc;
1261 1267
1262 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc); 1268 GNUNET_CRYPTO_hash(p, sizeof(*p), &hc);
1263 GNUNET_CRYPTO_hash_to_enc (&hc, &ret); 1269 GNUNET_CRYPTO_hash_to_enc(&hc, &ret);
1264 ret.encoding[6] = '\0'; 1270 ret.encoding[6] = '\0';
1265 return (const char *) ret.encoding; 1271 return (const char *)ret.encoding;
1266} 1272}
1267 1273
1268 1274
@@ -1276,15 +1282,15 @@ GNUNET_e2s (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1276 * @return string 1282 * @return string
1277 */ 1283 */
1278const char * 1284const char *
1279GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p) 1285GNUNET_e2s2(const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1280{ 1286{
1281 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1287 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1282 struct GNUNET_HashCode hc; 1288 struct GNUNET_HashCode hc;
1283 1289
1284 GNUNET_CRYPTO_hash (p, sizeof (*p), &hc); 1290 GNUNET_CRYPTO_hash(p, sizeof(*p), &hc);
1285 GNUNET_CRYPTO_hash_to_enc (&hc, &ret); 1291 GNUNET_CRYPTO_hash_to_enc(&hc, &ret);
1286 ret.encoding[6] = '\0'; 1292 ret.encoding[6] = '\0';
1287 return (const char *) ret.encoding; 1293 return (const char *)ret.encoding;
1288} 1294}
1289 1295
1290 1296
@@ -1298,13 +1304,13 @@ GNUNET_e2s2 (const struct GNUNET_CRYPTO_EcdhePublicKey *p)
1298 * @return string 1304 * @return string
1299 */ 1305 */
1300const char * 1306const char *
1301GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc) 1307GNUNET_sh2s(const struct GNUNET_ShortHashCode *shc)
1302{ 1308{
1303 static char buf[64]; 1309 static char buf[64];
1304 1310
1305 GNUNET_STRINGS_data_to_string (shc, sizeof (*shc), buf, sizeof (buf)); 1311 GNUNET_STRINGS_data_to_string(shc, sizeof(*shc), buf, sizeof(buf));
1306 buf[6] = '\0'; 1312 buf[6] = '\0';
1307 return (const char *) buf; 1313 return (const char *)buf;
1308} 1314}
1309 1315
1310 1316
@@ -1318,13 +1324,13 @@ GNUNET_sh2s (const struct GNUNET_ShortHashCode *shc)
1318 * @return string 1324 * @return string
1319 */ 1325 */
1320const char * 1326const char *
1321GNUNET_uuid2s (const struct GNUNET_Uuid *uuid) 1327GNUNET_uuid2s(const struct GNUNET_Uuid *uuid)
1322{ 1328{
1323 static char buf[32]; 1329 static char buf[32];
1324 1330
1325 GNUNET_STRINGS_data_to_string (uuid, sizeof (*uuid), buf, sizeof (buf)); 1331 GNUNET_STRINGS_data_to_string(uuid, sizeof(*uuid), buf, sizeof(buf));
1326 buf[6] = '\0'; 1332 buf[6] = '\0';
1327 return (const char *) buf; 1333 return (const char *)buf;
1328} 1334}
1329 1335
1330 1336
@@ -1337,13 +1343,13 @@ GNUNET_uuid2s (const struct GNUNET_Uuid *uuid)
1337 * @return string form; will be overwritten by next call to GNUNET_h2s_full. 1343 * @return string form; will be overwritten by next call to GNUNET_h2s_full.
1338 */ 1344 */
1339const char * 1345const char *
1340GNUNET_h2s_full (const struct GNUNET_HashCode *hc) 1346GNUNET_h2s_full(const struct GNUNET_HashCode *hc)
1341{ 1347{
1342 static struct GNUNET_CRYPTO_HashAsciiEncoded ret; 1348 static struct GNUNET_CRYPTO_HashAsciiEncoded ret;
1343 1349
1344 GNUNET_CRYPTO_hash_to_enc (hc, &ret); 1350 GNUNET_CRYPTO_hash_to_enc(hc, &ret);
1345 ret.encoding[sizeof (ret) - 1] = '\0'; 1351 ret.encoding[sizeof(ret) - 1] = '\0';
1346 return (const char *) ret.encoding; 1352 return (const char *)ret.encoding;
1347} 1353}
1348 1354
1349 1355
@@ -1355,16 +1361,16 @@ GNUNET_h2s_full (const struct GNUNET_HashCode *hc)
1355 * call to #GNUNET_i2s. 1361 * call to #GNUNET_i2s.
1356 */ 1362 */
1357const char * 1363const char *
1358GNUNET_i2s (const struct GNUNET_PeerIdentity *pid) 1364GNUNET_i2s(const struct GNUNET_PeerIdentity *pid)
1359{ 1365{
1360 static GNUNET_THREAD_LOCAL char buf[5]; 1366 static GNUNET_THREAD_LOCAL char buf[5];
1361 char *ret; 1367 char *ret;
1362 1368
1363 if (NULL == pid) 1369 if (NULL == pid)
1364 return "NULL"; 1370 return "NULL";
1365 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key); 1371 ret = GNUNET_CRYPTO_eddsa_public_key_to_string(&pid->public_key);
1366 GNUNET_strlcpy (buf, ret, sizeof (buf)); 1372 GNUNET_strlcpy(buf, ret, sizeof(buf));
1367 GNUNET_free (ret); 1373 GNUNET_free(ret);
1368 return buf; 1374 return buf;
1369} 1375}
1370 1376
@@ -1380,16 +1386,16 @@ GNUNET_i2s (const struct GNUNET_PeerIdentity *pid)
1380 * call to #GNUNET_i2s. 1386 * call to #GNUNET_i2s.
1381 */ 1387 */
1382const char * 1388const char *
1383GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid) 1389GNUNET_i2s2(const struct GNUNET_PeerIdentity *pid)
1384{ 1390{
1385 static GNUNET_THREAD_LOCAL char buf[5]; 1391 static GNUNET_THREAD_LOCAL char buf[5];
1386 char *ret; 1392 char *ret;
1387 1393
1388 if (NULL == pid) 1394 if (NULL == pid)
1389 return "NULL"; 1395 return "NULL";
1390 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key); 1396 ret = GNUNET_CRYPTO_eddsa_public_key_to_string(&pid->public_key);
1391 GNUNET_strlcpy (buf, ret, sizeof (buf)); 1397 GNUNET_strlcpy(buf, ret, sizeof(buf));
1392 GNUNET_free (ret); 1398 GNUNET_free(ret);
1393 return buf; 1399 return buf;
1394} 1400}
1395 1401
@@ -1402,14 +1408,14 @@ GNUNET_i2s2 (const struct GNUNET_PeerIdentity *pid)
1402 * call to #GNUNET_i2s_full. 1408 * call to #GNUNET_i2s_full.
1403 */ 1409 */
1404const char * 1410const char *
1405GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid) 1411GNUNET_i2s_full(const struct GNUNET_PeerIdentity *pid)
1406{ 1412{
1407 static GNUNET_THREAD_LOCAL char buf[256]; 1413 static GNUNET_THREAD_LOCAL char buf[256];
1408 char *ret; 1414 char *ret;
1409 1415
1410 ret = GNUNET_CRYPTO_eddsa_public_key_to_string (&pid->public_key); 1416 ret = GNUNET_CRYPTO_eddsa_public_key_to_string(&pid->public_key);
1411 strcpy (buf, ret); 1417 strcpy(buf, ret);
1412 GNUNET_free (ret); 1418 GNUNET_free(ret);
1413 return buf; 1419 return buf;
1414} 1420}
1415 1421
@@ -1425,12 +1431,12 @@ GNUNET_i2s_full (const struct GNUNET_PeerIdentity *pid)
1425 * will be overwritten by next call to #GNUNET_a2s. 1431 * will be overwritten by next call to #GNUNET_a2s.
1426 */ 1432 */
1427const char * 1433const char *
1428GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen) 1434GNUNET_a2s(const struct sockaddr *addr, socklen_t addrlen)
1429{ 1435{
1430#ifndef WINDOWS 1436#ifndef WINDOWS
1431#define LEN \ 1437#define LEN \
1432 GNUNET_MAX ((INET6_ADDRSTRLEN + 8), \ 1438 GNUNET_MAX((INET6_ADDRSTRLEN + 8), \
1433 (1 + sizeof (struct sockaddr_un) - sizeof (sa_family_t))) 1439 (1 + sizeof(struct sockaddr_un) - sizeof(sa_family_t)))
1434#else 1440#else
1435#define LEN (INET6_ADDRSTRLEN + 8) 1441#define LEN (INET6_ADDRSTRLEN + 8)
1436#endif 1442#endif
@@ -1443,50 +1449,53 @@ GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
1443 unsigned int off; 1449 unsigned int off;
1444 1450
1445 if (addr == NULL) 1451 if (addr == NULL)
1446 return _ ("unknown address"); 1452 return _("unknown address");
1447 switch (addr->sa_family) 1453 switch (addr->sa_family)
1448 { 1454 {
1449 case AF_INET: 1455 case AF_INET:
1450 if (addrlen != sizeof (struct sockaddr_in)) 1456 if (addrlen != sizeof(struct sockaddr_in))
1451 return "<invalid v4 address>"; 1457 return "<invalid v4 address>";
1452 v4 = (const struct sockaddr_in *) addr; 1458 v4 = (const struct sockaddr_in *)addr;
1453 inet_ntop (AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN); 1459 inet_ntop(AF_INET, &v4->sin_addr, buf, INET_ADDRSTRLEN);
1454 if (0 == ntohs (v4->sin_port)) 1460 if (0 == ntohs(v4->sin_port))
1461 return buf;
1462 strcat(buf, ":");
1463 GNUNET_snprintf(b2, sizeof(b2), "%u", ntohs(v4->sin_port));
1464 strcat(buf, b2);
1455 return buf; 1465 return buf;
1456 strcat (buf, ":"); 1466
1457 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v4->sin_port)); 1467 case AF_INET6:
1458 strcat (buf, b2); 1468 if (addrlen != sizeof(struct sockaddr_in6))
1459 return buf; 1469 return "<invalid v4 address>";
1460 case AF_INET6: 1470 v6 = (const struct sockaddr_in6 *)addr;
1461 if (addrlen != sizeof (struct sockaddr_in6)) 1471 buf[0] = '[';
1462 return "<invalid v4 address>"; 1472 inet_ntop(AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN);
1463 v6 = (const struct sockaddr_in6 *) addr; 1473 if (0 == ntohs(v6->sin6_port))
1464 buf[0] = '['; 1474 return &buf[1];
1465 inet_ntop (AF_INET6, &v6->sin6_addr, &buf[1], INET6_ADDRSTRLEN); 1475 strcat(buf, "]:");
1466 if (0 == ntohs (v6->sin6_port)) 1476 GNUNET_snprintf(b2, sizeof(b2), "%u", ntohs(v6->sin6_port));
1467 return &buf[1]; 1477 strcat(buf, b2);
1468 strcat (buf, "]:"); 1478 return buf;
1469 GNUNET_snprintf (b2, sizeof (b2), "%u", ntohs (v6->sin6_port)); 1479
1470 strcat (buf, b2); 1480 case AF_UNIX:
1471 return buf; 1481 if (addrlen <= sizeof(sa_family_t))
1472 case AF_UNIX: 1482 return "<unbound UNIX client>";
1473 if (addrlen <= sizeof (sa_family_t)) 1483 un = (const struct sockaddr_un *)addr;
1474 return "<unbound UNIX client>"; 1484 off = 0;
1475 un = (const struct sockaddr_un *) addr; 1485 if ('\0' == un->sun_path[0])
1476 off = 0; 1486 off++;
1477 if ('\0' == un->sun_path[0]) 1487 memset(buf, 0, sizeof(buf));
1478 off++; 1488 GNUNET_snprintf(buf,
1479 memset (buf, 0, sizeof (buf)); 1489 sizeof(buf),
1480 GNUNET_snprintf (buf, 1490 "%s%.*s",
1481 sizeof (buf), 1491 (1 == off) ? "@" : "",
1482 "%s%.*s", 1492 (int)(addrlen - sizeof(sa_family_t) - off),
1483 (1 == off) ? "@" : "", 1493 &un->sun_path[off]);
1484 (int) (addrlen - sizeof (sa_family_t) - off), 1494 return buf;
1485 &un->sun_path[off]); 1495
1486 return buf; 1496 default:
1487 default: 1497 return _("invalid address");
1488 return _ ("invalid address"); 1498 }
1489 }
1490} 1499}
1491 1500
1492 1501
@@ -1498,15 +1507,15 @@ GNUNET_a2s (const struct sockaddr *addr, socklen_t addrlen)
1498 * @param option name of missing option 1507 * @param option name of missing option
1499 */ 1508 */
1500void 1509void
1501GNUNET_log_config_missing (enum GNUNET_ErrorType kind, 1510GNUNET_log_config_missing(enum GNUNET_ErrorType kind,
1502 const char *section, 1511 const char *section,
1503 const char *option) 1512 const char *option)
1504{ 1513{
1505 GNUNET_log (kind, 1514 GNUNET_log(kind,
1506 _ ( 1515 _(
1507 "Configuration fails to specify option `%s' in section `%s'!\n"), 1516 "Configuration fails to specify option `%s' in section `%s'!\n"),
1508 option, 1517 option,
1509 section); 1518 section);
1510} 1519}
1511 1520
1512 1521
@@ -1519,14 +1528,14 @@ GNUNET_log_config_missing (enum GNUNET_ErrorType kind,
1519 * @param required what is required that is invalid about the option 1528 * @param required what is required that is invalid about the option
1520 */ 1529 */
1521void 1530void
1522GNUNET_log_config_invalid (enum GNUNET_ErrorType kind, 1531GNUNET_log_config_invalid(enum GNUNET_ErrorType kind,
1523 const char *section, 1532 const char *section,
1524 const char *option, 1533 const char *option,
1525 const char *required) 1534 const char *required)
1526{ 1535{
1527 GNUNET_log ( 1536 GNUNET_log(
1528 kind, 1537 kind,
1529 _ ( 1538 _(
1530 "Configuration specifies invalid value for option `%s' in section `%s': %s\n"), 1539 "Configuration specifies invalid value for option `%s' in section `%s': %s\n"),
1531 option, 1540 option,
1532 section, 1541 section,
@@ -1541,8 +1550,8 @@ GNUNET_log_config_invalid (enum GNUNET_ErrorType kind,
1541 * @param old_scope[out] location to save the old scope 1550 * @param old_scope[out] location to save the old scope
1542 */ 1551 */
1543void 1552void
1544GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid, 1553GNUNET_async_scope_enter(const struct GNUNET_AsyncScopeId *aid,
1545 struct GNUNET_AsyncScopeSave *old_scope) 1554 struct GNUNET_AsyncScopeSave *old_scope)
1546{ 1555{
1547 *old_scope = current_async_scope; 1556 *old_scope = current_async_scope;
1548 current_async_scope.have_scope = GNUNET_YES; 1557 current_async_scope.have_scope = GNUNET_YES;
@@ -1556,7 +1565,7 @@ GNUNET_async_scope_enter (const struct GNUNET_AsyncScopeId *aid,
1556 * @param old_scope scope to restore 1565 * @param old_scope scope to restore
1557 */ 1566 */
1558void 1567void
1559GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope) 1568GNUNET_async_scope_restore(struct GNUNET_AsyncScopeSave *old_scope)
1560{ 1569{
1561 current_async_scope = *old_scope; 1570 current_async_scope = *old_scope;
1562} 1571}
@@ -1568,11 +1577,11 @@ GNUNET_async_scope_restore (struct GNUNET_AsyncScopeSave *old_scope)
1568 * @param[out] aid_ret pointer to where the result is stored 1577 * @param[out] aid_ret pointer to where the result is stored
1569 */ 1578 */
1570void 1579void
1571GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret) 1580GNUNET_async_scope_fresh(struct GNUNET_AsyncScopeId *aid_ret)
1572{ 1581{
1573 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 1582 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
1574 aid_ret, 1583 aid_ret,
1575 sizeof (struct GNUNET_AsyncScopeId)); 1584 sizeof(struct GNUNET_AsyncScopeId));
1576} 1585}
1577 1586
1578 1587
@@ -1582,7 +1591,7 @@ GNUNET_async_scope_fresh (struct GNUNET_AsyncScopeId *aid_ret)
1582 * @param[out] scope_ret pointer to where the result is stored 1591 * @param[out] scope_ret pointer to where the result is stored
1583 */ 1592 */
1584void 1593void
1585GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret) 1594GNUNET_async_scope_get(struct GNUNET_AsyncScopeSave *scope_ret)
1586{ 1595{
1587 *scope_ret = current_async_scope; 1596 *scope_ret = current_async_scope;
1588} 1597}
@@ -1591,15 +1600,15 @@ GNUNET_async_scope_get (struct GNUNET_AsyncScopeSave *scope_ret)
1591/** 1600/**
1592 * Initializer 1601 * Initializer
1593 */ 1602 */
1594void __attribute__ ((constructor)) GNUNET_util_cl_init () 1603void __attribute__ ((constructor)) GNUNET_util_cl_init()
1595{ 1604{
1596 GNUNET_stderr = stderr; 1605 GNUNET_stderr = stderr;
1597#ifdef MINGW 1606#ifdef MINGW
1598 GNInitWinEnv (NULL); 1607 GNInitWinEnv(NULL);
1599#endif 1608#endif
1600#if WINDOWS 1609#if WINDOWS
1601 if (! InitializeCriticalSectionAndSpinCount (&output_message_cs, 0x00000400)) 1610 if (!InitializeCriticalSectionAndSpinCount(&output_message_cs, 0x00000400))
1602 GNUNET_abort_ (); 1611 GNUNET_abort_();
1603#endif 1612#endif
1604} 1613}
1605 1614
@@ -1607,13 +1616,13 @@ void __attribute__ ((constructor)) GNUNET_util_cl_init ()
1607/** 1616/**
1608 * Destructor 1617 * Destructor
1609 */ 1618 */
1610void __attribute__ ((destructor)) GNUNET_util_cl_fini () 1619void __attribute__ ((destructor)) GNUNET_util_cl_fini()
1611{ 1620{
1612#if WINDOWS 1621#if WINDOWS
1613 DeleteCriticalSection (&output_message_cs); 1622 DeleteCriticalSection(&output_message_cs);
1614#endif 1623#endif
1615#ifdef MINGW 1624#ifdef MINGW
1616 GNShutdownWinEnv (); 1625 GNShutdownWinEnv();
1617#endif 1626#endif
1618} 1627}
1619 1628
diff --git a/src/util/configuration.c b/src/util/configuration.c
index f327071de..4e7659276 100644
--- a/src/util/configuration.c
+++ b/src/util/configuration.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/configuration.c 22 * @file src/util/configuration.c
@@ -30,17 +30,15 @@
30#include "gnunet_configuration_lib.h" 30#include "gnunet_configuration_lib.h"
31#include "gnunet_disk_lib.h" 31#include "gnunet_disk_lib.h"
32 32
33#define LOG(kind, ...) GNUNET_log_from (kind, "util", __VA_ARGS__) 33#define LOG(kind, ...) GNUNET_log_from(kind, "util", __VA_ARGS__)
34 34
35#define LOG_STRERROR_FILE(kind, syscall, filename) \ 35#define LOG_STRERROR_FILE(kind, syscall, filename) \
36 GNUNET_log_from_strerror_file (kind, "util", syscall, filename) 36 GNUNET_log_from_strerror_file(kind, "util", syscall, filename)
37 37
38/** 38/**
39 * @brief configuration entry 39 * @brief configuration entry
40 */ 40 */
41struct ConfigEntry 41struct ConfigEntry {
42{
43
44 /** 42 /**
45 * This is a linked list. 43 * This is a linked list.
46 */ 44 */
@@ -61,8 +59,7 @@ struct ConfigEntry
61/** 59/**
62 * @brief configuration section 60 * @brief configuration section
63 */ 61 */
64struct ConfigSection 62struct ConfigSection {
65{
66 /** 63 /**
67 * This is a linked list. 64 * This is a linked list.
68 */ 65 */
@@ -83,8 +80,7 @@ struct ConfigSection
83/** 80/**
84 * @brief configuration data 81 * @brief configuration data
85 */ 82 */
86struct GNUNET_CONFIGURATION_Handle 83struct GNUNET_CONFIGURATION_Handle {
87{
88 /** 84 /**
89 * Configuration sections. 85 * Configuration sections.
90 */ 86 */
@@ -103,8 +99,7 @@ struct GNUNET_CONFIGURATION_Handle
103 * Used for diffing a configuration object against 99 * Used for diffing a configuration object against
104 * the default one 100 * the default one
105 */ 101 */
106struct DiffHandle 102struct DiffHandle {
107{
108 const struct GNUNET_CONFIGURATION_Handle *cfg_default; 103 const struct GNUNET_CONFIGURATION_Handle *cfg_default;
109 104
110 struct GNUNET_CONFIGURATION_Handle *cfgDiff; 105 struct GNUNET_CONFIGURATION_Handle *cfgDiff;
@@ -117,9 +112,9 @@ struct DiffHandle
117 * @return fresh configuration object 112 * @return fresh configuration object
118 */ 113 */
119struct GNUNET_CONFIGURATION_Handle * 114struct GNUNET_CONFIGURATION_Handle *
120GNUNET_CONFIGURATION_create () 115GNUNET_CONFIGURATION_create()
121{ 116{
122 return GNUNET_new (struct GNUNET_CONFIGURATION_Handle); 117 return GNUNET_new(struct GNUNET_CONFIGURATION_Handle);
123} 118}
124 119
125 120
@@ -129,13 +124,13 @@ GNUNET_CONFIGURATION_create ()
129 * @param cfg configuration to destroy 124 * @param cfg configuration to destroy
130 */ 125 */
131void 126void
132GNUNET_CONFIGURATION_destroy (struct GNUNET_CONFIGURATION_Handle *cfg) 127GNUNET_CONFIGURATION_destroy(struct GNUNET_CONFIGURATION_Handle *cfg)
133{ 128{
134 struct ConfigSection *sec; 129 struct ConfigSection *sec;
135 130
136 while (NULL != (sec = cfg->sections)) 131 while (NULL != (sec = cfg->sections))
137 GNUNET_CONFIGURATION_remove_section (cfg, sec->name); 132 GNUNET_CONFIGURATION_remove_section(cfg, sec->name);
138 GNUNET_free (cfg); 133 GNUNET_free(cfg);
139} 134}
140 135
141 136
@@ -151,22 +146,22 @@ GNUNET_CONFIGURATION_destroy (struct GNUNET_CONFIGURATION_Handle *cfg)
151 * otherwise return value from @a cb. 146 * otherwise return value from @a cb.
152 */ 147 */
153int 148int
154GNUNET_CONFIGURATION_parse_and_run (const char *filename, 149GNUNET_CONFIGURATION_parse_and_run(const char *filename,
155 GNUNET_CONFIGURATION_Callback cb, 150 GNUNET_CONFIGURATION_Callback cb,
156 void *cb_cls) 151 void *cb_cls)
157{ 152{
158 struct GNUNET_CONFIGURATION_Handle *cfg; 153 struct GNUNET_CONFIGURATION_Handle *cfg;
159 int ret; 154 int ret;
160 155
161 cfg = GNUNET_CONFIGURATION_create (); 156 cfg = GNUNET_CONFIGURATION_create();
162 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, filename)) 157 if (GNUNET_OK != GNUNET_CONFIGURATION_load(cfg, filename))
163 { 158 {
164 GNUNET_break (0); 159 GNUNET_break(0);
165 GNUNET_CONFIGURATION_destroy (cfg); 160 GNUNET_CONFIGURATION_destroy(cfg);
166 return GNUNET_SYSERR; 161 return GNUNET_SYSERR;
167 } 162 }
168 ret = cb (cb_cls, cfg); 163 ret = cb(cb_cls, cfg);
169 GNUNET_CONFIGURATION_destroy (cfg); 164 GNUNET_CONFIGURATION_destroy(cfg);
170 return ret; 165 return ret;
171} 166}
172 167
@@ -183,10 +178,10 @@ GNUNET_CONFIGURATION_parse_and_run (const char *filename,
183 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 178 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
184 */ 179 */
185int 180int
186GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg, 181GNUNET_CONFIGURATION_deserialize(struct GNUNET_CONFIGURATION_Handle *cfg,
187 const char *mem, 182 const char *mem,
188 size_t size, 183 size_t size,
189 const char *basedir) 184 const char *basedir)
190{ 185{
191 char *line; 186 char *line;
192 char *line_orig; 187 char *line_orig;
@@ -204,133 +199,133 @@ GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg,
204 char *value; 199 char *value;
205 200
206 ret = GNUNET_OK; 201 ret = GNUNET_OK;
207 section = GNUNET_strdup (""); 202 section = GNUNET_strdup("");
208 nr = 0; 203 nr = 0;
209 r_bytes = 0; 204 r_bytes = 0;
210 line_orig = NULL; 205 line_orig = NULL;
211 while (r_bytes < size) 206 while (r_bytes < size)
212 {
213 GNUNET_free_non_null (line_orig);
214 /* fgets-like behaviour on buffer */
215 to_read = size - r_bytes;
216 pos = memchr (&mem[r_bytes], '\n', to_read);
217 if (NULL == pos)
218 {
219 line_orig = GNUNET_strndup (&mem[r_bytes], line_size = to_read);
220 r_bytes += line_size;
221 }
222 else
223 { 207 {
224 line_orig = 208 GNUNET_free_non_null(line_orig);
225 GNUNET_strndup (&mem[r_bytes], line_size = (pos - &mem[r_bytes])); 209 /* fgets-like behaviour on buffer */
226 r_bytes += line_size + 1; 210 to_read = size - r_bytes;
227 } 211 pos = memchr(&mem[r_bytes], '\n', to_read);
228 line = line_orig; 212 if (NULL == pos)
229 /* increment line number */
230 nr++;
231 /* tabs and '\r' are whitespace */
232 emptyline = GNUNET_YES;
233 for (i = 0; i < line_size; i++)
234 {
235 if (line[i] == '\t')
236 line[i] = ' ';
237 if (line[i] == '\r')
238 line[i] = ' ';
239 if (' ' != line[i])
240 emptyline = GNUNET_NO;
241 }
242 /* ignore empty lines */
243 if (GNUNET_YES == emptyline)
244 continue;
245
246 /* remove tailing whitespace */
247 for (i = line_size - 1; (i >= 1) && (isspace ((unsigned char) line[i]));
248 i--)
249 line[i] = '\0';
250
251 /* remove leading whitespace */
252 for (; line[0] != '\0' && (isspace ((unsigned char) line[0])); line++)
253 ;
254
255 /* ignore comments */
256 if (('#' == line[0]) || ('%' == line[0]))
257 continue;
258
259 /* handle special "@INLINE@" directive */
260 if (0 == strncasecmp (line, "@INLINE@ ", strlen ("@INLINE@ ")))
261 {
262 /* @INLINE@ value */
263 value = &line[strlen ("@INLINE@ ")];
264 if (NULL != basedir)
265 {
266 char *fn;
267
268 GNUNET_asprintf (&fn, "%s/%s", basedir, value);
269 if (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg, fn))
270 { 213 {
271 GNUNET_free (fn); 214 line_orig = GNUNET_strndup(&mem[r_bytes], line_size = to_read);
272 ret = GNUNET_SYSERR; /* failed to parse included config */ 215 r_bytes += line_size;
273 break;
274 } 216 }
275 GNUNET_free (fn);
276 }
277 else 217 else
278 { 218 {
279 LOG (GNUNET_ERROR_TYPE_DEBUG, 219 line_orig =
280 "Ignoring parsing @INLINE@ configurations, not allowed!\n"); 220 GNUNET_strndup(&mem[r_bytes], line_size = (pos - &mem[r_bytes]));
281 ret = GNUNET_SYSERR; 221 r_bytes += line_size + 1;
282 break; 222 }
283 } 223 line = line_orig;
284 continue; 224 /* increment line number */
285 } 225 nr++;
286 if (('[' == line[0]) && (']' == line[line_size - 1])) 226 /* tabs and '\r' are whitespace */
287 { 227 emptyline = GNUNET_YES;
288 /* [value] */ 228 for (i = 0; i < line_size; i++)
289 line[line_size - 1] = '\0'; 229 {
290 value = &line[1]; 230 if (line[i] == '\t')
291 GNUNET_free (section); 231 line[i] = ' ';
292 section = GNUNET_strdup (value); 232 if (line[i] == '\r')
293 continue; 233 line[i] = ' ';
294 } 234 if (' ' != line[i])
295 if (NULL != (eq = strchr (line, '='))) 235 emptyline = GNUNET_NO;
296 { 236 }
297 /* tag = value */ 237 /* ignore empty lines */
298 tag = GNUNET_strndup (line, eq - line); 238 if (GNUNET_YES == emptyline)
239 continue;
240
299 /* remove tailing whitespace */ 241 /* remove tailing whitespace */
300 for (i = strlen (tag) - 1; (i >= 1) && (isspace ((unsigned char) tag[i])); 242 for (i = line_size - 1; (i >= 1) && (isspace((unsigned char)line[i]));
301 i--)
302 tag[i] = '\0';
303
304 /* Strip whitespace */
305 value = eq + 1;
306 while (isspace ((unsigned char) value[0]))
307 value++;
308 for (i = strlen (value) - 1;
309 (i >= 1) && (isspace ((unsigned char) value[i]));
310 i--) 243 i--)
311 value[i] = '\0'; 244 line[i] = '\0';
312 245
313 /* remove quotes */ 246 /* remove leading whitespace */
314 i = 0; 247 for (; line[0] != '\0' && (isspace((unsigned char)line[0])); line++)
315 if (('"' == value[0]) && ('"' == value[strlen (value) - 1])) 248 ;
316 { 249
317 value[strlen (value) - 1] = '\0'; 250 /* ignore comments */
318 value++; 251 if (('#' == line[0]) || ('%' == line[0]))
319 } 252 continue;
320 GNUNET_CONFIGURATION_set_value_string (cfg, section, tag, &value[i]); 253
321 GNUNET_free (tag); 254 /* handle special "@INLINE@" directive */
322 continue; 255 if (0 == strncasecmp(line, "@INLINE@ ", strlen("@INLINE@ ")))
256 {
257 /* @INLINE@ value */
258 value = &line[strlen("@INLINE@ ")];
259 if (NULL != basedir)
260 {
261 char *fn;
262
263 GNUNET_asprintf(&fn, "%s/%s", basedir, value);
264 if (GNUNET_OK != GNUNET_CONFIGURATION_parse(cfg, fn))
265 {
266 GNUNET_free(fn);
267 ret = GNUNET_SYSERR; /* failed to parse included config */
268 break;
269 }
270 GNUNET_free(fn);
271 }
272 else
273 {
274 LOG(GNUNET_ERROR_TYPE_DEBUG,
275 "Ignoring parsing @INLINE@ configurations, not allowed!\n");
276 ret = GNUNET_SYSERR;
277 break;
278 }
279 continue;
280 }
281 if (('[' == line[0]) && (']' == line[line_size - 1]))
282 {
283 /* [value] */
284 line[line_size - 1] = '\0';
285 value = &line[1];
286 GNUNET_free(section);
287 section = GNUNET_strdup(value);
288 continue;
289 }
290 if (NULL != (eq = strchr(line, '=')))
291 {
292 /* tag = value */
293 tag = GNUNET_strndup(line, eq - line);
294 /* remove tailing whitespace */
295 for (i = strlen(tag) - 1; (i >= 1) && (isspace((unsigned char)tag[i]));
296 i--)
297 tag[i] = '\0';
298
299 /* Strip whitespace */
300 value = eq + 1;
301 while (isspace((unsigned char)value[0]))
302 value++;
303 for (i = strlen(value) - 1;
304 (i >= 1) && (isspace((unsigned char)value[i]));
305 i--)
306 value[i] = '\0';
307
308 /* remove quotes */
309 i = 0;
310 if (('"' == value[0]) && ('"' == value[strlen(value) - 1]))
311 {
312 value[strlen(value) - 1] = '\0';
313 value++;
314 }
315 GNUNET_CONFIGURATION_set_value_string(cfg, section, tag, &value[i]);
316 GNUNET_free(tag);
317 continue;
318 }
319 /* parse error */
320 LOG(GNUNET_ERROR_TYPE_WARNING,
321 _("Syntax error while deserializing in line %u\n"),
322 nr);
323 ret = GNUNET_SYSERR;
324 break;
323 } 325 }
324 /* parse error */ 326 GNUNET_free_non_null(line_orig);
325 LOG (GNUNET_ERROR_TYPE_WARNING, 327 GNUNET_free(section);
326 _ ("Syntax error while deserializing in line %u\n"), 328 GNUNET_assert((GNUNET_OK != ret) || (r_bytes == size));
327 nr);
328 ret = GNUNET_SYSERR;
329 break;
330 }
331 GNUNET_free_non_null (line_orig);
332 GNUNET_free (section);
333 GNUNET_assert ((GNUNET_OK != ret) || (r_bytes == size));
334 return ret; 329 return ret;
335} 330}
336 331
@@ -344,8 +339,8 @@ GNUNET_CONFIGURATION_deserialize (struct GNUNET_CONFIGURATION_Handle *cfg,
344 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 339 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
345 */ 340 */
346int 341int
347GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg, 342GNUNET_CONFIGURATION_parse(struct GNUNET_CONFIGURATION_Handle *cfg,
348 const char *filename) 343 const char *filename)
349{ 344{
350 uint64_t fs64; 345 uint64_t fs64;
351 size_t fs; 346 size_t fs;
@@ -356,43 +351,43 @@ GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg,
356 int ret; 351 int ret;
357 ssize_t sret; 352 ssize_t sret;
358 353
359 fn = GNUNET_STRINGS_filename_expand (filename); 354 fn = GNUNET_STRINGS_filename_expand(filename);
360 LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to parse config file `%s'\n", fn); 355 LOG(GNUNET_ERROR_TYPE_DEBUG, "Asked to parse config file `%s'\n", fn);
361 if (NULL == fn) 356 if (NULL == fn)
362 return GNUNET_SYSERR; 357 return GNUNET_SYSERR;
363 dirty = cfg->dirty; /* back up value! */ 358 dirty = cfg->dirty; /* back up value! */
364 if (GNUNET_SYSERR == 359 if (GNUNET_SYSERR ==
365 GNUNET_DISK_file_size (fn, &fs64, GNUNET_YES, GNUNET_YES)) 360 GNUNET_DISK_file_size(fn, &fs64, GNUNET_YES, GNUNET_YES))
366 { 361 {
367 LOG (GNUNET_ERROR_TYPE_WARNING, 362 LOG(GNUNET_ERROR_TYPE_WARNING,
368 "Error while determining the file size of `%s'\n", 363 "Error while determining the file size of `%s'\n",
369 fn); 364 fn);
370 GNUNET_free (fn); 365 GNUNET_free(fn);
371 return GNUNET_SYSERR; 366 return GNUNET_SYSERR;
372 } 367 }
373 if (fs64 > SIZE_MAX) 368 if (fs64 > SIZE_MAX)
374 { 369 {
375 GNUNET_break (0); /* File size is more than the heap size */ 370 GNUNET_break(0); /* File size is more than the heap size */
376 GNUNET_free (fn); 371 GNUNET_free(fn);
377 return GNUNET_SYSERR; 372 return GNUNET_SYSERR;
378 } 373 }
379 fs = fs64; 374 fs = fs64;
380 mem = GNUNET_malloc (fs); 375 mem = GNUNET_malloc(fs);
381 sret = GNUNET_DISK_fn_read (fn, mem, fs); 376 sret = GNUNET_DISK_fn_read(fn, mem, fs);
382 if ((sret < 0) || (fs != (size_t) sret)) 377 if ((sret < 0) || (fs != (size_t)sret))
383 { 378 {
384 LOG (GNUNET_ERROR_TYPE_WARNING, _ ("Error while reading file `%s'\n"), fn); 379 LOG(GNUNET_ERROR_TYPE_WARNING, _("Error while reading file `%s'\n"), fn);
385 GNUNET_free (fn); 380 GNUNET_free(fn);
386 GNUNET_free (mem); 381 GNUNET_free(mem);
387 return GNUNET_SYSERR; 382 return GNUNET_SYSERR;
388 } 383 }
389 LOG (GNUNET_ERROR_TYPE_DEBUG, "Deserializing contents of file `%s'\n", fn); 384 LOG(GNUNET_ERROR_TYPE_DEBUG, "Deserializing contents of file `%s'\n", fn);
390 endsep = strrchr (fn, (int) '/'); 385 endsep = strrchr(fn, (int)'/');
391 if (NULL != endsep) 386 if (NULL != endsep)
392 *endsep = '\0'; 387 *endsep = '\0';
393 ret = GNUNET_CONFIGURATION_deserialize (cfg, mem, fs, fn); 388 ret = GNUNET_CONFIGURATION_deserialize(cfg, mem, fs, fn);
394 GNUNET_free (fn); 389 GNUNET_free(fn);
395 GNUNET_free (mem); 390 GNUNET_free(mem);
396 /* restore dirty flag - anything we set in the meantime 391 /* restore dirty flag - anything we set in the meantime
397 * came from disk */ 392 * came from disk */
398 cfg->dirty = dirty; 393 cfg->dirty = dirty;
@@ -408,7 +403,7 @@ GNUNET_CONFIGURATION_parse (struct GNUNET_CONFIGURATION_Handle *cfg,
408 * @return #GNUNET_NO if clean, #GNUNET_YES if dirty, #GNUNET_SYSERR on error (i.e. last save failed) 403 * @return #GNUNET_NO if clean, #GNUNET_YES if dirty, #GNUNET_SYSERR on error (i.e. last save failed)
409 */ 404 */
410int 405int
411GNUNET_CONFIGURATION_is_dirty (const struct GNUNET_CONFIGURATION_Handle *cfg) 406GNUNET_CONFIGURATION_is_dirty(const struct GNUNET_CONFIGURATION_Handle *cfg)
412{ 407{
413 return cfg->dirty; 408 return cfg->dirty;
414} 409}
@@ -423,8 +418,8 @@ GNUNET_CONFIGURATION_is_dirty (const struct GNUNET_CONFIGURATION_Handle *cfg)
423 * present. This memory should be freed by the caller 418 * present. This memory should be freed by the caller
424 */ 419 */
425char * 420char *
426GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg, 421GNUNET_CONFIGURATION_serialize(const struct GNUNET_CONFIGURATION_Handle *cfg,
427 size_t *size) 422 size_t *size)
428{ 423{
429 struct ConfigSection *sec; 424 struct ConfigSection *sec;
430 struct ConfigEntry *ent; 425 struct ConfigEntry *ent;
@@ -439,65 +434,65 @@ GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg,
439 /* Pass1 : calculate the buffer size required */ 434 /* Pass1 : calculate the buffer size required */
440 m_size = 0; 435 m_size = 0;
441 for (sec = cfg->sections; NULL != sec; sec = sec->next) 436 for (sec = cfg->sections; NULL != sec; sec = sec->next)
442 {
443 /* For each section we need to add 3 charaters: {'[',']','\n'} */
444 m_size += strlen (sec->name) + 3;
445 for (ent = sec->entries; NULL != ent; ent = ent->next)
446 { 437 {
447 if (NULL != ent->val) 438 /* For each section we need to add 3 charaters: {'[',']','\n'} */
448 { 439 m_size += strlen(sec->name) + 3;
449 /* if val has any '\n' then they occupy +1 character as '\n'->'\\','n' */ 440 for (ent = sec->entries; NULL != ent; ent = ent->next)
450 pos = ent->val;
451 while (NULL != (pos = strstr (pos, "\n")))
452 { 441 {
453 m_size++; 442 if (NULL != ent->val)
454 pos++; 443 {
444 /* if val has any '\n' then they occupy +1 character as '\n'->'\\','n' */
445 pos = ent->val;
446 while (NULL != (pos = strstr(pos, "\n")))
447 {
448 m_size++;
449 pos++;
450 }
451 /* For each key = value pair we need to add 4 characters (2
452 spaces and 1 equal-to character and 1 new line) */
453 m_size += strlen(ent->key) + strlen(ent->val) + 4;
454 }
455 } 455 }
456 /* For each key = value pair we need to add 4 characters (2 456 /* A new line after section end */
457 spaces and 1 equal-to character and 1 new line) */ 457 m_size++;
458 m_size += strlen (ent->key) + strlen (ent->val) + 4;
459 }
460 } 458 }
461 /* A new line after section end */
462 m_size++;
463 }
464 459
465 /* Pass2: Allocate memory and write the configuration to it */ 460 /* Pass2: Allocate memory and write the configuration to it */
466 mem = GNUNET_malloc (m_size); 461 mem = GNUNET_malloc(m_size);
467 sec = cfg->sections; 462 sec = cfg->sections;
468 c_size = 0; 463 c_size = 0;
469 *size = c_size; 464 *size = c_size;
470 while (NULL != sec) 465 while (NULL != sec)
471 {
472 len = GNUNET_asprintf (&cbuf, "[%s]\n", sec->name);
473 GNUNET_assert (0 < len);
474 GNUNET_memcpy (mem + c_size, cbuf, len);
475 c_size += len;
476 GNUNET_free (cbuf);
477 for (ent = sec->entries; NULL != ent; ent = ent->next)
478 { 466 {
479 if (NULL != ent->val) 467 len = GNUNET_asprintf(&cbuf, "[%s]\n", sec->name);
480 { 468 GNUNET_assert(0 < len);
481 val = GNUNET_malloc (strlen (ent->val) * 2 + 1); 469 GNUNET_memcpy(mem + c_size, cbuf, len);
482 strcpy (val, ent->val); 470 c_size += len;
483 while (NULL != (pos = strstr (val, "\n"))) 471 GNUNET_free(cbuf);
472 for (ent = sec->entries; NULL != ent; ent = ent->next)
484 { 473 {
485 memmove (&pos[2], &pos[1], strlen (&pos[1])); 474 if (NULL != ent->val)
486 pos[0] = '\\'; 475 {
487 pos[1] = 'n'; 476 val = GNUNET_malloc(strlen(ent->val) * 2 + 1);
477 strcpy(val, ent->val);
478 while (NULL != (pos = strstr(val, "\n")))
479 {
480 memmove(&pos[2], &pos[1], strlen(&pos[1]));
481 pos[0] = '\\';
482 pos[1] = 'n';
483 }
484 len = GNUNET_asprintf(&cbuf, "%s = %s\n", ent->key, val);
485 GNUNET_free(val);
486 GNUNET_memcpy(mem + c_size, cbuf, len);
487 c_size += len;
488 GNUNET_free(cbuf);
489 }
488 } 490 }
489 len = GNUNET_asprintf (&cbuf, "%s = %s\n", ent->key, val); 491 GNUNET_memcpy(mem + c_size, "\n", 1);
490 GNUNET_free (val); 492 c_size++;
491 GNUNET_memcpy (mem + c_size, cbuf, len); 493 sec = sec->next;
492 c_size += len;
493 GNUNET_free (cbuf);
494 }
495 } 494 }
496 GNUNET_memcpy (mem + c_size, "\n", 1); 495 GNUNET_assert(c_size == m_size);
497 c_size++;
498 sec = sec->next;
499 }
500 GNUNET_assert (c_size == m_size);
501 *size = c_size; 496 *size = c_size;
502 return mem; 497 return mem;
503} 498}
@@ -511,42 +506,42 @@ GNUNET_CONFIGURATION_serialize (const struct GNUNET_CONFIGURATION_Handle *cfg,
511 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 506 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
512 */ 507 */
513int 508int
514GNUNET_CONFIGURATION_write (struct GNUNET_CONFIGURATION_Handle *cfg, 509GNUNET_CONFIGURATION_write(struct GNUNET_CONFIGURATION_Handle *cfg,
515 const char *filename) 510 const char *filename)
516{ 511{
517 char *fn; 512 char *fn;
518 char *cfg_buf; 513 char *cfg_buf;
519 size_t size; 514 size_t size;
520 ssize_t sret; 515 ssize_t sret;
521 516
522 fn = GNUNET_STRINGS_filename_expand (filename); 517 fn = GNUNET_STRINGS_filename_expand(filename);
523 if (fn == NULL) 518 if (fn == NULL)
524 return GNUNET_SYSERR; 519 return GNUNET_SYSERR;
525 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file (fn)) 520 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file(fn))
526 { 521 {
527 GNUNET_free (fn); 522 GNUNET_free(fn);
528 return GNUNET_SYSERR; 523 return GNUNET_SYSERR;
529 } 524 }
530 cfg_buf = GNUNET_CONFIGURATION_serialize (cfg, &size); 525 cfg_buf = GNUNET_CONFIGURATION_serialize(cfg, &size);
531 sret = GNUNET_DISK_fn_write (fn, 526 sret = GNUNET_DISK_fn_write(fn,
532 cfg_buf, 527 cfg_buf,
533 size, 528 size,
534 GNUNET_DISK_PERM_USER_READ | 529 GNUNET_DISK_PERM_USER_READ |
535 GNUNET_DISK_PERM_USER_WRITE | 530 GNUNET_DISK_PERM_USER_WRITE |
536 GNUNET_DISK_PERM_GROUP_READ | 531 GNUNET_DISK_PERM_GROUP_READ |
537 GNUNET_DISK_PERM_GROUP_WRITE); 532 GNUNET_DISK_PERM_GROUP_WRITE);
538 if ((sret < 0) || (size != (size_t) sret)) 533 if ((sret < 0) || (size != (size_t)sret))
539 { 534 {
540 GNUNET_free (fn); 535 GNUNET_free(fn);
541 GNUNET_free (cfg_buf); 536 GNUNET_free(cfg_buf);
542 LOG (GNUNET_ERROR_TYPE_WARNING, 537 LOG(GNUNET_ERROR_TYPE_WARNING,
543 "Writing configuration to file `%s' failed\n", 538 "Writing configuration to file `%s' failed\n",
544 filename); 539 filename);
545 cfg->dirty = GNUNET_SYSERR; /* last write failed */ 540 cfg->dirty = GNUNET_SYSERR; /* last write failed */
546 return GNUNET_SYSERR; 541 return GNUNET_SYSERR;
547 } 542 }
548 GNUNET_free (fn); 543 GNUNET_free(fn);
549 GNUNET_free (cfg_buf); 544 GNUNET_free(cfg_buf);
550 cfg->dirty = GNUNET_NO; /* last write succeeded */ 545 cfg->dirty = GNUNET_NO; /* last write succeeded */
551 return GNUNET_OK; 546 return GNUNET_OK;
552} 547}
@@ -560,9 +555,9 @@ GNUNET_CONFIGURATION_write (struct GNUNET_CONFIGURATION_Handle *cfg,
560 * @param iter_cls closure for @a iter 555 * @param iter_cls closure for @a iter
561 */ 556 */
562void 557void
563GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg, 558GNUNET_CONFIGURATION_iterate(const struct GNUNET_CONFIGURATION_Handle *cfg,
564 GNUNET_CONFIGURATION_Iterator iter, 559 GNUNET_CONFIGURATION_Iterator iter,
565 void *iter_cls) 560 void *iter_cls)
566{ 561{
567 struct ConfigSection *spos; 562 struct ConfigSection *spos;
568 struct ConfigEntry *epos; 563 struct ConfigEntry *epos;
@@ -570,7 +565,7 @@ GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg,
570 for (spos = cfg->sections; NULL != spos; spos = spos->next) 565 for (spos = cfg->sections; NULL != spos; spos = spos->next)
571 for (epos = spos->entries; NULL != epos; epos = epos->next) 566 for (epos = spos->entries; NULL != epos; epos = epos->next)
572 if (NULL != epos->val) 567 if (NULL != epos->val)
573 iter (iter_cls, spos->name, epos->key, epos->val); 568 iter(iter_cls, spos->name, epos->key, epos->val);
574} 569}
575 570
576 571
@@ -583,7 +578,7 @@ GNUNET_CONFIGURATION_iterate (const struct GNUNET_CONFIGURATION_Handle *cfg,
583 * @param iter_cls closure for @a iter 578 * @param iter_cls closure for @a iter
584 */ 579 */
585void 580void
586GNUNET_CONFIGURATION_iterate_section_values ( 581GNUNET_CONFIGURATION_iterate_section_values(
587 const struct GNUNET_CONFIGURATION_Handle *cfg, 582 const struct GNUNET_CONFIGURATION_Handle *cfg,
588 const char *section, 583 const char *section,
589 GNUNET_CONFIGURATION_Iterator iter, 584 GNUNET_CONFIGURATION_Iterator iter,
@@ -593,13 +588,13 @@ GNUNET_CONFIGURATION_iterate_section_values (
593 struct ConfigEntry *epos; 588 struct ConfigEntry *epos;
594 589
595 spos = cfg->sections; 590 spos = cfg->sections;
596 while ((spos != NULL) && (0 != strcasecmp (spos->name, section))) 591 while ((spos != NULL) && (0 != strcasecmp(spos->name, section)))
597 spos = spos->next; 592 spos = spos->next;
598 if (NULL == spos) 593 if (NULL == spos)
599 return; 594 return;
600 for (epos = spos->entries; NULL != epos; epos = epos->next) 595 for (epos = spos->entries; NULL != epos; epos = epos->next)
601 if (NULL != epos->val) 596 if (NULL != epos->val)
602 iter (iter_cls, spos->name, epos->key, epos->val); 597 iter(iter_cls, spos->name, epos->key, epos->val);
603} 598}
604 599
605 600
@@ -611,7 +606,7 @@ GNUNET_CONFIGURATION_iterate_section_values (
611 * @param iter_cls closure for @a iter 606 * @param iter_cls closure for @a iter
612 */ 607 */
613void 608void
614GNUNET_CONFIGURATION_iterate_sections ( 609GNUNET_CONFIGURATION_iterate_sections(
615 const struct GNUNET_CONFIGURATION_Handle *cfg, 610 const struct GNUNET_CONFIGURATION_Handle *cfg,
616 GNUNET_CONFIGURATION_Section_Iterator iter, 611 GNUNET_CONFIGURATION_Section_Iterator iter,
617 void *iter_cls) 612 void *iter_cls)
@@ -621,11 +616,11 @@ GNUNET_CONFIGURATION_iterate_sections (
621 616
622 next = cfg->sections; 617 next = cfg->sections;
623 while (next != NULL) 618 while (next != NULL)
624 { 619 {
625 spos = next; 620 spos = next;
626 next = spos->next; 621 next = spos->next;
627 iter (iter_cls, spos->name); 622 iter(iter_cls, spos->name);
628 } 623 }
629} 624}
630 625
631 626
@@ -636,8 +631,8 @@ GNUNET_CONFIGURATION_iterate_sections (
636 * @param section name of the section to remove 631 * @param section name of the section to remove
637 */ 632 */
638void 633void
639GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg, 634GNUNET_CONFIGURATION_remove_section(struct GNUNET_CONFIGURATION_Handle *cfg,
640 const char *section) 635 const char *section)
641{ 636{
642 struct ConfigSection *spos; 637 struct ConfigSection *spos;
643 struct ConfigSection *prev; 638 struct ConfigSection *prev;
@@ -646,28 +641,28 @@ GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg,
646 prev = NULL; 641 prev = NULL;
647 spos = cfg->sections; 642 spos = cfg->sections;
648 while (NULL != spos) 643 while (NULL != spos)
649 {
650 if (0 == strcasecmp (section, spos->name))
651 { 644 {
652 if (NULL == prev) 645 if (0 == strcasecmp(section, spos->name))
653 cfg->sections = spos->next; 646 {
654 else 647 if (NULL == prev)
655 prev->next = spos->next; 648 cfg->sections = spos->next;
656 while (NULL != (ent = spos->entries)) 649 else
657 { 650 prev->next = spos->next;
658 spos->entries = ent->next; 651 while (NULL != (ent = spos->entries))
659 GNUNET_free (ent->key); 652 {
660 GNUNET_free_non_null (ent->val); 653 spos->entries = ent->next;
661 GNUNET_free (ent); 654 GNUNET_free(ent->key);
662 cfg->dirty = GNUNET_YES; 655 GNUNET_free_non_null(ent->val);
663 } 656 GNUNET_free(ent);
664 GNUNET_free (spos->name); 657 cfg->dirty = GNUNET_YES;
665 GNUNET_free (spos); 658 }
666 return; 659 GNUNET_free(spos->name);
660 GNUNET_free(spos);
661 return;
662 }
663 prev = spos;
664 spos = spos->next;
667 } 665 }
668 prev = spos;
669 spos = spos->next;
670 }
671} 666}
672 667
673 668
@@ -681,14 +676,14 @@ GNUNET_CONFIGURATION_remove_section (struct GNUNET_CONFIGURATION_Handle *cfg,
681 * @param value value to copy 676 * @param value value to copy
682 */ 677 */
683static void 678static void
684copy_entry (void *cls, 679copy_entry(void *cls,
685 const char *section, 680 const char *section,
686 const char *option, 681 const char *option,
687 const char *value) 682 const char *value)
688{ 683{
689 struct GNUNET_CONFIGURATION_Handle *dst = cls; 684 struct GNUNET_CONFIGURATION_Handle *dst = cls;
690 685
691 GNUNET_CONFIGURATION_set_value_string (dst, section, option, value); 686 GNUNET_CONFIGURATION_set_value_string(dst, section, option, value);
692} 687}
693 688
694 689
@@ -699,12 +694,12 @@ copy_entry (void *cls,
699 * @return duplicate configuration 694 * @return duplicate configuration
700 */ 695 */
701struct GNUNET_CONFIGURATION_Handle * 696struct GNUNET_CONFIGURATION_Handle *
702GNUNET_CONFIGURATION_dup (const struct GNUNET_CONFIGURATION_Handle *cfg) 697GNUNET_CONFIGURATION_dup(const struct GNUNET_CONFIGURATION_Handle *cfg)
703{ 698{
704 struct GNUNET_CONFIGURATION_Handle *ret; 699 struct GNUNET_CONFIGURATION_Handle *ret;
705 700
706 ret = GNUNET_CONFIGURATION_create (); 701 ret = GNUNET_CONFIGURATION_create();
707 GNUNET_CONFIGURATION_iterate (cfg, &copy_entry, ret); 702 GNUNET_CONFIGURATION_iterate(cfg, &copy_entry, ret);
708 return ret; 703 return ret;
709} 704}
710 705
@@ -717,13 +712,13 @@ GNUNET_CONFIGURATION_dup (const struct GNUNET_CONFIGURATION_Handle *cfg)
717 * @return matching entry, NULL if not found 712 * @return matching entry, NULL if not found
718 */ 713 */
719static struct ConfigSection * 714static struct ConfigSection *
720find_section (const struct GNUNET_CONFIGURATION_Handle *cfg, 715find_section(const struct GNUNET_CONFIGURATION_Handle *cfg,
721 const char *section) 716 const char *section)
722{ 717{
723 struct ConfigSection *pos; 718 struct ConfigSection *pos;
724 719
725 pos = cfg->sections; 720 pos = cfg->sections;
726 while ((pos != NULL) && (0 != strcasecmp (section, pos->name))) 721 while ((pos != NULL) && (0 != strcasecmp(section, pos->name)))
727 pos = pos->next; 722 pos = pos->next;
728 return pos; 723 return pos;
729} 724}
@@ -738,17 +733,17 @@ find_section (const struct GNUNET_CONFIGURATION_Handle *cfg,
738 * @return matching entry, NULL if not found 733 * @return matching entry, NULL if not found
739 */ 734 */
740static struct ConfigEntry * 735static struct ConfigEntry *
741find_entry (const struct GNUNET_CONFIGURATION_Handle *cfg, 736find_entry(const struct GNUNET_CONFIGURATION_Handle *cfg,
742 const char *section, 737 const char *section,
743 const char *key) 738 const char *key)
744{ 739{
745 struct ConfigSection *sec; 740 struct ConfigSection *sec;
746 struct ConfigEntry *pos; 741 struct ConfigEntry *pos;
747 742
748 if (NULL == (sec = find_section (cfg, section))) 743 if (NULL == (sec = find_section(cfg, section)))
749 return NULL; 744 return NULL;
750 pos = sec->entries; 745 pos = sec->entries;
751 while ((pos != NULL) && (0 != strcasecmp (key, pos->key))) 746 while ((pos != NULL) && (0 != strcasecmp(key, pos->key)))
752 pos = pos->next; 747 pos = pos->next;
753 return pos; 748 return pos;
754} 749}
@@ -765,19 +760,19 @@ find_entry (const struct GNUNET_CONFIGURATION_Handle *cfg,
765 * @param value value to copy (of the default conf.) 760 * @param value value to copy (of the default conf.)
766 */ 761 */
767static void 762static void
768compare_entries (void *cls, 763compare_entries(void *cls,
769 const char *section, 764 const char *section,
770 const char *option, 765 const char *option,
771 const char *value) 766 const char *value)
772{ 767{
773 struct DiffHandle *dh = cls; 768 struct DiffHandle *dh = cls;
774 struct ConfigEntry *entNew; 769 struct ConfigEntry *entNew;
775 770
776 entNew = find_entry (dh->cfg_default, section, option); 771 entNew = find_entry(dh->cfg_default, section, option);
777 if ((NULL != entNew) && (NULL != entNew->val) && 772 if ((NULL != entNew) && (NULL != entNew->val) &&
778 (0 == strcmp (entNew->val, value))) 773 (0 == strcmp(entNew->val, value)))
779 return; 774 return;
780 GNUNET_CONFIGURATION_set_value_string (dh->cfgDiff, section, option, value); 775 GNUNET_CONFIGURATION_set_value_string(dh->cfgDiff, section, option, value);
781} 776}
782 777
783 778
@@ -789,15 +784,15 @@ compare_entries (void *cls,
789 * @return configuration with only the differences, never NULL 784 * @return configuration with only the differences, never NULL
790 */ 785 */
791struct GNUNET_CONFIGURATION_Handle * 786struct GNUNET_CONFIGURATION_Handle *
792GNUNET_CONFIGURATION_get_diff ( 787GNUNET_CONFIGURATION_get_diff(
793 const struct GNUNET_CONFIGURATION_Handle *cfg_default, 788 const struct GNUNET_CONFIGURATION_Handle *cfg_default,
794 const struct GNUNET_CONFIGURATION_Handle *cfg_new) 789 const struct GNUNET_CONFIGURATION_Handle *cfg_new)
795{ 790{
796 struct DiffHandle diffHandle; 791 struct DiffHandle diffHandle;
797 792
798 diffHandle.cfgDiff = GNUNET_CONFIGURATION_create (); 793 diffHandle.cfgDiff = GNUNET_CONFIGURATION_create();
799 diffHandle.cfg_default = cfg_default; 794 diffHandle.cfg_default = cfg_default;
800 GNUNET_CONFIGURATION_iterate (cfg_new, &compare_entries, &diffHandle); 795 GNUNET_CONFIGURATION_iterate(cfg_new, &compare_entries, &diffHandle);
801 return diffHandle.cfgDiff; 796 return diffHandle.cfgDiff;
802} 797}
803 798
@@ -811,7 +806,7 @@ GNUNET_CONFIGURATION_get_diff (
811 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 806 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
812 */ 807 */
813int 808int
814GNUNET_CONFIGURATION_write_diffs ( 809GNUNET_CONFIGURATION_write_diffs(
815 const struct GNUNET_CONFIGURATION_Handle *cfg_default, 810 const struct GNUNET_CONFIGURATION_Handle *cfg_default,
816 const struct GNUNET_CONFIGURATION_Handle *cfg_new, 811 const struct GNUNET_CONFIGURATION_Handle *cfg_new,
817 const char *filename) 812 const char *filename)
@@ -819,9 +814,9 @@ GNUNET_CONFIGURATION_write_diffs (
819 int ret; 814 int ret;
820 struct GNUNET_CONFIGURATION_Handle *diff; 815 struct GNUNET_CONFIGURATION_Handle *diff;
821 816
822 diff = GNUNET_CONFIGURATION_get_diff (cfg_default, cfg_new); 817 diff = GNUNET_CONFIGURATION_get_diff(cfg_default, cfg_new);
823 ret = GNUNET_CONFIGURATION_write (diff, filename); 818 ret = GNUNET_CONFIGURATION_write(diff, filename);
824 GNUNET_CONFIGURATION_destroy (diff); 819 GNUNET_CONFIGURATION_destroy(diff);
825 return ret; 820 return ret;
826} 821}
827 822
@@ -835,42 +830,42 @@ GNUNET_CONFIGURATION_write_diffs (
835 * @param value value to set 830 * @param value value to set
836 */ 831 */
837void 832void
838GNUNET_CONFIGURATION_set_value_string (struct GNUNET_CONFIGURATION_Handle *cfg, 833GNUNET_CONFIGURATION_set_value_string(struct GNUNET_CONFIGURATION_Handle *cfg,
839 const char *section, 834 const char *section,
840 const char *option, 835 const char *option,
841 const char *value) 836 const char *value)
842{ 837{
843 struct ConfigSection *sec; 838 struct ConfigSection *sec;
844 struct ConfigEntry *e; 839 struct ConfigEntry *e;
845 char *nv; 840 char *nv;
846 841
847 e = find_entry (cfg, section, option); 842 e = find_entry(cfg, section, option);
848 if (NULL != e) 843 if (NULL != e)
849 {
850 if (NULL == value)
851 { 844 {
852 GNUNET_free_non_null (e->val); 845 if (NULL == value)
853 e->val = NULL; 846 {
847 GNUNET_free_non_null(e->val);
848 e->val = NULL;
849 }
850 else
851 {
852 nv = GNUNET_strdup(value);
853 GNUNET_free_non_null(e->val);
854 e->val = nv;
855 }
856 return;
854 } 857 }
855 else 858 sec = find_section(cfg, section);
859 if (sec == NULL)
856 { 860 {
857 nv = GNUNET_strdup (value); 861 sec = GNUNET_new(struct ConfigSection);
858 GNUNET_free_non_null (e->val); 862 sec->name = GNUNET_strdup(section);
859 e->val = nv; 863 sec->next = cfg->sections;
864 cfg->sections = sec;
860 } 865 }
861 return; 866 e = GNUNET_new(struct ConfigEntry);
862 } 867 e->key = GNUNET_strdup(option);
863 sec = find_section (cfg, section); 868 e->val = GNUNET_strdup(value);
864 if (sec == NULL)
865 {
866 sec = GNUNET_new (struct ConfigSection);
867 sec->name = GNUNET_strdup (section);
868 sec->next = cfg->sections;
869 cfg->sections = sec;
870 }
871 e = GNUNET_new (struct ConfigEntry);
872 e->key = GNUNET_strdup (option);
873 e->val = GNUNET_strdup (value);
874 e->next = sec->entries; 869 e->next = sec->entries;
875 sec->entries = e; 870 sec->entries = e;
876} 871}
@@ -885,15 +880,15 @@ GNUNET_CONFIGURATION_set_value_string (struct GNUNET_CONFIGURATION_Handle *cfg,
885 * @param number value to set 880 * @param number value to set
886 */ 881 */
887void 882void
888GNUNET_CONFIGURATION_set_value_number (struct GNUNET_CONFIGURATION_Handle *cfg, 883GNUNET_CONFIGURATION_set_value_number(struct GNUNET_CONFIGURATION_Handle *cfg,
889 const char *section, 884 const char *section,
890 const char *option, 885 const char *option,
891 unsigned long long number) 886 unsigned long long number)
892{ 887{
893 char s[64]; 888 char s[64];
894 889
895 GNUNET_snprintf (s, 64, "%llu", number); 890 GNUNET_snprintf(s, 64, "%llu", number);
896 GNUNET_CONFIGURATION_set_value_string (cfg, section, option, s); 891 GNUNET_CONFIGURATION_set_value_string(cfg, section, option, s);
897} 892}
898 893
899 894
@@ -907,7 +902,7 @@ GNUNET_CONFIGURATION_set_value_number (struct GNUNET_CONFIGURATION_Handle *cfg,
907 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 902 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
908 */ 903 */
909int 904int
910GNUNET_CONFIGURATION_get_value_number ( 905GNUNET_CONFIGURATION_get_value_number(
911 const struct GNUNET_CONFIGURATION_Handle *cfg, 906 const struct GNUNET_CONFIGURATION_Handle *cfg,
912 const char *section, 907 const char *section,
913 const char *option, 908 const char *option,
@@ -916,11 +911,11 @@ GNUNET_CONFIGURATION_get_value_number (
916 struct ConfigEntry *e; 911 struct ConfigEntry *e;
917 char dummy[2]; 912 char dummy[2];
918 913
919 if (NULL == (e = find_entry (cfg, section, option))) 914 if (NULL == (e = find_entry(cfg, section, option)))
920 return GNUNET_SYSERR; 915 return GNUNET_SYSERR;
921 if (NULL == e->val) 916 if (NULL == e->val)
922 return GNUNET_SYSERR; 917 return GNUNET_SYSERR;
923 if (1 != sscanf (e->val, "%llu%1s", number, dummy)) 918 if (1 != sscanf(e->val, "%llu%1s", number, dummy))
924 return GNUNET_SYSERR; 919 return GNUNET_SYSERR;
925 return GNUNET_OK; 920 return GNUNET_OK;
926} 921}
@@ -936,7 +931,7 @@ GNUNET_CONFIGURATION_get_value_number (
936 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 931 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
937 */ 932 */
938int 933int
939GNUNET_CONFIGURATION_get_value_float ( 934GNUNET_CONFIGURATION_get_value_float(
940 const struct GNUNET_CONFIGURATION_Handle *cfg, 935 const struct GNUNET_CONFIGURATION_Handle *cfg,
941 const char *section, 936 const char *section,
942 const char *option, 937 const char *option,
@@ -945,11 +940,11 @@ GNUNET_CONFIGURATION_get_value_float (
945 struct ConfigEntry *e; 940 struct ConfigEntry *e;
946 char dummy[2]; 941 char dummy[2];
947 942
948 if (NULL == (e = find_entry (cfg, section, option))) 943 if (NULL == (e = find_entry(cfg, section, option)))
949 return GNUNET_SYSERR; 944 return GNUNET_SYSERR;
950 if (NULL == e->val) 945 if (NULL == e->val)
951 return GNUNET_SYSERR; 946 return GNUNET_SYSERR;
952 if (1 != sscanf (e->val, "%f%1s", number, dummy)) 947 if (1 != sscanf(e->val, "%f%1s", number, dummy))
953 return GNUNET_SYSERR; 948 return GNUNET_SYSERR;
954 return GNUNET_OK; 949 return GNUNET_OK;
955} 950}
@@ -965,7 +960,7 @@ GNUNET_CONFIGURATION_get_value_float (
965 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 960 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
966 */ 961 */
967int 962int
968GNUNET_CONFIGURATION_get_value_time ( 963GNUNET_CONFIGURATION_get_value_time(
969 const struct GNUNET_CONFIGURATION_Handle *cfg, 964 const struct GNUNET_CONFIGURATION_Handle *cfg,
970 const char *section, 965 const char *section,
971 const char *option, 966 const char *option,
@@ -974,16 +969,16 @@ GNUNET_CONFIGURATION_get_value_time (
974 struct ConfigEntry *e; 969 struct ConfigEntry *e;
975 int ret; 970 int ret;
976 971
977 if (NULL == (e = find_entry (cfg, section, option))) 972 if (NULL == (e = find_entry(cfg, section, option)))
978 return GNUNET_SYSERR; 973 return GNUNET_SYSERR;
979 if (NULL == e->val) 974 if (NULL == e->val)
980 return GNUNET_SYSERR; 975 return GNUNET_SYSERR;
981 ret = GNUNET_STRINGS_fancy_time_to_relative (e->val, time); 976 ret = GNUNET_STRINGS_fancy_time_to_relative(e->val, time);
982 if (GNUNET_OK != ret) 977 if (GNUNET_OK != ret)
983 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, 978 GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR,
984 section, 979 section,
985 option, 980 option,
986 _ ("Not a valid relative time specification")); 981 _("Not a valid relative time specification"));
987 return ret; 982 return ret;
988} 983}
989 984
@@ -998,7 +993,7 @@ GNUNET_CONFIGURATION_get_value_time (
998 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 993 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
999 */ 994 */
1000int 995int
1001GNUNET_CONFIGURATION_get_value_size ( 996GNUNET_CONFIGURATION_get_value_size(
1002 const struct GNUNET_CONFIGURATION_Handle *cfg, 997 const struct GNUNET_CONFIGURATION_Handle *cfg,
1003 const char *section, 998 const char *section,
1004 const char *option, 999 const char *option,
@@ -1006,11 +1001,11 @@ GNUNET_CONFIGURATION_get_value_size (
1006{ 1001{
1007 struct ConfigEntry *e; 1002 struct ConfigEntry *e;
1008 1003
1009 if (NULL == (e = find_entry (cfg, section, option))) 1004 if (NULL == (e = find_entry(cfg, section, option)))
1010 return GNUNET_SYSERR; 1005 return GNUNET_SYSERR;
1011 if (NULL == e->val) 1006 if (NULL == e->val)
1012 return GNUNET_SYSERR; 1007 return GNUNET_SYSERR;
1013 return GNUNET_STRINGS_fancy_size_to_bytes (e->val, size); 1008 return GNUNET_STRINGS_fancy_size_to_bytes(e->val, size);
1014} 1009}
1015 1010
1016 1011
@@ -1025,7 +1020,7 @@ GNUNET_CONFIGURATION_get_value_size (
1025 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1020 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1026 */ 1021 */
1027int 1022int
1028GNUNET_CONFIGURATION_get_value_string ( 1023GNUNET_CONFIGURATION_get_value_string(
1029 const struct GNUNET_CONFIGURATION_Handle *cfg, 1024 const struct GNUNET_CONFIGURATION_Handle *cfg,
1030 const char *section, 1025 const char *section,
1031 const char *option, 1026 const char *option,
@@ -1033,12 +1028,12 @@ GNUNET_CONFIGURATION_get_value_string (
1033{ 1028{
1034 struct ConfigEntry *e; 1029 struct ConfigEntry *e;
1035 1030
1036 if ((NULL == (e = find_entry (cfg, section, option))) || (NULL == e->val)) 1031 if ((NULL == (e = find_entry(cfg, section, option))) || (NULL == e->val))
1037 { 1032 {
1038 *value = NULL; 1033 *value = NULL;
1039 return GNUNET_SYSERR; 1034 return GNUNET_SYSERR;
1040 } 1035 }
1041 *value = GNUNET_strdup (e->val); 1036 *value = GNUNET_strdup(e->val);
1042 return GNUNET_OK; 1037 return GNUNET_OK;
1043} 1038}
1044 1039
@@ -1056,7 +1051,7 @@ GNUNET_CONFIGURATION_get_value_string (
1056 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1051 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1057 */ 1052 */
1058int 1053int
1059GNUNET_CONFIGURATION_get_value_choice ( 1054GNUNET_CONFIGURATION_get_value_choice(
1060 const struct GNUNET_CONFIGURATION_Handle *cfg, 1055 const struct GNUNET_CONFIGURATION_Handle *cfg,
1061 const char *section, 1056 const char *section,
1062 const char *option, 1057 const char *option,
@@ -1066,21 +1061,21 @@ GNUNET_CONFIGURATION_get_value_choice (
1066 struct ConfigEntry *e; 1061 struct ConfigEntry *e;
1067 unsigned int i; 1062 unsigned int i;
1068 1063
1069 if (NULL == (e = find_entry (cfg, section, option))) 1064 if (NULL == (e = find_entry(cfg, section, option)))
1070 return GNUNET_SYSERR; 1065 return GNUNET_SYSERR;
1071 for (i = 0; NULL != choices[i]; i++) 1066 for (i = 0; NULL != choices[i]; i++)
1072 if (0 == strcasecmp (choices[i], e->val)) 1067 if (0 == strcasecmp(choices[i], e->val))
1073 break; 1068 break;
1074 if (NULL == choices[i]) 1069 if (NULL == choices[i])
1075 { 1070 {
1076 LOG (GNUNET_ERROR_TYPE_ERROR, 1071 LOG(GNUNET_ERROR_TYPE_ERROR,
1077 _ ("Configuration value '%s' for '%s'" 1072 _("Configuration value '%s' for '%s'"
1078 " in section '%s' is not in set of legal choices\n"), 1073 " in section '%s' is not in set of legal choices\n"),
1079 e->val, 1074 e->val,
1080 option, 1075 option,
1081 section); 1076 section);
1082 return GNUNET_SYSERR; 1077 return GNUNET_SYSERR;
1083 } 1078 }
1084 *value = choices[i]; 1079 *value = choices[i];
1085 return GNUNET_OK; 1080 return GNUNET_OK;
1086} 1081}
@@ -1099,11 +1094,11 @@ GNUNET_CONFIGURATION_get_value_choice (
1099 * #GNUNET_SYSERR on decoding error 1094 * #GNUNET_SYSERR on decoding error
1100 */ 1095 */
1101int 1096int
1102GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg, 1097GNUNET_CONFIGURATION_get_data(const struct GNUNET_CONFIGURATION_Handle *cfg,
1103 const char *section, 1098 const char *section,
1104 const char *option, 1099 const char *option,
1105 void *buf, 1100 void *buf,
1106 size_t buf_size) 1101 size_t buf_size)
1107{ 1102{
1108 char *enc; 1103 char *enc;
1109 int res; 1104 int res;
@@ -1111,21 +1106,21 @@ GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg,
1111 1106
1112 if (GNUNET_OK != 1107 if (GNUNET_OK !=
1113 (res = 1108 (res =
1114 GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &enc))) 1109 GNUNET_CONFIGURATION_get_value_string(cfg, section, option, &enc)))
1115 return res; 1110 return res;
1116 data_size = (strlen (enc) * 5) / 8; 1111 data_size = (strlen(enc) * 5) / 8;
1117 if (data_size != buf_size) 1112 if (data_size != buf_size)
1118 { 1113 {
1119 GNUNET_free (enc); 1114 GNUNET_free(enc);
1120 return GNUNET_SYSERR; 1115 return GNUNET_SYSERR;
1121 } 1116 }
1122 if (GNUNET_OK != 1117 if (GNUNET_OK !=
1123 GNUNET_STRINGS_string_to_data (enc, strlen (enc), buf, buf_size)) 1118 GNUNET_STRINGS_string_to_data(enc, strlen(enc), buf, buf_size))
1124 { 1119 {
1125 GNUNET_free (enc); 1120 GNUNET_free(enc);
1126 return GNUNET_SYSERR; 1121 return GNUNET_SYSERR;
1127 } 1122 }
1128 GNUNET_free (enc); 1123 GNUNET_free(enc);
1129 return GNUNET_OK; 1124 return GNUNET_OK;
1130} 1125}
1131 1126
@@ -1139,13 +1134,13 @@ GNUNET_CONFIGURATION_get_data (const struct GNUNET_CONFIGURATION_Handle *cfg,
1139 * @return #GNUNET_YES if so, #GNUNET_NO if not. 1134 * @return #GNUNET_YES if so, #GNUNET_NO if not.
1140 */ 1135 */
1141int 1136int
1142GNUNET_CONFIGURATION_have_value (const struct GNUNET_CONFIGURATION_Handle *cfg, 1137GNUNET_CONFIGURATION_have_value(const struct GNUNET_CONFIGURATION_Handle *cfg,
1143 const char *section, 1138 const char *section,
1144 const char *option) 1139 const char *option)
1145{ 1140{
1146 struct ConfigEntry *e; 1141 struct ConfigEntry *e;
1147 1142
1148 if ((NULL == (e = find_entry (cfg, section, option))) || (NULL == e->val)) 1143 if ((NULL == (e = find_entry(cfg, section, option))) || (NULL == e->val))
1149 return GNUNET_NO; 1144 return GNUNET_NO;
1150 return GNUNET_YES; 1145 return GNUNET_YES;
1151} 1146}
@@ -1167,9 +1162,9 @@ GNUNET_CONFIGURATION_have_value (const struct GNUNET_CONFIGURATION_Handle *cfg,
1167 * @return $-expanded string 1162 * @return $-expanded string
1168 */ 1163 */
1169static char * 1164static char *
1170expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cfg, 1165expand_dollar(const struct GNUNET_CONFIGURATION_Handle *cfg,
1171 char *orig, 1166 char *orig,
1172 unsigned int depth) 1167 unsigned int depth)
1173{ 1168{
1174 int i; 1169 int i;
1175 char *prefix; 1170 char *prefix;
@@ -1187,124 +1182,127 @@ expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cfg,
1187 if (NULL == orig) 1182 if (NULL == orig)
1188 return NULL; 1183 return NULL;
1189 if (depth > 128) 1184 if (depth > 128)
1190 { 1185 {
1191 LOG (GNUNET_ERROR_TYPE_WARNING, 1186 LOG(GNUNET_ERROR_TYPE_WARNING,
1192 _ ( 1187 _(
1193 "Recursive expansion suspected, aborting $-expansion for term `%s'\n"), 1188 "Recursive expansion suspected, aborting $-expansion for term `%s'\n"),
1194 orig); 1189 orig);
1195 return orig; 1190 return orig;
1196 } 1191 }
1197 LOG (GNUNET_ERROR_TYPE_DEBUG, "Asked to $-expand %s\n", orig); 1192 LOG(GNUNET_ERROR_TYPE_DEBUG, "Asked to $-expand %s\n", orig);
1198 if ('$' != orig[0]) 1193 if ('$' != orig[0])
1199 { 1194 {
1200 LOG (GNUNET_ERROR_TYPE_DEBUG, "Doesn't start with $ - not expanding\n"); 1195 LOG(GNUNET_ERROR_TYPE_DEBUG, "Doesn't start with $ - not expanding\n");
1201 return orig; 1196 return orig;
1202 } 1197 }
1203 erased_char = 0; 1198 erased_char = 0;
1204 erased_pos = NULL; 1199 erased_pos = NULL;
1205 if ('{' == orig[1]) 1200 if ('{' == orig[1])
1206 {
1207 start = &orig[2];
1208 lopen = 1;
1209 end = &orig[1];
1210 while (lopen > 0)
1211 {
1212 end++;
1213 switch (*end)
1214 {
1215 case '}':
1216 lopen--;
1217 break;
1218 case '{':
1219 lopen++;
1220 break;
1221 case '\0':
1222 LOG (GNUNET_ERROR_TYPE_WARNING,
1223 _ ("Missing closing `%s' in option `%s'\n"),
1224 "}",
1225 orig);
1226 return orig;
1227 default:
1228 break;
1229 }
1230 }
1231 erased_char = *end;
1232 erased_pos = end;
1233 *end = '\0';
1234 post = end + 1;
1235 def = strchr (orig, ':');
1236 if (NULL != def)
1237 { 1201 {
1238 *def = '\0'; 1202 start = &orig[2];
1239 def++; 1203 lopen = 1;
1240 if (('-' == *def) || ('=' == *def)) 1204 end = &orig[1];
1241 def++; 1205 while (lopen > 0)
1242 def = GNUNET_strdup (def); 1206 {
1207 end++;
1208 switch (*end)
1209 {
1210 case '}':
1211 lopen--;
1212 break;
1213
1214 case '{':
1215 lopen++;
1216 break;
1217
1218 case '\0':
1219 LOG(GNUNET_ERROR_TYPE_WARNING,
1220 _("Missing closing `%s' in option `%s'\n"),
1221 "}",
1222 orig);
1223 return orig;
1224
1225 default:
1226 break;
1227 }
1228 }
1229 erased_char = *end;
1230 erased_pos = end;
1231 *end = '\0';
1232 post = end + 1;
1233 def = strchr(orig, ':');
1234 if (NULL != def)
1235 {
1236 *def = '\0';
1237 def++;
1238 if (('-' == *def) || ('=' == *def))
1239 def++;
1240 def = GNUNET_strdup(def);
1241 }
1243 } 1242 }
1244 }
1245 else 1243 else
1246 {
1247 start = &orig[1];
1248 def = NULL;
1249 i = 0;
1250 while ((orig[i] != '/') && (orig[i] != '\\') && (orig[i] != '\0') &&
1251 (orig[i] != ' '))
1252 i++;
1253 if (orig[i] == '\0')
1254 {
1255 post = "";
1256 }
1257 else
1258 { 1244 {
1259 erased_char = orig[i]; 1245 start = &orig[1];
1260 erased_pos = &orig[i]; 1246 def = NULL;
1261 orig[i] = '\0'; 1247 i = 0;
1262 post = &orig[i + 1]; 1248 while ((orig[i] != '/') && (orig[i] != '\\') && (orig[i] != '\0') &&
1249 (orig[i] != ' '))
1250 i++;
1251 if (orig[i] == '\0')
1252 {
1253 post = "";
1254 }
1255 else
1256 {
1257 erased_char = orig[i];
1258 erased_pos = &orig[i];
1259 orig[i] = '\0';
1260 post = &orig[i + 1];
1261 }
1263 } 1262 }
1264 } 1263 LOG(GNUNET_ERROR_TYPE_DEBUG,
1265 LOG (GNUNET_ERROR_TYPE_DEBUG, 1264 "Split into `%s' and `%s' with default %s\n",
1266 "Split into `%s' and `%s' with default %s\n", 1265 start,
1267 start, 1266 post,
1268 post, 1267 def);
1269 def);
1270 if (GNUNET_OK != 1268 if (GNUNET_OK !=
1271 GNUNET_CONFIGURATION_get_value_string (cfg, "PATHS", start, &prefix)) 1269 GNUNET_CONFIGURATION_get_value_string(cfg, "PATHS", start, &prefix))
1272 {
1273 if (NULL == (env = getenv (start)))
1274 { 1270 {
1275 /* try default */ 1271 if (NULL == (env = getenv(start)))
1276 def = expand_dollar (cfg, def, depth + 1); 1272 {
1277 env = def; 1273 /* try default */
1274 def = expand_dollar(cfg, def, depth + 1);
1275 env = def;
1276 }
1277 if (NULL == env)
1278 {
1279 start = GNUNET_strdup(start);
1280 if (erased_pos)
1281 *erased_pos = erased_char;
1282 LOG(GNUNET_ERROR_TYPE_WARNING,
1283 _(
1284 "Failed to expand `%s' in `%s' as it is neither found in [PATHS] nor defined as an environmental variable\n"),
1285 start,
1286 orig);
1287 GNUNET_free(start);
1288 return orig;
1289 }
1290 prefix = GNUNET_strdup(env);
1278 } 1291 }
1279 if (NULL == env) 1292 prefix = GNUNET_CONFIGURATION_expand_dollar(cfg, prefix);
1293 if ((erased_pos) && ('}' != erased_char))
1280 { 1294 {
1281 start = GNUNET_strdup (start); 1295 len = strlen(prefix) + 1;
1282 if (erased_pos) 1296 prefix = GNUNET_realloc(prefix, len + 1);
1283 *erased_pos = erased_char; 1297 prefix[len - 1] = erased_char;
1284 LOG (GNUNET_ERROR_TYPE_WARNING, 1298 prefix[len] = '\0';
1285 _ (
1286 "Failed to expand `%s' in `%s' as it is neither found in [PATHS] nor defined as an environmental variable\n"),
1287 start,
1288 orig);
1289 GNUNET_free (start);
1290 return orig;
1291 } 1299 }
1292 prefix = GNUNET_strdup (env); 1300 result = GNUNET_malloc(strlen(prefix) + strlen(post) + 1);
1293 } 1301 strcpy(result, prefix);
1294 prefix = GNUNET_CONFIGURATION_expand_dollar (cfg, prefix); 1302 strcat(result, post);
1295 if ((erased_pos) && ('}' != erased_char)) 1303 GNUNET_free_non_null(def);
1296 { 1304 GNUNET_free(prefix);
1297 len = strlen (prefix) + 1; 1305 GNUNET_free(orig);
1298 prefix = GNUNET_realloc (prefix, len + 1);
1299 prefix[len - 1] = erased_char;
1300 prefix[len] = '\0';
1301 }
1302 result = GNUNET_malloc (strlen (prefix) + strlen (post) + 1);
1303 strcpy (result, prefix);
1304 strcat (result, post);
1305 GNUNET_free_non_null (def);
1306 GNUNET_free (prefix);
1307 GNUNET_free (orig);
1308 return result; 1306 return result;
1309} 1307}
1310 1308
@@ -1326,7 +1324,7 @@ expand_dollar (const struct GNUNET_CONFIGURATION_Handle *cfg,
1326 * @return $-expanded string 1324 * @return $-expanded string
1327 */ 1325 */
1328char * 1326char *
1329GNUNET_CONFIGURATION_expand_dollar ( 1327GNUNET_CONFIGURATION_expand_dollar(
1330 const struct GNUNET_CONFIGURATION_Handle *cfg, 1328 const struct GNUNET_CONFIGURATION_Handle *cfg,
1331 char *orig) 1329 char *orig)
1332{ 1330{
@@ -1335,16 +1333,16 @@ GNUNET_CONFIGURATION_expand_dollar (
1335 size_t len; 1333 size_t len;
1336 1334
1337 for (i = 0; '\0' != orig[i]; i++) 1335 for (i = 0; '\0' != orig[i]; i++)
1338 { 1336 {
1339 if ('$' != orig[i]) 1337 if ('$' != orig[i])
1340 continue; 1338 continue;
1341 dup = GNUNET_strdup (orig + i); 1339 dup = GNUNET_strdup(orig + i);
1342 dup = expand_dollar (cfg, dup, 0); 1340 dup = expand_dollar(cfg, dup, 0);
1343 len = strlen (dup) + 1; 1341 len = strlen(dup) + 1;
1344 orig = GNUNET_realloc (orig, i + len); 1342 orig = GNUNET_realloc(orig, i + len);
1345 GNUNET_memcpy (orig + i, dup, len); 1343 GNUNET_memcpy(orig + i, dup, len);
1346 GNUNET_free (dup); 1344 GNUNET_free(dup);
1347 } 1345 }
1348 return orig; 1346 return orig;
1349} 1347}
1350 1348
@@ -1360,7 +1358,7 @@ GNUNET_CONFIGURATION_expand_dollar (
1360 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1358 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1361 */ 1359 */
1362int 1360int
1363GNUNET_CONFIGURATION_get_value_filename ( 1361GNUNET_CONFIGURATION_get_value_filename(
1364 const struct GNUNET_CONFIGURATION_Handle *cfg, 1362 const struct GNUNET_CONFIGURATION_Handle *cfg,
1365 const char *section, 1363 const char *section,
1366 const char *option, 1364 const char *option,
@@ -1369,15 +1367,15 @@ GNUNET_CONFIGURATION_get_value_filename (
1369 char *tmp; 1367 char *tmp;
1370 1368
1371 if (GNUNET_OK != 1369 if (GNUNET_OK !=
1372 GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &tmp)) 1370 GNUNET_CONFIGURATION_get_value_string(cfg, section, option, &tmp))
1373 { 1371 {
1374 LOG (GNUNET_ERROR_TYPE_DEBUG, "Failed to retrieve filename\n"); 1372 LOG(GNUNET_ERROR_TYPE_DEBUG, "Failed to retrieve filename\n");
1375 *value = NULL; 1373 *value = NULL;
1376 return GNUNET_SYSERR; 1374 return GNUNET_SYSERR;
1377 } 1375 }
1378 tmp = GNUNET_CONFIGURATION_expand_dollar (cfg, tmp); 1376 tmp = GNUNET_CONFIGURATION_expand_dollar(cfg, tmp);
1379 *value = GNUNET_STRINGS_filename_expand (tmp); 1377 *value = GNUNET_STRINGS_filename_expand(tmp);
1380 GNUNET_free (tmp); 1378 GNUNET_free(tmp);
1381 if (*value == NULL) 1379 if (*value == NULL)
1382 return GNUNET_SYSERR; 1380 return GNUNET_SYSERR;
1383 return GNUNET_OK; 1381 return GNUNET_OK;
@@ -1394,17 +1392,17 @@ GNUNET_CONFIGURATION_get_value_filename (
1394 * @return #GNUNET_YES, #GNUNET_NO or #GNUNET_SYSERR 1392 * @return #GNUNET_YES, #GNUNET_NO or #GNUNET_SYSERR
1395 */ 1393 */
1396int 1394int
1397GNUNET_CONFIGURATION_get_value_yesno ( 1395GNUNET_CONFIGURATION_get_value_yesno(
1398 const struct GNUNET_CONFIGURATION_Handle *cfg, 1396 const struct GNUNET_CONFIGURATION_Handle *cfg,
1399 const char *section, 1397 const char *section,
1400 const char *option) 1398 const char *option)
1401{ 1399{
1402 static const char *yesno[] = {"YES", "NO", NULL}; 1400 static const char *yesno[] = { "YES", "NO", NULL };
1403 const char *val; 1401 const char *val;
1404 int ret; 1402 int ret;
1405 1403
1406 ret = 1404 ret =
1407 GNUNET_CONFIGURATION_get_value_choice (cfg, section, option, yesno, &val); 1405 GNUNET_CONFIGURATION_get_value_choice(cfg, section, option, yesno, &val);
1408 if (ret == GNUNET_SYSERR) 1406 if (ret == GNUNET_SYSERR)
1409 return ret; 1407 return ret;
1410 if (val == yesno[0]) 1408 if (val == yesno[0])
@@ -1424,7 +1422,7 @@ GNUNET_CONFIGURATION_get_value_yesno (
1424 * @return number of filenames iterated over, -1 on error 1422 * @return number of filenames iterated over, -1 on error
1425 */ 1423 */
1426int 1424int
1427GNUNET_CONFIGURATION_iterate_value_filenames ( 1425GNUNET_CONFIGURATION_iterate_value_filenames(
1428 const struct GNUNET_CONFIGURATION_Handle *cfg, 1426 const struct GNUNET_CONFIGURATION_Handle *cfg,
1429 const char *section, 1427 const char *section,
1430 const char *option, 1428 const char *option,
@@ -1438,53 +1436,55 @@ GNUNET_CONFIGURATION_iterate_value_filenames (
1438 int ret; 1436 int ret;
1439 1437
1440 if (GNUNET_OK != 1438 if (GNUNET_OK !=
1441 GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &list)) 1439 GNUNET_CONFIGURATION_get_value_string(cfg, section, option, &list))
1442 return 0; 1440 return 0;
1443 GNUNET_assert (list != NULL); 1441 GNUNET_assert(list != NULL);
1444 ret = 0; 1442 ret = 0;
1445 pos = list; 1443 pos = list;
1446 while (1) 1444 while (1)
1447 {
1448 while (pos[0] == ' ')
1449 pos++;
1450 if (strlen (pos) == 0)
1451 break;
1452 end = pos + 1;
1453 while ((end[0] != ' ') && (end[0] != '\0'))
1454 { 1445 {
1455 if (end[0] == '\\') 1446 while (pos[0] == ' ')
1456 { 1447 pos++;
1457 switch (end[1]) 1448 if (strlen(pos) == 0)
1449 break;
1450 end = pos + 1;
1451 while ((end[0] != ' ') && (end[0] != '\0'))
1458 { 1452 {
1459 case '\\': 1453 if (end[0] == '\\')
1460 case ' ': 1454 {
1461 memmove (end, &end[1], strlen (&end[1]) + 1); 1455 switch (end[1])
1462 case '\0': 1456 {
1463 /* illegal, but just keep it */ 1457 case '\\':
1464 break; 1458 case ' ':
1465 default: 1459 memmove(end, &end[1], strlen(&end[1]) + 1);
1466 /* illegal, but just ignore that there was a '/' */ 1460
1467 break; 1461 case '\0':
1462 /* illegal, but just keep it */
1463 break;
1464
1465 default:
1466 /* illegal, but just ignore that there was a '/' */
1467 break;
1468 }
1469 }
1470 end++;
1468 } 1471 }
1469 } 1472 old = end[0];
1470 end++; 1473 end[0] = '\0';
1471 } 1474 if (strlen(pos) > 0)
1472 old = end[0]; 1475 {
1473 end[0] = '\0'; 1476 ret++;
1474 if (strlen (pos) > 0) 1477 if ((cb != NULL) && (GNUNET_OK != cb(cb_cls, pos)))
1475 { 1478 {
1476 ret++; 1479 ret = GNUNET_SYSERR;
1477 if ((cb != NULL) && (GNUNET_OK != cb (cb_cls, pos))) 1480 break;
1478 { 1481 }
1479 ret = GNUNET_SYSERR; 1482 }
1483 if (old == '\0')
1480 break; 1484 break;
1481 } 1485 pos = end + 1;
1482 } 1486 }
1483 if (old == '\0') 1487 GNUNET_free(list);
1484 break;
1485 pos = end + 1;
1486 }
1487 GNUNET_free (list);
1488 return ret; 1488 return ret;
1489} 1489}
1490 1490
@@ -1496,32 +1496,33 @@ GNUNET_CONFIGURATION_iterate_value_filenames (
1496 * @return FIXME 1496 * @return FIXME
1497 */ 1497 */
1498static char * 1498static char *
1499escape_name (const char *value) 1499escape_name(const char *value)
1500{ 1500{
1501 char *escaped; 1501 char *escaped;
1502 const char *rpos; 1502 const char *rpos;
1503 char *wpos; 1503 char *wpos;
1504 1504
1505 escaped = GNUNET_malloc (strlen (value) * 2 + 1); 1505 escaped = GNUNET_malloc(strlen(value) * 2 + 1);
1506 memset (escaped, 0, strlen (value) * 2 + 1); 1506 memset(escaped, 0, strlen(value) * 2 + 1);
1507 rpos = value; 1507 rpos = value;
1508 wpos = escaped; 1508 wpos = escaped;
1509 while (rpos[0] != '\0') 1509 while (rpos[0] != '\0')
1510 {
1511 switch (rpos[0])
1512 { 1510 {
1513 case '\\': 1511 switch (rpos[0])
1514 case ' ': 1512 {
1515 wpos[0] = '\\'; 1513 case '\\':
1516 wpos[1] = rpos[0]; 1514 case ' ':
1517 wpos += 2; 1515 wpos[0] = '\\';
1518 break; 1516 wpos[1] = rpos[0];
1519 default: 1517 wpos += 2;
1520 wpos[0] = rpos[0]; 1518 break;
1521 wpos++; 1519
1520 default:
1521 wpos[0] = rpos[0];
1522 wpos++;
1523 }
1524 rpos++;
1522 } 1525 }
1523 rpos++;
1524 }
1525 return escaped; 1526 return escaped;
1526} 1527}
1527 1528
@@ -1534,11 +1535,11 @@ escape_name (const char *value)
1534 * @return #GNUNET_OK if the names do not match, #GNUNET_SYSERR if they do 1535 * @return #GNUNET_OK if the names do not match, #GNUNET_SYSERR if they do
1535 */ 1536 */
1536static int 1537static int
1537test_match (void *cls, const char *fn) 1538test_match(void *cls, const char *fn)
1538{ 1539{
1539 const char *of = cls; 1540 const char *of = cls;
1540 1541
1541 return (0 == strcmp (of, fn)) ? GNUNET_SYSERR : GNUNET_OK; 1542 return (0 == strcmp(of, fn)) ? GNUNET_SYSERR : GNUNET_OK;
1542} 1543}
1543 1544
1544 1545
@@ -1555,7 +1556,7 @@ test_match (void *cls, const char *fn)
1555 * #GNUNET_SYSERR on error 1556 * #GNUNET_SYSERR on error
1556 */ 1557 */
1557int 1558int
1558GNUNET_CONFIGURATION_append_value_filename ( 1559GNUNET_CONFIGURATION_append_value_filename(
1559 struct GNUNET_CONFIGURATION_Handle *cfg, 1560 struct GNUNET_CONFIGURATION_Handle *cfg,
1560 const char *section, 1561 const char *section,
1561 const char *option, 1562 const char *option,
@@ -1566,25 +1567,25 @@ GNUNET_CONFIGURATION_append_value_filename (
1566 char *nw; 1567 char *nw;
1567 1568
1568 if (GNUNET_SYSERR == 1569 if (GNUNET_SYSERR ==
1569 GNUNET_CONFIGURATION_iterate_value_filenames (cfg, 1570 GNUNET_CONFIGURATION_iterate_value_filenames(cfg,
1570 section, 1571 section,
1571 option, 1572 option,
1572 &test_match, 1573 &test_match,
1573 (void *) value)) 1574 (void *)value))
1574 return GNUNET_NO; /* already exists */ 1575 return GNUNET_NO; /* already exists */
1575 if (GNUNET_OK != 1576 if (GNUNET_OK !=
1576 GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &old)) 1577 GNUNET_CONFIGURATION_get_value_string(cfg, section, option, &old))
1577 old = GNUNET_strdup (""); 1578 old = GNUNET_strdup("");
1578 escaped = escape_name (value); 1579 escaped = escape_name(value);
1579 nw = GNUNET_malloc (strlen (old) + strlen (escaped) + 2); 1580 nw = GNUNET_malloc(strlen(old) + strlen(escaped) + 2);
1580 strcpy (nw, old); 1581 strcpy(nw, old);
1581 if (strlen (old) > 0) 1582 if (strlen(old) > 0)
1582 strcat (nw, " "); 1583 strcat(nw, " ");
1583 strcat (nw, escaped); 1584 strcat(nw, escaped);
1584 GNUNET_CONFIGURATION_set_value_string (cfg, section, option, nw); 1585 GNUNET_CONFIGURATION_set_value_string(cfg, section, option, nw);
1585 GNUNET_free (old); 1586 GNUNET_free(old);
1586 GNUNET_free (nw); 1587 GNUNET_free(nw);
1587 GNUNET_free (escaped); 1588 GNUNET_free(escaped);
1588 return GNUNET_OK; 1589 return GNUNET_OK;
1589} 1590}
1590 1591
@@ -1602,7 +1603,7 @@ GNUNET_CONFIGURATION_append_value_filename (
1602 * #GNUNET_SYSERR on error 1603 * #GNUNET_SYSERR on error
1603 */ 1604 */
1604int 1605int
1605GNUNET_CONFIGURATION_remove_value_filename ( 1606GNUNET_CONFIGURATION_remove_value_filename(
1606 struct GNUNET_CONFIGURATION_Handle *cfg, 1607 struct GNUNET_CONFIGURATION_Handle *cfg,
1607 const char *section, 1608 const char *section,
1608 const char *option, 1609 const char *option,
@@ -1615,62 +1616,64 @@ GNUNET_CONFIGURATION_remove_value_filename (
1615 char old; 1616 char old;
1616 1617
1617 if (GNUNET_OK != 1618 if (GNUNET_OK !=
1618 GNUNET_CONFIGURATION_get_value_string (cfg, section, option, &list)) 1619 GNUNET_CONFIGURATION_get_value_string(cfg, section, option, &list))
1619 return GNUNET_NO; 1620 return GNUNET_NO;
1620 match = escape_name (value); 1621 match = escape_name(value);
1621 pos = list; 1622 pos = list;
1622 while (1) 1623 while (1)
1623 {
1624 while (pos[0] == ' ')
1625 pos++;
1626 if (strlen (pos) == 0)
1627 break;
1628 end = pos + 1;
1629 while ((end[0] != ' ') && (end[0] != '\0'))
1630 { 1624 {
1631 if (end[0] == '\\') 1625 while (pos[0] == ' ')
1632 { 1626 pos++;
1633 switch (end[1]) 1627 if (strlen(pos) == 0)
1628 break;
1629 end = pos + 1;
1630 while ((end[0] != ' ') && (end[0] != '\0'))
1634 { 1631 {
1635 case '\\': 1632 if (end[0] == '\\')
1636 case ' ': 1633 {
1634 switch (end[1])
1635 {
1636 case '\\':
1637 case ' ':
1638 end++;
1639 break;
1640
1641 case '\0':
1642 /* illegal, but just keep it */
1643 break;
1644
1645 default:
1646 /* illegal, but just ignore that there was a '/' */
1647 break;
1648 }
1649 }
1637 end++; 1650 end++;
1638 break;
1639 case '\0':
1640 /* illegal, but just keep it */
1641 break;
1642 default:
1643 /* illegal, but just ignore that there was a '/' */
1644 break;
1645 } 1651 }
1646 } 1652 old = end[0];
1647 end++; 1653 end[0] = '\0';
1648 } 1654 if (0 == strcmp(pos, match))
1649 old = end[0]; 1655 {
1650 end[0] = '\0'; 1656 if (old != '\0')
1651 if (0 == strcmp (pos, match)) 1657 memmove(pos, &end[1], strlen(&end[1]) + 1);
1652 { 1658 else
1653 if (old != '\0') 1659 {
1654 memmove (pos, &end[1], strlen (&end[1]) + 1); 1660 if (pos != list)
1655 else 1661 pos[-1] = '\0';
1656 { 1662 else
1657 if (pos != list) 1663 pos[0] = '\0';
1658 pos[-1] = '\0'; 1664 }
1659 else 1665 GNUNET_CONFIGURATION_set_value_string(cfg, section, option, list);
1660 pos[0] = '\0'; 1666 GNUNET_free(list);
1661 } 1667 GNUNET_free(match);
1662 GNUNET_CONFIGURATION_set_value_string (cfg, section, option, list); 1668 return GNUNET_OK;
1663 GNUNET_free (list); 1669 }
1664 GNUNET_free (match); 1670 if (old == '\0')
1665 return GNUNET_OK; 1671 break;
1672 end[0] = old;
1673 pos = end + 1;
1666 } 1674 }
1667 if (old == '\0') 1675 GNUNET_free(list);
1668 break; 1676 GNUNET_free(match);
1669 end[0] = old;
1670 pos = end + 1;
1671 }
1672 GNUNET_free (list);
1673 GNUNET_free (match);
1674 return GNUNET_NO; 1677 return GNUNET_NO;
1675} 1678}
1676 1679
@@ -1685,21 +1688,21 @@ GNUNET_CONFIGURATION_remove_value_filename (
1685 * @return #GNUNET_OK on success 1688 * @return #GNUNET_OK on success
1686 */ 1689 */
1687static int 1690static int
1688parse_configuration_file (void *cls, const char *filename) 1691parse_configuration_file(void *cls, const char *filename)
1689{ 1692{
1690 struct GNUNET_CONFIGURATION_Handle *cfg = cls; 1693 struct GNUNET_CONFIGURATION_Handle *cfg = cls;
1691 char *ext; 1694 char *ext;
1692 int ret; 1695 int ret;
1693 1696
1694 /* Examine file extension */ 1697 /* Examine file extension */
1695 ext = strrchr (filename, '.'); 1698 ext = strrchr(filename, '.');
1696 if ((NULL == ext) || (0 != strcmp (ext, ".conf"))) 1699 if ((NULL == ext) || (0 != strcmp(ext, ".conf")))
1697 { 1700 {
1698 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, "Skipping file `%s'\n", filename); 1701 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, "Skipping file `%s'\n", filename);
1699 return GNUNET_OK; 1702 return GNUNET_OK;
1700 } 1703 }
1701 1704
1702 ret = GNUNET_CONFIGURATION_parse (cfg, filename); 1705 ret = GNUNET_CONFIGURATION_parse(cfg, filename);
1703 return ret; 1706 return ret;
1704} 1707}
1705 1708
@@ -1713,11 +1716,11 @@ parse_configuration_file (void *cls, const char *filename)
1713 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1716 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1714 */ 1717 */
1715int 1718int
1716GNUNET_CONFIGURATION_load_from (struct GNUNET_CONFIGURATION_Handle *cfg, 1719GNUNET_CONFIGURATION_load_from(struct GNUNET_CONFIGURATION_Handle *cfg,
1717 const char *defaults_d) 1720 const char *defaults_d)
1718{ 1721{
1719 if (GNUNET_SYSERR == 1722 if (GNUNET_SYSERR ==
1720 GNUNET_DISK_directory_scan (defaults_d, &parse_configuration_file, cfg)) 1723 GNUNET_DISK_directory_scan(defaults_d, &parse_configuration_file, cfg))
1721 return GNUNET_SYSERR; /* no configuration at all found */ 1724 return GNUNET_SYSERR; /* no configuration at all found */
1722 return GNUNET_OK; 1725 return GNUNET_OK;
1723} 1726}
diff --git a/src/util/configuration_loader.c b/src/util/configuration_loader.c
index 095e69474..ccf9a25b2 100644
--- a/src/util/configuration_loader.c
+++ b/src/util/configuration_loader.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/configuration_loader.c 22 * @file src/util/configuration_loader.c
@@ -27,7 +27,7 @@
27#include "platform.h" 27#include "platform.h"
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define LOG(kind,...) GNUNET_log_from (kind, "util-configuration", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-configuration", __VA_ARGS__)
31 31
32 32
33/** 33/**
@@ -39,48 +39,48 @@
39 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 39 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
40 */ 40 */
41int 41int
42GNUNET_CONFIGURATION_load (struct GNUNET_CONFIGURATION_Handle *cfg, 42GNUNET_CONFIGURATION_load(struct GNUNET_CONFIGURATION_Handle *cfg,
43 const char *filename) 43 const char *filename)
44{ 44{
45 char *baseconfig; 45 char *baseconfig;
46 const char *base_config_varname; 46 const char *base_config_varname;
47 47
48 base_config_varname = GNUNET_OS_project_data_get ()->base_config_varname; 48 base_config_varname = GNUNET_OS_project_data_get()->base_config_varname;
49 49
50 if (NULL != (baseconfig = getenv (base_config_varname))) 50 if (NULL != (baseconfig = getenv(base_config_varname)))
51 { 51 {
52 baseconfig = GNUNET_strdup (baseconfig); 52 baseconfig = GNUNET_strdup(baseconfig);
53 } 53 }
54 else 54 else
55 { 55 {
56 char *ipath; 56 char *ipath;
57 57
58 ipath = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_DATADIR); 58 ipath = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_DATADIR);
59 if (NULL == ipath) 59 if (NULL == ipath)
60 return GNUNET_SYSERR; 60 return GNUNET_SYSERR;
61 GNUNET_asprintf (&baseconfig, "%s%s", ipath, "config.d"); 61 GNUNET_asprintf(&baseconfig, "%s%s", ipath, "config.d");
62 GNUNET_free (ipath); 62 GNUNET_free(ipath);
63 } 63 }
64 64
65 if (GNUNET_SYSERR == 65 if (GNUNET_SYSERR ==
66 GNUNET_CONFIGURATION_load_from (cfg, 66 GNUNET_CONFIGURATION_load_from(cfg,
67 baseconfig)) 67 baseconfig))
68 { 68 {
69 GNUNET_free (baseconfig); 69 GNUNET_free(baseconfig);
70 return GNUNET_SYSERR; /* no configuration at all found */ 70 return GNUNET_SYSERR; /* no configuration at all found */
71 } 71 }
72 GNUNET_free (baseconfig); 72 GNUNET_free(baseconfig);
73 if ((NULL != filename) && 73 if ((NULL != filename) &&
74 (GNUNET_OK != GNUNET_CONFIGURATION_parse (cfg, filename))) 74 (GNUNET_OK != GNUNET_CONFIGURATION_parse(cfg, filename)))
75 { 75 {
76 /* specified configuration not found */ 76 /* specified configuration not found */
77 return GNUNET_SYSERR; 77 return GNUNET_SYSERR;
78 } 78 }
79 if (((GNUNET_YES != 79 if (((GNUNET_YES !=
80 GNUNET_CONFIGURATION_have_value (cfg, "PATHS", "DEFAULTCONFIG"))) && 80 GNUNET_CONFIGURATION_have_value(cfg, "PATHS", "DEFAULTCONFIG"))) &&
81 (filename != NULL)) 81 (filename != NULL))
82 GNUNET_CONFIGURATION_set_value_string (cfg, "PATHS", "DEFAULTCONFIG", 82 GNUNET_CONFIGURATION_set_value_string(cfg, "PATHS", "DEFAULTCONFIG",
83 filename); 83 filename);
84 return GNUNET_OK; 84 return GNUNET_OK;
85} 85}
86 86
diff --git a/src/util/container_bloomfilter.c b/src/util/container_bloomfilter.c
index a4033defe..1bc559ba3 100644
--- a/src/util/container_bloomfilter.c
+++ b/src/util/container_bloomfilter.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_bloomfilter.c 21 * @file util/container_bloomfilter.c
22 * @brief data structure used to reduce disk accesses. 22 * @brief data structure used to reduce disk accesses.
@@ -43,20 +43,18 @@
43#include "gnunet_util_lib.h" 43#include "gnunet_util_lib.h"
44 44
45#define LOG(kind, ...) \ 45#define LOG(kind, ...) \
46 GNUNET_log_from (kind, "util-container-bloomfilter", __VA_ARGS__) 46 GNUNET_log_from(kind, "util-container-bloomfilter", __VA_ARGS__)
47 47
48#define LOG_STRERROR(kind, syscall) \ 48#define LOG_STRERROR(kind, syscall) \
49 GNUNET_log_from_strerror (kind, "util-container-bloomfilter", syscall) 49 GNUNET_log_from_strerror(kind, "util-container-bloomfilter", syscall)
50 50
51#define LOG_STRERROR_FILE(kind, syscall, filename) \ 51#define LOG_STRERROR_FILE(kind, syscall, filename) \
52 GNUNET_log_from_strerror_file (kind, \ 52 GNUNET_log_from_strerror_file(kind, \
53 "util-container-bloomfilter", \ 53 "util-container-bloomfilter", \
54 syscall, \ 54 syscall, \
55 filename) 55 filename)
56
57struct GNUNET_CONTAINER_BloomFilter
58{
59 56
57struct GNUNET_CONTAINER_BloomFilter {
60 /** 58 /**
61 * The actual bloomfilter bit array 59 * The actual bloomfilter bit array
62 */ 60 */
@@ -91,7 +89,7 @@ struct GNUNET_CONTAINER_BloomFilter
91 * @return addresses set per element in the bf 89 * @return addresses set per element in the bf
92 */ 90 */
93size_t 91size_t
94GNUNET_CONTAINER_bloomfilter_get_element_addresses ( 92GNUNET_CONTAINER_bloomfilter_get_element_addresses(
95 const struct GNUNET_CONTAINER_BloomFilter *bf) 93 const struct GNUNET_CONTAINER_BloomFilter *bf)
96{ 94{
97 if (bf == NULL) 95 if (bf == NULL)
@@ -107,7 +105,7 @@ GNUNET_CONTAINER_bloomfilter_get_element_addresses (
107 * @return number of bytes used for the data of the bloom filter 105 * @return number of bytes used for the data of the bloom filter
108 */ 106 */
109size_t 107size_t
110GNUNET_CONTAINER_bloomfilter_get_size ( 108GNUNET_CONTAINER_bloomfilter_get_size(
111 const struct GNUNET_CONTAINER_BloomFilter *bf) 109 const struct GNUNET_CONTAINER_BloomFilter *bf)
112{ 110{
113 if (bf == NULL) 111 if (bf == NULL)
@@ -123,12 +121,12 @@ GNUNET_CONTAINER_bloomfilter_get_size (
123 * @return copy of the bf 121 * @return copy of the bf
124 */ 122 */
125struct GNUNET_CONTAINER_BloomFilter * 123struct GNUNET_CONTAINER_BloomFilter *
126GNUNET_CONTAINER_bloomfilter_copy ( 124GNUNET_CONTAINER_bloomfilter_copy(
127 const struct GNUNET_CONTAINER_BloomFilter *bf) 125 const struct GNUNET_CONTAINER_BloomFilter *bf)
128{ 126{
129 return GNUNET_CONTAINER_bloomfilter_init (bf->bitArray, 127 return GNUNET_CONTAINER_bloomfilter_init(bf->bitArray,
130 bf->bitArraySize, 128 bf->bitArraySize,
131 bf->addressesPerElement); 129 bf->addressesPerElement);
132} 130}
133 131
134 132
@@ -140,7 +138,7 @@ GNUNET_CONTAINER_bloomfilter_copy (
140 * @param bitIdx which bit to set 138 * @param bitIdx which bit to set
141 */ 139 */
142static void 140static void
143setBit (char *bitArray, unsigned int bitIdx) 141setBit(char *bitArray, unsigned int bitIdx)
144{ 142{
145 size_t arraySlot; 143 size_t arraySlot;
146 unsigned int targetBit; 144 unsigned int targetBit;
@@ -158,7 +156,7 @@ setBit (char *bitArray, unsigned int bitIdx)
158 * @param bitIdx which bit to unset 156 * @param bitIdx which bit to unset
159 */ 157 */
160static void 158static void
161clearBit (char *bitArray, unsigned int bitIdx) 159clearBit(char *bitArray, unsigned int bitIdx)
162{ 160{
163 size_t slot; 161 size_t slot;
164 unsigned int targetBit; 162 unsigned int targetBit;
@@ -176,7 +174,7 @@ clearBit (char *bitArray, unsigned int bitIdx)
176 * @return GNUNET_YES if the bit is set, GNUNET_NO if not. 174 * @return GNUNET_YES if the bit is set, GNUNET_NO if not.
177 */ 175 */
178static int 176static int
179testBit (char *bitArray, unsigned int bitIdx) 177testBit(char *bitArray, unsigned int bitIdx)
180{ 178{
181 size_t slot; 179 size_t slot;
182 unsigned int targetBit; 180 unsigned int targetBit;
@@ -199,9 +197,9 @@ testBit (char *bitArray, unsigned int bitIdx)
199 * @param fh A file to keep the 4 bit address usage counters in 197 * @param fh A file to keep the 4 bit address usage counters in
200 */ 198 */
201static void 199static void
202incrementBit (char *bitArray, 200incrementBit(char *bitArray,
203 unsigned int bitIdx, 201 unsigned int bitIdx,
204 const struct GNUNET_DISK_FileHandle *fh) 202 const struct GNUNET_DISK_FileHandle *fh)
205{ 203{
206 off_t fileSlot; 204 off_t fileSlot;
207 unsigned char value; 205 unsigned char value;
@@ -209,34 +207,34 @@ incrementBit (char *bitArray,
209 unsigned int low; 207 unsigned int low;
210 unsigned int targetLoc; 208 unsigned int targetLoc;
211 209
212 setBit (bitArray, bitIdx); 210 setBit(bitArray, bitIdx);
213 if (GNUNET_DISK_handle_invalid (fh)) 211 if (GNUNET_DISK_handle_invalid(fh))
214 return; 212 return;
215 /* Update the counter file on disk */ 213 /* Update the counter file on disk */
216 fileSlot = bitIdx / 2; 214 fileSlot = bitIdx / 2;
217 targetLoc = bitIdx % 2; 215 targetLoc = bitIdx % 2;
218 216
219 GNUNET_assert (fileSlot == 217 GNUNET_assert(fileSlot ==
220 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET)); 218 GNUNET_DISK_file_seek(fh, fileSlot, GNUNET_DISK_SEEK_SET));
221 if (1 != GNUNET_DISK_file_read (fh, &value, 1)) 219 if (1 != GNUNET_DISK_file_read(fh, &value, 1))
222 value = 0; 220 value = 0;
223 low = value & 0xF; 221 low = value & 0xF;
224 high = (value & (~0xF)) >> 4; 222 high = (value & (~0xF)) >> 4;
225 223
226 if (targetLoc == 0) 224 if (targetLoc == 0)
227 { 225 {
228 if (low < 0xF) 226 if (low < 0xF)
229 low++; 227 low++;
230 } 228 }
231 else 229 else
232 { 230 {
233 if (high < 0xF) 231 if (high < 0xF)
234 high++; 232 high++;
235 } 233 }
236 value = ((high << 4) | low); 234 value = ((high << 4) | low);
237 GNUNET_assert (fileSlot == 235 GNUNET_assert(fileSlot ==
238 GNUNET_DISK_file_seek (fh, fileSlot, GNUNET_DISK_SEEK_SET)); 236 GNUNET_DISK_file_seek(fh, fileSlot, GNUNET_DISK_SEEK_SET));
239 GNUNET_assert (1 == GNUNET_DISK_file_write (fh, &value, 1)); 237 GNUNET_assert(1 == GNUNET_DISK_file_write(fh, &value, 1));
240} 238}
241 239
242/** 240/**
@@ -248,9 +246,9 @@ incrementBit (char *bitArray,
248 * @param fh A file to keep the 4bit address usage counters in 246 * @param fh A file to keep the 4bit address usage counters in
249 */ 247 */
250static void 248static void
251decrementBit (char *bitArray, 249decrementBit(char *bitArray,
252 unsigned int bitIdx, 250 unsigned int bitIdx,
253 const struct GNUNET_DISK_FileHandle *fh) 251 const struct GNUNET_DISK_FileHandle *fh)
254{ 252{
255 off_t fileslot; 253 off_t fileslot;
256 unsigned char value; 254 unsigned char value;
@@ -258,49 +256,49 @@ decrementBit (char *bitArray,
258 unsigned int low; 256 unsigned int low;
259 unsigned int targetLoc; 257 unsigned int targetLoc;
260 258
261 if (GNUNET_DISK_handle_invalid (fh)) 259 if (GNUNET_DISK_handle_invalid(fh))
262 return; /* cannot decrement! */ 260 return; /* cannot decrement! */
263 /* Each char slot in the counter file holds two 4 bit counters */ 261 /* Each char slot in the counter file holds two 4 bit counters */
264 fileslot = bitIdx / 2; 262 fileslot = bitIdx / 2;
265 targetLoc = bitIdx % 2; 263 targetLoc = bitIdx % 2;
266 if (GNUNET_SYSERR == 264 if (GNUNET_SYSERR ==
267 GNUNET_DISK_file_seek (fh, fileslot, GNUNET_DISK_SEEK_SET)) 265 GNUNET_DISK_file_seek(fh, fileslot, GNUNET_DISK_SEEK_SET))
268 { 266 {
269 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "seek"); 267 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "seek");
270 return; 268 return;
271 } 269 }
272 if (1 != GNUNET_DISK_file_read (fh, &value, 1)) 270 if (1 != GNUNET_DISK_file_read(fh, &value, 1))
273 value = 0; 271 value = 0;
274 low = value & 0xF; 272 low = value & 0xF;
275 high = (value & 0xF0) >> 4; 273 high = (value & 0xF0) >> 4;
276 274
277 /* decrement, but once we have reached the max, never go back! */ 275 /* decrement, but once we have reached the max, never go back! */
278 if (targetLoc == 0) 276 if (targetLoc == 0)
279 {
280 if ((low > 0) && (low < 0xF))
281 low--;
282 if (low == 0)
283 { 277 {
284 clearBit (bitArray, bitIdx); 278 if ((low > 0) && (low < 0xF))
279 low--;
280 if (low == 0)
281 {
282 clearBit(bitArray, bitIdx);
283 }
285 } 284 }
286 }
287 else 285 else
288 {
289 if ((high > 0) && (high < 0xF))
290 high--;
291 if (high == 0)
292 { 286 {
293 clearBit (bitArray, bitIdx); 287 if ((high > 0) && (high < 0xF))
288 high--;
289 if (high == 0)
290 {
291 clearBit(bitArray, bitIdx);
292 }
294 } 293 }
295 }
296 value = ((high << 4) | low); 294 value = ((high << 4) | low);
297 if (GNUNET_SYSERR == 295 if (GNUNET_SYSERR ==
298 GNUNET_DISK_file_seek (fh, fileslot, GNUNET_DISK_SEEK_SET)) 296 GNUNET_DISK_file_seek(fh, fileslot, GNUNET_DISK_SEEK_SET))
299 { 297 {
300 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "seek"); 298 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "seek");
301 return; 299 return;
302 } 300 }
303 GNUNET_assert (1 == GNUNET_DISK_file_write (fh, &value, 1)); 301 GNUNET_assert(1 == GNUNET_DISK_file_write(fh, &value, 1));
304} 302}
305 303
306#define BUFFSIZE 65536 304#define BUFFSIZE 65536
@@ -313,33 +311,33 @@ decrementBit (char *bitArray,
313 * @return GNUNET_OK if created ok, GNUNET_SYSERR otherwise 311 * @return GNUNET_OK if created ok, GNUNET_SYSERR otherwise
314 */ 312 */
315static int 313static int
316make_empty_file (const struct GNUNET_DISK_FileHandle *fh, size_t size) 314make_empty_file(const struct GNUNET_DISK_FileHandle *fh, size_t size)
317{ 315{
318 char buffer[BUFFSIZE]; 316 char buffer[BUFFSIZE];
319 size_t bytesleft = size; 317 size_t bytesleft = size;
320 int res = 0; 318 int res = 0;
321 319
322 if (GNUNET_DISK_handle_invalid (fh)) 320 if (GNUNET_DISK_handle_invalid(fh))
323 return GNUNET_SYSERR; 321 return GNUNET_SYSERR;
324 memset (buffer, 0, sizeof (buffer)); 322 memset(buffer, 0, sizeof(buffer));
325 GNUNET_DISK_file_seek (fh, 0, GNUNET_DISK_SEEK_SET); 323 GNUNET_DISK_file_seek(fh, 0, GNUNET_DISK_SEEK_SET);
326 while (bytesleft > 0) 324 while (bytesleft > 0)
327 {
328 if (bytesleft > sizeof (buffer))
329 {
330 res = GNUNET_DISK_file_write (fh, buffer, sizeof (buffer));
331 if (res >= 0)
332 bytesleft -= res;
333 }
334 else
335 { 325 {
336 res = GNUNET_DISK_file_write (fh, buffer, bytesleft); 326 if (bytesleft > sizeof(buffer))
337 if (res >= 0) 327 {
338 bytesleft -= res; 328 res = GNUNET_DISK_file_write(fh, buffer, sizeof(buffer));
329 if (res >= 0)
330 bytesleft -= res;
331 }
332 else
333 {
334 res = GNUNET_DISK_file_write(fh, buffer, bytesleft);
335 if (res >= 0)
336 bytesleft -= res;
337 }
338 if (GNUNET_SYSERR == res)
339 return GNUNET_SYSERR;
339 } 340 }
340 if (GNUNET_SYSERR == res)
341 return GNUNET_SYSERR;
342 }
343 return GNUNET_OK; 341 return GNUNET_OK;
344} 342}
345 343
@@ -370,10 +368,10 @@ typedef int (*BitIterator) (void *cls,
370 * @param key the key for which we iterate over the BF bits 368 * @param key the key for which we iterate over the BF bits
371 */ 369 */
372static void 370static void
373iterateBits (const struct GNUNET_CONTAINER_BloomFilter *bf, 371iterateBits(const struct GNUNET_CONTAINER_BloomFilter *bf,
374 BitIterator callback, 372 BitIterator callback,
375 void *arg, 373 void *arg,
376 const struct GNUNET_HashCode *key) 374 const struct GNUNET_HashCode *key)
377{ 375{
378 struct GNUNET_HashCode tmp[2]; 376 struct GNUNET_HashCode tmp[2];
379 int bitCount; 377 int bitCount;
@@ -383,32 +381,32 @@ iterateBits (const struct GNUNET_CONTAINER_BloomFilter *bf,
383 bitCount = bf->addressesPerElement; 381 bitCount = bf->addressesPerElement;
384 tmp[0] = *key; 382 tmp[0] = *key;
385 round = 0; 383 round = 0;
386 GNUNET_assert (bf->bitArraySize > 0); 384 GNUNET_assert(bf->bitArraySize > 0);
387 GNUNET_assert (bf->bitArraySize * 8LL > bf->bitArraySize); 385 GNUNET_assert(bf->bitArraySize * 8LL > bf->bitArraySize);
388 while (bitCount > 0) 386 while (bitCount > 0)
389 {
390 while (slot < (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)))
391 {
392 if (GNUNET_YES !=
393 callback (arg,
394 bf,
395 ntohl ((((uint32_t *) &tmp[round & 1])[slot])) %
396 ((bf->bitArraySize * 8LL))))
397 return;
398 slot++;
399 bitCount--;
400 if (bitCount == 0)
401 break;
402 }
403 if (bitCount > 0)
404 { 387 {
405 GNUNET_CRYPTO_hash (&tmp[round & 1], 388 while (slot < (sizeof(struct GNUNET_HashCode) / sizeof(uint32_t)))
406 sizeof (struct GNUNET_HashCode), 389 {
407 &tmp[(round + 1) & 1]); 390 if (GNUNET_YES !=
408 round++; 391 callback(arg,
409 slot = 0; 392 bf,
393 ntohl((((uint32_t *)&tmp[round & 1])[slot])) %
394 ((bf->bitArraySize * 8LL))))
395 return;
396 slot++;
397 bitCount--;
398 if (bitCount == 0)
399 break;
400 }
401 if (bitCount > 0)
402 {
403 GNUNET_CRYPTO_hash(&tmp[round & 1],
404 sizeof(struct GNUNET_HashCode),
405 &tmp[(round + 1) & 1]);
406 round++;
407 slot = 0;
408 }
410 } 409 }
411 }
412} 410}
413 411
414 412
@@ -421,13 +419,13 @@ iterateBits (const struct GNUNET_CONTAINER_BloomFilter *bf,
421 * @return GNUNET_YES 419 * @return GNUNET_YES
422 */ 420 */
423static int 421static int
424incrementBitCallback (void *cls, 422incrementBitCallback(void *cls,
425 const struct GNUNET_CONTAINER_BloomFilter *bf, 423 const struct GNUNET_CONTAINER_BloomFilter *bf,
426 unsigned int bit) 424 unsigned int bit)
427{ 425{
428 struct GNUNET_CONTAINER_BloomFilter *b = cls; 426 struct GNUNET_CONTAINER_BloomFilter *b = cls;
429 427
430 incrementBit (b->bitArray, bit, bf->fh); 428 incrementBit(b->bitArray, bit, bf->fh);
431 return GNUNET_YES; 429 return GNUNET_YES;
432} 430}
433 431
@@ -441,13 +439,13 @@ incrementBitCallback (void *cls,
441 * @return GNUNET_YES 439 * @return GNUNET_YES
442 */ 440 */
443static int 441static int
444decrementBitCallback (void *cls, 442decrementBitCallback(void *cls,
445 const struct GNUNET_CONTAINER_BloomFilter *bf, 443 const struct GNUNET_CONTAINER_BloomFilter *bf,
446 unsigned int bit) 444 unsigned int bit)
447{ 445{
448 struct GNUNET_CONTAINER_BloomFilter *b = cls; 446 struct GNUNET_CONTAINER_BloomFilter *b = cls;
449 447
450 decrementBit (b->bitArray, bit, bf->fh); 448 decrementBit(b->bitArray, bit, bf->fh);
451 return GNUNET_YES; 449 return GNUNET_YES;
452} 450}
453 451
@@ -461,17 +459,17 @@ decrementBitCallback (void *cls,
461 * @return YES if the bit is set, NO if not 459 * @return YES if the bit is set, NO if not
462 */ 460 */
463static int 461static int
464testBitCallback (void *cls, 462testBitCallback(void *cls,
465 const struct GNUNET_CONTAINER_BloomFilter *bf, 463 const struct GNUNET_CONTAINER_BloomFilter *bf,
466 unsigned int bit) 464 unsigned int bit)
467{ 465{
468 int *arg = cls; 466 int *arg = cls;
469 467
470 if (GNUNET_NO == testBit (bf->bitArray, bit)) 468 if (GNUNET_NO == testBit(bf->bitArray, bit))
471 { 469 {
472 *arg = GNUNET_NO; 470 *arg = GNUNET_NO;
473 return GNUNET_NO; 471 return GNUNET_NO;
474 } 472 }
475 return GNUNET_YES; 473 return GNUNET_YES;
476} 474}
477 475
@@ -489,9 +487,9 @@ testBitCallback (void *cls,
489 * @return the bloomfilter 487 * @return the bloomfilter
490 */ 488 */
491struct GNUNET_CONTAINER_BloomFilter * 489struct GNUNET_CONTAINER_BloomFilter *
492GNUNET_CONTAINER_bloomfilter_load (const char *filename, 490GNUNET_CONTAINER_bloomfilter_load(const char *filename,
493 size_t size, 491 size_t size,
494 unsigned int k) 492 unsigned int k)
495{ 493{
496 struct GNUNET_CONTAINER_BloomFilter *bf; 494 struct GNUNET_CONTAINER_BloomFilter *bf;
497 char *rbuff; 495 char *rbuff;
@@ -501,7 +499,7 @@ GNUNET_CONTAINER_bloomfilter_load (const char *filename,
501 off_t fsize; 499 off_t fsize;
502 int must_read; 500 int must_read;
503 501
504 GNUNET_assert (NULL != filename); 502 GNUNET_assert(NULL != filename);
505 if ((k == 0) || (size == 0)) 503 if ((k == 0) || (size == 0))
506 return NULL; 504 return NULL;
507 if (size < BUFFSIZE) 505 if (size < BUFFSIZE)
@@ -511,115 +509,115 @@ GNUNET_CONTAINER_bloomfilter_load (const char *filename,
511 ui *= 2; 509 ui *= 2;
512 size = ui; /* make sure it's a power of 2 */ 510 size = ui; /* make sure it's a power of 2 */
513 511
514 bf = GNUNET_new (struct GNUNET_CONTAINER_BloomFilter); 512 bf = GNUNET_new(struct GNUNET_CONTAINER_BloomFilter);
515 /* Try to open a bloomfilter file */ 513 /* Try to open a bloomfilter file */
516 if (GNUNET_YES == GNUNET_DISK_file_test (filename)) 514 if (GNUNET_YES == GNUNET_DISK_file_test(filename))
517 bf->fh = GNUNET_DISK_file_open (filename, 515 bf->fh = GNUNET_DISK_file_open(filename,
518 GNUNET_DISK_OPEN_READWRITE, 516 GNUNET_DISK_OPEN_READWRITE,
519 GNUNET_DISK_PERM_USER_READ | 517 GNUNET_DISK_PERM_USER_READ |
520 GNUNET_DISK_PERM_USER_WRITE); 518 GNUNET_DISK_PERM_USER_WRITE);
521 if (NULL != bf->fh) 519 if (NULL != bf->fh)
522 {
523 /* file existed, try to read it! */
524 must_read = GNUNET_YES;
525 if (GNUNET_OK != GNUNET_DISK_file_handle_size (bf->fh, &fsize))
526 {
527 GNUNET_DISK_file_close (bf->fh);
528 GNUNET_free (bf);
529 return NULL;
530 }
531 if (0 == fsize)
532 {
533 /* found existing empty file, just overwrite */
534 if (GNUNET_OK != make_empty_file (bf->fh, size * 4LL))
535 {
536 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write");
537 GNUNET_DISK_file_close (bf->fh);
538 GNUNET_free (bf);
539 return NULL;
540 }
541 }
542 else if (fsize != ((off_t) size) * 4LL)
543 { 520 {
544 GNUNET_log ( 521 /* file existed, try to read it! */
545 GNUNET_ERROR_TYPE_ERROR, 522 must_read = GNUNET_YES;
546 _ ( 523 if (GNUNET_OK != GNUNET_DISK_file_handle_size(bf->fh, &fsize))
547 "Size of file on disk is incorrect for this Bloom filter (want %llu, have %llu)\n"), 524 {
548 (unsigned long long) (size * 4LL), 525 GNUNET_DISK_file_close(bf->fh);
549 (unsigned long long) fsize); 526 GNUNET_free(bf);
550 GNUNET_DISK_file_close (bf->fh); 527 return NULL;
551 GNUNET_free (bf); 528 }
552 return NULL; 529 if (0 == fsize)
530 {
531 /* found existing empty file, just overwrite */
532 if (GNUNET_OK != make_empty_file(bf->fh, size * 4LL))
533 {
534 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "write");
535 GNUNET_DISK_file_close(bf->fh);
536 GNUNET_free(bf);
537 return NULL;
538 }
539 }
540 else if (fsize != ((off_t)size) * 4LL)
541 {
542 GNUNET_log(
543 GNUNET_ERROR_TYPE_ERROR,
544 _(
545 "Size of file on disk is incorrect for this Bloom filter (want %llu, have %llu)\n"),
546 (unsigned long long)(size * 4LL),
547 (unsigned long long)fsize);
548 GNUNET_DISK_file_close(bf->fh);
549 GNUNET_free(bf);
550 return NULL;
551 }
553 } 552 }
554 }
555 else 553 else
556 {
557 /* file did not exist, don't read, just create */
558 must_read = GNUNET_NO;
559 bf->fh = GNUNET_DISK_file_open (filename,
560 GNUNET_DISK_OPEN_CREATE |
561 GNUNET_DISK_OPEN_READWRITE,
562 GNUNET_DISK_PERM_USER_READ |
563 GNUNET_DISK_PERM_USER_WRITE);
564 if (NULL == bf->fh)
565 { 554 {
566 GNUNET_free (bf); 555 /* file did not exist, don't read, just create */
567 return NULL; 556 must_read = GNUNET_NO;
557 bf->fh = GNUNET_DISK_file_open(filename,
558 GNUNET_DISK_OPEN_CREATE |
559 GNUNET_DISK_OPEN_READWRITE,
560 GNUNET_DISK_PERM_USER_READ |
561 GNUNET_DISK_PERM_USER_WRITE);
562 if (NULL == bf->fh)
563 {
564 GNUNET_free(bf);
565 return NULL;
566 }
567 if (GNUNET_OK != make_empty_file(bf->fh, size * 4LL))
568 {
569 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "write");
570 GNUNET_DISK_file_close(bf->fh);
571 GNUNET_free(bf);
572 return NULL;
573 }
568 } 574 }
569 if (GNUNET_OK != make_empty_file (bf->fh, size * 4LL)) 575 bf->filename = GNUNET_strdup(filename);
576 /* Alloc block */
577 bf->bitArray = GNUNET_malloc_large(size);
578 if (NULL == bf->bitArray)
570 { 579 {
571 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "write"); 580 if (NULL != bf->fh)
572 GNUNET_DISK_file_close (bf->fh); 581 GNUNET_DISK_file_close(bf->fh);
573 GNUNET_free (bf); 582 GNUNET_free(bf->filename);
583 GNUNET_free(bf);
574 return NULL; 584 return NULL;
575 } 585 }
576 }
577 bf->filename = GNUNET_strdup (filename);
578 /* Alloc block */
579 bf->bitArray = GNUNET_malloc_large (size);
580 if (NULL == bf->bitArray)
581 {
582 if (NULL != bf->fh)
583 GNUNET_DISK_file_close (bf->fh);
584 GNUNET_free (bf->filename);
585 GNUNET_free (bf);
586 return NULL;
587 }
588 bf->bitArraySize = size; 586 bf->bitArraySize = size;
589 bf->addressesPerElement = k; 587 bf->addressesPerElement = k;
590 if (GNUNET_YES != must_read) 588 if (GNUNET_YES != must_read)
591 return bf; /* already done! */ 589 return bf; /* already done! */
592 /* Read from the file what bits we can */ 590 /* Read from the file what bits we can */
593 rbuff = GNUNET_malloc (BUFFSIZE); 591 rbuff = GNUNET_malloc(BUFFSIZE);
594 pos = 0; 592 pos = 0;
595 while (pos < ((off_t) size) * 8LL) 593 while (pos < ((off_t)size) * 8LL)
596 {
597 int res;
598
599 res = GNUNET_DISK_file_read (bf->fh, rbuff, BUFFSIZE);
600 if (res == -1)
601 { 594 {
602 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "read", bf->filename); 595 int res;
603 GNUNET_free (rbuff); 596
604 GNUNET_free (bf->filename); 597 res = GNUNET_DISK_file_read(bf->fh, rbuff, BUFFSIZE);
605 GNUNET_DISK_file_close (bf->fh); 598 if (res == -1)
606 GNUNET_free (bf); 599 {
607 return NULL; 600 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "read", bf->filename);
608 } 601 GNUNET_free(rbuff);
609 if (res == 0) 602 GNUNET_free(bf->filename);
610 break; /* is ok! we just did not use that many bits yet */ 603 GNUNET_DISK_file_close(bf->fh);
611 for (i = 0; i < res; i++) 604 GNUNET_free(bf);
612 { 605 return NULL;
613 if ((rbuff[i] & 0x0F) != 0) 606 }
614 setBit (bf->bitArray, pos + i * 2); 607 if (res == 0)
615 if ((rbuff[i] & 0xF0) != 0) 608 break; /* is ok! we just did not use that many bits yet */
616 setBit (bf->bitArray, pos + i * 2 + 1); 609 for (i = 0; i < res; i++)
610 {
611 if ((rbuff[i] & 0x0F) != 0)
612 setBit(bf->bitArray, pos + i * 2);
613 if ((rbuff[i] & 0xF0) != 0)
614 setBit(bf->bitArray, pos + i * 2 + 1);
615 }
616 if (res < BUFFSIZE)
617 break;
618 pos += BUFFSIZE * 2; /* 2 bits per byte in the buffer */
617 } 619 }
618 if (res < BUFFSIZE) 620 GNUNET_free(rbuff);
619 break;
620 pos += BUFFSIZE * 2; /* 2 bits per byte in the buffer */
621 }
622 GNUNET_free (rbuff);
623 return bf; 621 return bf;
624} 622}
625 623
@@ -638,27 +636,27 @@ GNUNET_CONTAINER_bloomfilter_load (const char *filename,
638 * @return the bloomfilter 636 * @return the bloomfilter
639 */ 637 */
640struct GNUNET_CONTAINER_BloomFilter * 638struct GNUNET_CONTAINER_BloomFilter *
641GNUNET_CONTAINER_bloomfilter_init (const char *data, 639GNUNET_CONTAINER_bloomfilter_init(const char *data,
642 size_t size, 640 size_t size,
643 unsigned int k) 641 unsigned int k)
644{ 642{
645 struct GNUNET_CONTAINER_BloomFilter *bf; 643 struct GNUNET_CONTAINER_BloomFilter *bf;
646 644
647 if ((0 == k) || (0 == size)) 645 if ((0 == k) || (0 == size))
648 return NULL; 646 return NULL;
649 bf = GNUNET_new (struct GNUNET_CONTAINER_BloomFilter); 647 bf = GNUNET_new(struct GNUNET_CONTAINER_BloomFilter);
650 bf->filename = NULL; 648 bf->filename = NULL;
651 bf->fh = NULL; 649 bf->fh = NULL;
652 bf->bitArray = GNUNET_malloc_large (size); 650 bf->bitArray = GNUNET_malloc_large(size);
653 if (NULL == bf->bitArray) 651 if (NULL == bf->bitArray)
654 { 652 {
655 GNUNET_free (bf); 653 GNUNET_free(bf);
656 return NULL; 654 return NULL;
657 } 655 }
658 bf->bitArraySize = size; 656 bf->bitArraySize = size;
659 bf->addressesPerElement = k; 657 bf->addressesPerElement = k;
660 if (NULL != data) 658 if (NULL != data)
661 GNUNET_memcpy (bf->bitArray, data, size); 659 GNUNET_memcpy(bf->bitArray, data, size);
662 return bf; 660 return bf;
663} 661}
664 662
@@ -673,7 +671,7 @@ GNUNET_CONTAINER_bloomfilter_init (const char *data,
673 * @return #GNUNET_SYSERR if the data array is not big enough 671 * @return #GNUNET_SYSERR if the data array is not big enough
674 */ 672 */
675int 673int
676GNUNET_CONTAINER_bloomfilter_get_raw_data ( 674GNUNET_CONTAINER_bloomfilter_get_raw_data(
677 const struct GNUNET_CONTAINER_BloomFilter *bf, 675 const struct GNUNET_CONTAINER_BloomFilter *bf,
678 char *data, 676 char *data,
679 size_t size) 677 size_t size)
@@ -682,7 +680,7 @@ GNUNET_CONTAINER_bloomfilter_get_raw_data (
682 return GNUNET_SYSERR; 680 return GNUNET_SYSERR;
683 if (bf->bitArraySize != size) 681 if (bf->bitArraySize != size)
684 return GNUNET_SYSERR; 682 return GNUNET_SYSERR;
685 GNUNET_memcpy (data, bf->bitArray, size); 683 GNUNET_memcpy(data, bf->bitArray, size);
686 return GNUNET_OK; 684 return GNUNET_OK;
687} 685}
688 686
@@ -695,15 +693,15 @@ GNUNET_CONTAINER_bloomfilter_get_raw_data (
695 * @param bf the filter 693 * @param bf the filter
696 */ 694 */
697void 695void
698GNUNET_CONTAINER_bloomfilter_free (struct GNUNET_CONTAINER_BloomFilter *bf) 696GNUNET_CONTAINER_bloomfilter_free(struct GNUNET_CONTAINER_BloomFilter *bf)
699{ 697{
700 if (NULL == bf) 698 if (NULL == bf)
701 return; 699 return;
702 if (bf->fh != NULL) 700 if (bf->fh != NULL)
703 GNUNET_DISK_file_close (bf->fh); 701 GNUNET_DISK_file_close(bf->fh);
704 GNUNET_free_non_null (bf->filename); 702 GNUNET_free_non_null(bf->filename);
705 GNUNET_free (bf->bitArray); 703 GNUNET_free(bf->bitArray);
706 GNUNET_free (bf); 704 GNUNET_free(bf);
707} 705}
708 706
709 707
@@ -713,14 +711,14 @@ GNUNET_CONTAINER_bloomfilter_free (struct GNUNET_CONTAINER_BloomFilter *bf)
713 * @param bf the filter 711 * @param bf the filter
714 */ 712 */
715void 713void
716GNUNET_CONTAINER_bloomfilter_clear (struct GNUNET_CONTAINER_BloomFilter *bf) 714GNUNET_CONTAINER_bloomfilter_clear(struct GNUNET_CONTAINER_BloomFilter *bf)
717{ 715{
718 if (NULL == bf) 716 if (NULL == bf)
719 return; 717 return;
720 718
721 memset (bf->bitArray, 0, bf->bitArraySize); 719 memset(bf->bitArray, 0, bf->bitArraySize);
722 if (bf->filename != NULL) 720 if (bf->filename != NULL)
723 make_empty_file (bf->fh, bf->bitArraySize * 4LL); 721 make_empty_file(bf->fh, bf->bitArraySize * 4LL);
724} 722}
725 723
726 724
@@ -732,7 +730,7 @@ GNUNET_CONTAINER_bloomfilter_clear (struct GNUNET_CONTAINER_BloomFilter *bf)
732 * @return #GNUNET_YES if the element is in the filter, #GNUNET_NO if not 730 * @return #GNUNET_YES if the element is in the filter, #GNUNET_NO if not
733 */ 731 */
734int 732int
735GNUNET_CONTAINER_bloomfilter_test ( 733GNUNET_CONTAINER_bloomfilter_test(
736 const struct GNUNET_CONTAINER_BloomFilter *bf, 734 const struct GNUNET_CONTAINER_BloomFilter *bf,
737 const struct GNUNET_HashCode *e) 735 const struct GNUNET_HashCode *e)
738{ 736{
@@ -741,7 +739,7 @@ GNUNET_CONTAINER_bloomfilter_test (
741 if (NULL == bf) 739 if (NULL == bf)
742 return GNUNET_YES; 740 return GNUNET_YES;
743 res = GNUNET_YES; 741 res = GNUNET_YES;
744 iterateBits (bf, &testBitCallback, &res, e); 742 iterateBits(bf, &testBitCallback, &res, e);
745 return res; 743 return res;
746} 744}
747 745
@@ -753,12 +751,12 @@ GNUNET_CONTAINER_bloomfilter_test (
753 * @param e the element 751 * @param e the element
754 */ 752 */
755void 753void
756GNUNET_CONTAINER_bloomfilter_add (struct GNUNET_CONTAINER_BloomFilter *bf, 754GNUNET_CONTAINER_bloomfilter_add(struct GNUNET_CONTAINER_BloomFilter *bf,
757 const struct GNUNET_HashCode *e) 755 const struct GNUNET_HashCode *e)
758{ 756{
759 if (NULL == bf) 757 if (NULL == bf)
760 return; 758 return;
761 iterateBits (bf, &incrementBitCallback, bf, e); 759 iterateBits(bf, &incrementBitCallback, bf, e);
762} 760}
763 761
764 762
@@ -773,9 +771,9 @@ GNUNET_CONTAINER_bloomfilter_add (struct GNUNET_CONTAINER_BloomFilter *bf,
773 * @param size number of bytes in data 771 * @param size number of bytes in data
774 */ 772 */
775int 773int
776GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf, 774GNUNET_CONTAINER_bloomfilter_or(struct GNUNET_CONTAINER_BloomFilter *bf,
777 const char *data, 775 const char *data,
778 size_t size) 776 size_t size)
779{ 777{
780 unsigned int i; 778 unsigned int i;
781 unsigned int n; 779 unsigned int n;
@@ -786,13 +784,13 @@ GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf,
786 return GNUNET_YES; 784 return GNUNET_YES;
787 if (bf->bitArraySize != size) 785 if (bf->bitArraySize != size)
788 return GNUNET_SYSERR; 786 return GNUNET_SYSERR;
789 fc = (unsigned long long *) bf->bitArray; 787 fc = (unsigned long long *)bf->bitArray;
790 dc = (const unsigned long long *) data; 788 dc = (const unsigned long long *)data;
791 n = size / sizeof (unsigned long long); 789 n = size / sizeof(unsigned long long);
792 790
793 for (i = 0; i < n; i++) 791 for (i = 0; i < n; i++)
794 fc[i] |= dc[i]; 792 fc[i] |= dc[i];
795 for (i = n * sizeof (unsigned long long); i < size; i++) 793 for (i = n * sizeof(unsigned long long); i < size; i++)
796 bf->bitArray[i] |= data[i]; 794 bf->bitArray[i] |= data[i];
797 return GNUNET_OK; 795 return GNUNET_OK;
798} 796}
@@ -808,7 +806,7 @@ GNUNET_CONTAINER_bloomfilter_or (struct GNUNET_CONTAINER_BloomFilter *bf,
808 * @return #GNUNET_OK on success 806 * @return #GNUNET_OK on success
809 */ 807 */
810int 808int
811GNUNET_CONTAINER_bloomfilter_or2 ( 809GNUNET_CONTAINER_bloomfilter_or2(
812 struct GNUNET_CONTAINER_BloomFilter *bf, 810 struct GNUNET_CONTAINER_BloomFilter *bf,
813 const struct GNUNET_CONTAINER_BloomFilter *to_or) 811 const struct GNUNET_CONTAINER_BloomFilter *to_or)
814{ 812{
@@ -821,18 +819,18 @@ GNUNET_CONTAINER_bloomfilter_or2 (
821 if (NULL == bf) 819 if (NULL == bf)
822 return GNUNET_OK; 820 return GNUNET_OK;
823 if (bf->bitArraySize != to_or->bitArraySize) 821 if (bf->bitArraySize != to_or->bitArraySize)
824 { 822 {
825 GNUNET_break (0); 823 GNUNET_break(0);
826 return GNUNET_SYSERR; 824 return GNUNET_SYSERR;
827 } 825 }
828 size = bf->bitArraySize; 826 size = bf->bitArraySize;
829 fc = (unsigned long long *) bf->bitArray; 827 fc = (unsigned long long *)bf->bitArray;
830 dc = (const unsigned long long *) to_or->bitArray; 828 dc = (const unsigned long long *)to_or->bitArray;
831 n = size / sizeof (unsigned long long); 829 n = size / sizeof(unsigned long long);
832 830
833 for (i = 0; i < n; i++) 831 for (i = 0; i < n; i++)
834 fc[i] |= dc[i]; 832 fc[i] |= dc[i];
835 for (i = n * sizeof (unsigned long long); i < size; i++) 833 for (i = n * sizeof(unsigned long long); i < size; i++)
836 bf->bitArray[i] |= to_or->bitArray[i]; 834 bf->bitArray[i] |= to_or->bitArray[i];
837 return GNUNET_OK; 835 return GNUNET_OK;
838} 836}
@@ -845,14 +843,14 @@ GNUNET_CONTAINER_bloomfilter_or2 (
845 * @param e the element to remove 843 * @param e the element to remove
846 */ 844 */
847void 845void
848GNUNET_CONTAINER_bloomfilter_remove (struct GNUNET_CONTAINER_BloomFilter *bf, 846GNUNET_CONTAINER_bloomfilter_remove(struct GNUNET_CONTAINER_BloomFilter *bf,
849 const struct GNUNET_HashCode *e) 847 const struct GNUNET_HashCode *e)
850{ 848{
851 if (NULL == bf) 849 if (NULL == bf)
852 return; 850 return;
853 if (NULL == bf->filename) 851 if (NULL == bf->filename)
854 return; 852 return;
855 iterateBits (bf, &decrementBitCallback, bf, e); 853 iterateBits(bf, &decrementBitCallback, bf, e);
856} 854}
857 855
858/** 856/**
@@ -867,27 +865,27 @@ GNUNET_CONTAINER_bloomfilter_remove (struct GNUNET_CONTAINER_BloomFilter *bf,
867 * @param k the new number of GNUNET_CRYPTO_hash-function to apply per element 865 * @param k the new number of GNUNET_CRYPTO_hash-function to apply per element
868 */ 866 */
869void 867void
870GNUNET_CONTAINER_bloomfilter_resize (struct GNUNET_CONTAINER_BloomFilter *bf, 868GNUNET_CONTAINER_bloomfilter_resize(struct GNUNET_CONTAINER_BloomFilter *bf,
871 GNUNET_CONTAINER_HashCodeIterator iterator, 869 GNUNET_CONTAINER_HashCodeIterator iterator,
872 void *iterator_cls, 870 void *iterator_cls,
873 size_t size, 871 size_t size,
874 unsigned int k) 872 unsigned int k)
875{ 873{
876 struct GNUNET_HashCode hc; 874 struct GNUNET_HashCode hc;
877 unsigned int i; 875 unsigned int i;
878 876
879 GNUNET_free (bf->bitArray); 877 GNUNET_free(bf->bitArray);
880 i = 1; 878 i = 1;
881 while (i < size) 879 while (i < size)
882 i *= 2; 880 i *= 2;
883 size = i; /* make sure it's a power of 2 */ 881 size = i; /* make sure it's a power of 2 */
884 bf->addressesPerElement = k; 882 bf->addressesPerElement = k;
885 bf->bitArraySize = size; 883 bf->bitArraySize = size;
886 bf->bitArray = GNUNET_malloc (size); 884 bf->bitArray = GNUNET_malloc(size);
887 if (NULL != bf->filename) 885 if (NULL != bf->filename)
888 make_empty_file (bf->fh, bf->bitArraySize * 4LL); 886 make_empty_file(bf->fh, bf->bitArraySize * 4LL);
889 while (GNUNET_YES == iterator (iterator_cls, &hc)) 887 while (GNUNET_YES == iterator(iterator_cls, &hc))
890 GNUNET_CONTAINER_bloomfilter_add (bf, &hc); 888 GNUNET_CONTAINER_bloomfilter_add(bf, &hc);
891} 889}
892 890
893/* end of container_bloomfilter.c */ 891/* end of container_bloomfilter.c */
diff --git a/src/util/container_heap.c b/src/util/container_heap.c
index d5dca20ef..3c8e6ce58 100644
--- a/src/util/container_heap.c
+++ b/src/util/container_heap.c
@@ -1,22 +1,22 @@
1/* 1/*
2 This file is part of GNUnet. 2 This file is part of GNUnet.
3 Copyright (C) 2008, 2009 GNUnet e.V. 3 Copyright (C) 2008, 2009 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/container_heap.c 22 * @file util/container_heap.c
@@ -28,15 +28,14 @@
28#include "platform.h" 28#include "platform.h"
29#include "gnunet_container_lib.h" 29#include "gnunet_container_lib.h"
30 30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-container-heap", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-container-heap", __VA_ARGS__)
32 32
33#define EXTRA_CHECKS 0 33#define EXTRA_CHECKS 0
34 34
35/** 35/**
36 * Node in the heap. 36 * Node in the heap.
37 */ 37 */
38struct GNUNET_CONTAINER_HeapNode 38struct GNUNET_CONTAINER_HeapNode {
39{
40 /** 39 /**
41 * Heap this node belongs to. 40 * Heap this node belongs to.
42 */ 41 */
@@ -72,15 +71,12 @@ struct GNUNET_CONTAINER_HeapNode
72 * (excluding this node itself). 71 * (excluding this node itself).
73 */ 72 */
74 unsigned int tree_size; 73 unsigned int tree_size;
75
76}; 74};
77 75
78/** 76/**
79 * Handle to a node in a heap. 77 * Handle to a node in a heap.
80 */ 78 */
81struct GNUNET_CONTAINER_Heap 79struct GNUNET_CONTAINER_Heap {
82{
83
84 /** 80 /**
85 * Root of the heap. 81 * Root of the heap.
86 */ 82 */
@@ -100,7 +96,6 @@ struct GNUNET_CONTAINER_Heap
100 * How is the heap sorted? 96 * How is the heap sorted?
101 */ 97 */
102 enum GNUNET_CONTAINER_HeapOrder order; 98 enum GNUNET_CONTAINER_HeapOrder order;
103
104}; 99};
105 100
106 101
@@ -111,17 +106,17 @@ struct GNUNET_CONTAINER_Heap
111 * @param node subtree to check 106 * @param node subtree to check
112 */ 107 */
113static void 108static void
114check (const struct GNUNET_CONTAINER_HeapNode *node) 109check(const struct GNUNET_CONTAINER_HeapNode *node)
115{ 110{
116 if (NULL == node) 111 if (NULL == node)
117 return; 112 return;
118 GNUNET_assert (node->tree_size == 113 GNUNET_assert(node->tree_size ==
119 ((node->left_child == 114 ((node->left_child ==
120 NULL) ? 0 : 1 + node->left_child->tree_size) + 115 NULL) ? 0 : 1 + node->left_child->tree_size) +
121 ((node->right_child == 116 ((node->right_child ==
122 NULL) ? 0 : 1 + node->right_child->tree_size)); 117 NULL) ? 0 : 1 + node->right_child->tree_size));
123 check (node->left_child); 118 check(node->left_child);
124 check (node->right_child); 119 check(node->right_child);
125} 120}
126 121
127 122
@@ -138,11 +133,11 @@ check (const struct GNUNET_CONTAINER_HeapNode *node)
138 * @return handle to the heap 133 * @return handle to the heap
139 */ 134 */
140struct GNUNET_CONTAINER_Heap * 135struct GNUNET_CONTAINER_Heap *
141GNUNET_CONTAINER_heap_create (enum GNUNET_CONTAINER_HeapOrder order) 136GNUNET_CONTAINER_heap_create(enum GNUNET_CONTAINER_HeapOrder order)
142{ 137{
143 struct GNUNET_CONTAINER_Heap *heap; 138 struct GNUNET_CONTAINER_Heap *heap;
144 139
145 heap = GNUNET_new (struct GNUNET_CONTAINER_Heap); 140 heap = GNUNET_new(struct GNUNET_CONTAINER_Heap);
146 heap->order = order; 141 heap->order = order;
147 return heap; 142 return heap;
148} 143}
@@ -155,10 +150,10 @@ GNUNET_CONTAINER_heap_create (enum GNUNET_CONTAINER_HeapOrder order)
155 * @param heap heap to destroy 150 * @param heap heap to destroy
156 */ 151 */
157void 152void
158GNUNET_CONTAINER_heap_destroy (struct GNUNET_CONTAINER_Heap *heap) 153GNUNET_CONTAINER_heap_destroy(struct GNUNET_CONTAINER_Heap *heap)
159{ 154{
160 GNUNET_break (heap->size == 0); 155 GNUNET_break(heap->size == 0);
161 GNUNET_free (heap); 156 GNUNET_free(heap);
162} 157}
163 158
164 159
@@ -169,7 +164,7 @@ GNUNET_CONTAINER_heap_destroy (struct GNUNET_CONTAINER_Heap *heap)
169 * @return Element at the root, or NULL if heap is empty. 164 * @return Element at the root, or NULL if heap is empty.
170 */ 165 */
171void * 166void *
172GNUNET_CONTAINER_heap_peek (const struct GNUNET_CONTAINER_Heap *heap) 167GNUNET_CONTAINER_heap_peek(const struct GNUNET_CONTAINER_Heap *heap)
173{ 168{
174 if (heap->root == NULL) 169 if (heap->root == NULL)
175 return NULL; 170 return NULL;
@@ -187,9 +182,9 @@ GNUNET_CONTAINER_heap_peek (const struct GNUNET_CONTAINER_Heap *heap)
187 * #GNUNET_NO if the heap is empty. 182 * #GNUNET_NO if the heap is empty.
188 */ 183 */
189int 184int
190GNUNET_CONTAINER_heap_peek2 (const struct GNUNET_CONTAINER_Heap *heap, 185GNUNET_CONTAINER_heap_peek2(const struct GNUNET_CONTAINER_Heap *heap,
191 void **element, 186 void **element,
192 GNUNET_CONTAINER_HeapCostType *cost) 187 GNUNET_CONTAINER_HeapCostType *cost)
193{ 188{
194 if (NULL == heap->root) 189 if (NULL == heap->root)
195 return GNUNET_NO; 190 return GNUNET_NO;
@@ -208,7 +203,7 @@ GNUNET_CONTAINER_heap_peek2 (const struct GNUNET_CONTAINER_Heap *heap,
208 * @return number of elements stored 203 * @return number of elements stored
209 */ 204 */
210unsigned int 205unsigned int
211GNUNET_CONTAINER_heap_get_size (const struct GNUNET_CONTAINER_Heap *heap) 206GNUNET_CONTAINER_heap_get_size(const struct GNUNET_CONTAINER_Heap *heap)
212{ 207{
213 return heap->size; 208 return heap->size;
214} 209}
@@ -221,8 +216,8 @@ GNUNET_CONTAINER_heap_get_size (const struct GNUNET_CONTAINER_Heap *heap)
221 * @return cost of the node 216 * @return cost of the node
222 */ 217 */
223GNUNET_CONTAINER_HeapCostType 218GNUNET_CONTAINER_HeapCostType
224GNUNET_CONTAINER_heap_node_get_cost (const struct GNUNET_CONTAINER_HeapNode 219GNUNET_CONTAINER_heap_node_get_cost(const struct GNUNET_CONTAINER_HeapNode
225 *node) 220 *node)
226{ 221{
227 return node->cost; 222 return node->cost;
228} 223}
@@ -238,19 +233,19 @@ GNUNET_CONTAINER_heap_node_get_cost (const struct GNUNET_CONTAINER_HeapNode
238 * @return GNUNET_YES to continue to iterate 233 * @return GNUNET_YES to continue to iterate
239 */ 234 */
240static int 235static int
241node_iterator (const struct GNUNET_CONTAINER_Heap *heap, 236node_iterator(const struct GNUNET_CONTAINER_Heap *heap,
242 struct GNUNET_CONTAINER_HeapNode *node, 237 struct GNUNET_CONTAINER_HeapNode *node,
243 GNUNET_CONTAINER_HeapIterator iterator, void *iterator_cls) 238 GNUNET_CONTAINER_HeapIterator iterator, void *iterator_cls)
244{ 239{
245 if (node == NULL) 240 if (node == NULL)
246 return GNUNET_YES; 241 return GNUNET_YES;
247 if (GNUNET_YES != 242 if (GNUNET_YES !=
248 node_iterator (heap, node->left_child, iterator, iterator_cls)) 243 node_iterator(heap, node->left_child, iterator, iterator_cls))
249 return GNUNET_NO; 244 return GNUNET_NO;
250 if (GNUNET_YES != 245 if (GNUNET_YES !=
251 node_iterator (heap, node->right_child, iterator, iterator_cls)) 246 node_iterator(heap, node->right_child, iterator, iterator_cls))
252 return GNUNET_NO; 247 return GNUNET_NO;
253 return iterator (iterator_cls, node, node->element, node->cost); 248 return iterator(iterator_cls, node, node->element, node->cost);
254} 249}
255 250
256 251
@@ -262,11 +257,11 @@ node_iterator (const struct GNUNET_CONTAINER_Heap *heap,
262 * @param iterator_cls closure for iterator 257 * @param iterator_cls closure for iterator
263 */ 258 */
264void 259void
265GNUNET_CONTAINER_heap_iterate (const struct GNUNET_CONTAINER_Heap *heap, 260GNUNET_CONTAINER_heap_iterate(const struct GNUNET_CONTAINER_Heap *heap,
266 GNUNET_CONTAINER_HeapIterator iterator, 261 GNUNET_CONTAINER_HeapIterator iterator,
267 void *iterator_cls) 262 void *iterator_cls)
268{ 263{
269 (void) node_iterator (heap, heap->root, iterator, iterator_cls); 264 (void)node_iterator(heap, heap->root, iterator, iterator_cls);
270} 265}
271 266
272 267
@@ -282,7 +277,7 @@ GNUNET_CONTAINER_heap_iterate (const struct GNUNET_CONTAINER_Heap *heap,
282 * NULL if the tree is empty. 277 * NULL if the tree is empty.
283 */ 278 */
284void * 279void *
285GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap) 280GNUNET_CONTAINER_heap_walk_get_next(struct GNUNET_CONTAINER_Heap *heap)
286{ 281{
287 struct GNUNET_CONTAINER_HeapNode *pos; 282 struct GNUNET_CONTAINER_HeapNode *pos;
288 void *element; 283 void *element;
@@ -294,9 +289,9 @@ GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap)
294 pos = heap->root; 289 pos = heap->root;
295 element = pos->element; 290 element = pos->element;
296 heap->walk_pos = 291 heap->walk_pos =
297 (0 == 292 (0 ==
298 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 293 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
299 2)) ? pos->right_child : pos->left_child; 294 2)) ? pos->right_child : pos->left_child;
300 return element; 295 return element;
301} 296}
302 297
@@ -310,55 +305,55 @@ GNUNET_CONTAINER_heap_walk_get_next (struct GNUNET_CONTAINER_Heap *heap)
310 * @param node node to insert (which may be a subtree itself) 305 * @param node node to insert (which may be a subtree itself)
311 */ 306 */
312static void 307static void
313insert_node (struct GNUNET_CONTAINER_Heap *heap, 308insert_node(struct GNUNET_CONTAINER_Heap *heap,
314 struct GNUNET_CONTAINER_HeapNode *pos, 309 struct GNUNET_CONTAINER_HeapNode *pos,
315 struct GNUNET_CONTAINER_HeapNode *node) 310 struct GNUNET_CONTAINER_HeapNode *node)
316{ 311{
317 struct GNUNET_CONTAINER_HeapNode *parent; 312 struct GNUNET_CONTAINER_HeapNode *parent;
318 313
319 GNUNET_assert (node->parent == NULL); 314 GNUNET_assert(node->parent == NULL);
320 while ((heap->order == GNUNET_CONTAINER_HEAP_ORDER_MAX) ? (pos->cost >= 315 while ((heap->order == GNUNET_CONTAINER_HEAP_ORDER_MAX) ? (pos->cost >=
321 node->cost) 316 node->cost)
322 : (pos->cost <= node->cost)) 317 : (pos->cost <= node->cost))
323 {
324 /* node is descendent of pos */
325 pos->tree_size += (1 + node->tree_size);
326 if (pos->left_child == NULL)
327 {
328 pos->left_child = node;
329 node->parent = pos;
330 return;
331 }
332 if (pos->right_child == NULL)
333 { 318 {
334 pos->right_child = node; 319 /* node is descendent of pos */
335 node->parent = pos; 320 pos->tree_size += (1 + node->tree_size);
336 return; 321 if (pos->left_child == NULL)
322 {
323 pos->left_child = node;
324 node->parent = pos;
325 return;
326 }
327 if (pos->right_child == NULL)
328 {
329 pos->right_child = node;
330 node->parent = pos;
331 return;
332 }
333 /* keep it balanced by descending into smaller subtree */
334 if (pos->left_child->tree_size < pos->right_child->tree_size)
335 pos = pos->left_child;
336 else
337 pos = pos->right_child;
337 } 338 }
338 /* keep it balanced by descending into smaller subtree */
339 if (pos->left_child->tree_size < pos->right_child->tree_size)
340 pos = pos->left_child;
341 else
342 pos = pos->right_child;
343 }
344 /* make 'node' parent of 'pos' */ 339 /* make 'node' parent of 'pos' */
345 parent = pos->parent; 340 parent = pos->parent;
346 pos->parent = NULL; 341 pos->parent = NULL;
347 node->parent = parent; 342 node->parent = parent;
348 if (NULL == parent) 343 if (NULL == parent)
349 { 344 {
350 heap->root = node; 345 heap->root = node;
351 } 346 }
352 else 347 else
353 { 348 {
354 if (parent->left_child == pos) 349 if (parent->left_child == pos)
355 parent->left_child = node; 350 parent->left_child = node;
356 else 351 else
357 parent->right_child = node; 352 parent->right_child = node;
358 } 353 }
359 /* insert 'pos' below 'node' */ 354 /* insert 'pos' below 'node' */
360 insert_node (heap, node, pos); 355 insert_node(heap, node, pos);
361 CHECK (pos); 356 CHECK(pos);
362} 357}
363 358
364 359
@@ -371,12 +366,12 @@ insert_node (struct GNUNET_CONTAINER_Heap *heap,
371 * @return node for the new element 366 * @return node for the new element
372 */ 367 */
373struct GNUNET_CONTAINER_HeapNode * 368struct GNUNET_CONTAINER_HeapNode *
374GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap, void *element, 369GNUNET_CONTAINER_heap_insert(struct GNUNET_CONTAINER_Heap *heap, void *element,
375 GNUNET_CONTAINER_HeapCostType cost) 370 GNUNET_CONTAINER_HeapCostType cost)
376{ 371{
377 struct GNUNET_CONTAINER_HeapNode *node; 372 struct GNUNET_CONTAINER_HeapNode *node;
378 373
379 node = GNUNET_new (struct GNUNET_CONTAINER_HeapNode); 374 node = GNUNET_new(struct GNUNET_CONTAINER_HeapNode);
380 node->heap = heap; 375 node->heap = heap;
381 node->element = element; 376 node->element = element;
382 node->cost = cost; 377 node->cost = cost;
@@ -384,9 +379,9 @@ GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap, void *element,
384 if (NULL == heap->root) 379 if (NULL == heap->root)
385 heap->root = node; 380 heap->root = node;
386 else 381 else
387 insert_node (heap, heap->root, node); 382 insert_node(heap, heap->root, node);
388 GNUNET_assert (heap->size == heap->root->tree_size + 1); 383 GNUNET_assert(heap->size == heap->root->tree_size + 1);
389 CHECK (heap->root); 384 CHECK(heap->root);
390 return node; 385 return node;
391} 386}
392 387
@@ -398,7 +393,7 @@ GNUNET_CONTAINER_heap_insert (struct GNUNET_CONTAINER_Heap *heap, void *element,
398 * @return element data stored at the root node, NULL if heap is empty 393 * @return element data stored at the root node, NULL if heap is empty
399 */ 394 */
400void * 395void *
401GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap) 396GNUNET_CONTAINER_heap_remove_root(struct GNUNET_CONTAINER_Heap *heap)
402{ 397{
403 void *ret; 398 void *ret;
404 struct GNUNET_CONTAINER_HeapNode *root; 399 struct GNUNET_CONTAINER_HeapNode *root;
@@ -408,30 +403,30 @@ GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap)
408 heap->size--; 403 heap->size--;
409 ret = root->element; 404 ret = root->element;
410 if (root->left_child == NULL) 405 if (root->left_child == NULL)
411 { 406 {
412 heap->root = root->right_child; 407 heap->root = root->right_child;
413 if (root->right_child != NULL) 408 if (root->right_child != NULL)
414 root->right_child->parent = NULL; 409 root->right_child->parent = NULL;
415 } 410 }
416 else if (root->right_child == NULL) 411 else if (root->right_child == NULL)
417 { 412 {
418 heap->root = root->left_child; 413 heap->root = root->left_child;
419 root->left_child->parent = NULL; 414 root->left_child->parent = NULL;
420 } 415 }
421 else 416 else
422 { 417 {
423 root->left_child->parent = NULL; 418 root->left_child->parent = NULL;
424 root->right_child->parent = NULL; 419 root->right_child->parent = NULL;
425 heap->root = root->left_child; 420 heap->root = root->left_child;
426 insert_node (heap, heap->root, root->right_child); 421 insert_node(heap, heap->root, root->right_child);
427 } 422 }
428 if (heap->walk_pos == root) 423 if (heap->walk_pos == root)
429 heap->walk_pos = heap->root; 424 heap->walk_pos = heap->root;
430 GNUNET_free (root); 425 GNUNET_free(root);
431#if EXTRA_CHECKS 426#if EXTRA_CHECKS
432 GNUNET_assert (((heap->size == 0) && (heap->root == NULL)) || 427 GNUNET_assert(((heap->size == 0) && (heap->root == NULL)) ||
433 (heap->size == heap->root->tree_size + 1)); 428 (heap->size == heap->root->tree_size + 1));
434 CHECK (heap->root); 429 CHECK(heap->root);
435#endif 430#endif
436 return ret; 431 return ret;
437} 432}
@@ -444,7 +439,7 @@ GNUNET_CONTAINER_heap_remove_root (struct GNUNET_CONTAINER_Heap *heap)
444 * 'size' field of the tree. 439 * 'size' field of the tree.
445 */ 440 */
446static void 441static void
447remove_node (struct GNUNET_CONTAINER_HeapNode *node) 442remove_node(struct GNUNET_CONTAINER_HeapNode *node)
448{ 443{
449 struct GNUNET_CONTAINER_HeapNode *ancestor; 444 struct GNUNET_CONTAINER_HeapNode *ancestor;
450 struct GNUNET_CONTAINER_Heap *heap = node->heap; 445 struct GNUNET_CONTAINER_Heap *heap = node->heap;
@@ -462,48 +457,48 @@ remove_node (struct GNUNET_CONTAINER_HeapNode *node)
462 457
463 /* unlink 'node' itself and insert children in its place */ 458 /* unlink 'node' itself and insert children in its place */
464 if (node->parent == NULL) 459 if (node->parent == NULL)
465 {
466 if (node->left_child != NULL)
467 { 460 {
468 heap->root = node->left_child; 461 if (node->left_child != NULL)
469 node->left_child->parent = NULL; 462 {
470 if (node->right_child != NULL) 463 heap->root = node->left_child;
471 { 464 node->left_child->parent = NULL;
472 node->right_child->parent = NULL; 465 if (node->right_child != NULL)
473 insert_node (heap, heap->root, node->right_child); 466 {
474 } 467 node->right_child->parent = NULL;
475 } 468 insert_node(heap, heap->root, node->right_child);
476 else 469 }
477 { 470 }
478 heap->root = node->right_child; 471 else
479 if (node->right_child != NULL) 472 {
480 node->right_child->parent = NULL; 473 heap->root = node->right_child;
474 if (node->right_child != NULL)
475 node->right_child->parent = NULL;
476 }
481 } 477 }
482 }
483 else 478 else
484 {
485 if (node->parent->left_child == node)
486 node->parent->left_child = NULL;
487 else
488 node->parent->right_child = NULL;
489 if (node->left_child != NULL)
490 { 479 {
491 node->left_child->parent = NULL; 480 if (node->parent->left_child == node)
492 node->parent->tree_size -= (1 + node->left_child->tree_size); 481 node->parent->left_child = NULL;
493 insert_node (heap, node->parent, node->left_child); 482 else
494 } 483 node->parent->right_child = NULL;
495 if (node->right_child != NULL) 484 if (node->left_child != NULL)
496 { 485 {
497 node->right_child->parent = NULL; 486 node->left_child->parent = NULL;
498 node->parent->tree_size -= (1 + node->right_child->tree_size); 487 node->parent->tree_size -= (1 + node->left_child->tree_size);
499 insert_node (heap, node->parent, node->right_child); 488 insert_node(heap, node->parent, node->left_child);
489 }
490 if (node->right_child != NULL)
491 {
492 node->right_child->parent = NULL;
493 node->parent->tree_size -= (1 + node->right_child->tree_size);
494 insert_node(heap, node->parent, node->right_child);
495 }
500 } 496 }
501 }
502 node->parent = NULL; 497 node->parent = NULL;
503 node->left_child = NULL; 498 node->left_child = NULL;
504 node->right_child = NULL; 499 node->right_child = NULL;
505 GNUNET_assert (node->tree_size == 0); 500 GNUNET_assert(node->tree_size == 0);
506 CHECK (heap->root); 501 CHECK(heap->root);
507} 502}
508 503
509 504
@@ -514,25 +509,25 @@ remove_node (struct GNUNET_CONTAINER_HeapNode *node)
514 * @return element data stored at the node 509 * @return element data stored at the node
515 */ 510 */
516void * 511void *
517GNUNET_CONTAINER_heap_remove_node (struct GNUNET_CONTAINER_HeapNode *node) 512GNUNET_CONTAINER_heap_remove_node(struct GNUNET_CONTAINER_HeapNode *node)
518{ 513{
519 void *ret; 514 void *ret;
520 struct GNUNET_CONTAINER_Heap *heap; 515 struct GNUNET_CONTAINER_Heap *heap;
521 516
522 heap = node->heap; 517 heap = node->heap;
523 CHECK (heap->root); 518 CHECK(heap->root);
524 if (heap->walk_pos == node) 519 if (heap->walk_pos == node)
525 (void) GNUNET_CONTAINER_heap_walk_get_next (heap); 520 (void)GNUNET_CONTAINER_heap_walk_get_next(heap);
526 remove_node (node); 521 remove_node(node);
527 heap->size--; 522 heap->size--;
528 ret = node->element; 523 ret = node->element;
529 if (heap->walk_pos == node) 524 if (heap->walk_pos == node)
530 heap->walk_pos = NULL; 525 heap->walk_pos = NULL;
531 GNUNET_free (node); 526 GNUNET_free(node);
532#if EXTRA_CHECKS 527#if EXTRA_CHECKS
533 CHECK (heap->root); 528 CHECK(heap->root);
534 GNUNET_assert (((heap->size == 0) && (heap->root == NULL)) || 529 GNUNET_assert(((heap->size == 0) && (heap->root == NULL)) ||
535 (heap->size == heap->root->tree_size + 1)); 530 (heap->size == heap->root->tree_size + 1));
536#endif 531#endif
537 return ret; 532 return ret;
538} 533}
@@ -545,19 +540,19 @@ GNUNET_CONTAINER_heap_remove_node (struct GNUNET_CONTAINER_HeapNode *node)
545 * @param new_cost new cost for the node 540 * @param new_cost new cost for the node
546 */ 541 */
547void 542void
548GNUNET_CONTAINER_heap_update_cost (struct GNUNET_CONTAINER_HeapNode *node, 543GNUNET_CONTAINER_heap_update_cost(struct GNUNET_CONTAINER_HeapNode *node,
549 GNUNET_CONTAINER_HeapCostType new_cost) 544 GNUNET_CONTAINER_HeapCostType new_cost)
550{ 545{
551 struct GNUNET_CONTAINER_Heap *heap = node->heap; 546 struct GNUNET_CONTAINER_Heap *heap = node->heap;
552 547
553 remove_node (node); 548 remove_node(node);
554 node->cost = new_cost; 549 node->cost = new_cost;
555 if (NULL == heap->root) 550 if (NULL == heap->root)
556 heap->root = node; 551 heap->root = node;
557 else 552 else
558 insert_node (heap, 553 insert_node(heap,
559 heap->root, 554 heap->root,
560 node); 555 node);
561} 556}
562 557
563 558
diff --git a/src/util/container_meta_data.c b/src/util/container_meta_data.c
index 4989b876a..e134ef869 100644
--- a/src/util/container_meta_data.c
+++ b/src/util/container_meta_data.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/container_meta_data.c 22 * @file util/container_meta_data.c
@@ -31,7 +31,7 @@
31#endif 31#endif
32#include <zlib.h> 32#include <zlib.h>
33 33
34#define LOG(kind,...) GNUNET_log_from (kind, "util-container-meta-data", __VA_ARGS__) 34#define LOG(kind, ...) GNUNET_log_from(kind, "util-container-meta-data", __VA_ARGS__)
35 35
36 36
37 37
@@ -51,10 +51,10 @@
51 * #GNUNET_NO if compression did not help 51 * #GNUNET_NO if compression did not help
52 */ 52 */
53int 53int
54GNUNET_try_compression (const char *data, 54GNUNET_try_compression(const char *data,
55 size_t old_size, 55 size_t old_size,
56 char **result, 56 char **result,
57 size_t *new_size) 57 size_t *new_size)
58{ 58{
59 char *tmp; 59 char *tmp;
60 uLongf dlen; 60 uLongf dlen;
@@ -62,27 +62,27 @@ GNUNET_try_compression (const char *data,
62 *result = NULL; 62 *result = NULL;
63 *new_size = 0; 63 *new_size = 0;
64#ifdef compressBound 64#ifdef compressBound
65 dlen = compressBound (old_size); 65 dlen = compressBound(old_size);
66#else 66#else
67 dlen = old_size + (old_size / 100) + 20; 67 dlen = old_size + (old_size / 100) + 20;
68 /* documentation says 100.1% oldSize + 12 bytes, but we 68 /* documentation says 100.1% oldSize + 12 bytes, but we
69 * should be able to overshoot by more to be safe */ 69 * should be able to overshoot by more to be safe */
70#endif 70#endif
71 tmp = GNUNET_malloc (dlen); 71 tmp = GNUNET_malloc(dlen);
72 if (Z_OK == 72 if (Z_OK ==
73 compress2 ((Bytef *) tmp, 73 compress2((Bytef *)tmp,
74 &dlen, 74 &dlen,
75 (const Bytef *) data, 75 (const Bytef *)data,
76 old_size, 9)) 76 old_size, 9))
77 {
78 if (dlen < old_size)
79 { 77 {
80 *result = tmp; 78 if (dlen < old_size)
81 *new_size = dlen; 79 {
82 return GNUNET_YES; 80 *result = tmp;
81 *new_size = dlen;
82 return GNUNET_YES;
83 }
83 } 84 }
84 } 85 GNUNET_free(tmp);
85 GNUNET_free (tmp);
86 return GNUNET_NO; 86 return GNUNET_NO;
87} 87}
88 88
@@ -98,22 +98,22 @@ GNUNET_try_compression (const char *data,
98 * @return NULL on error, buffer of @a output_size decompressed bytes otherwise 98 * @return NULL on error, buffer of @a output_size decompressed bytes otherwise
99 */ 99 */
100char * 100char *
101GNUNET_decompress (const char *input, 101GNUNET_decompress(const char *input,
102 size_t input_size, 102 size_t input_size,
103 size_t output_size) 103 size_t output_size)
104{ 104{
105 char *output; 105 char *output;
106 uLongf olen; 106 uLongf olen;
107 107
108 olen = output_size; 108 olen = output_size;
109 output = GNUNET_malloc (olen); 109 output = GNUNET_malloc(olen);
110 if (Z_OK == 110 if (Z_OK ==
111 uncompress ((Bytef *) output, 111 uncompress((Bytef *)output,
112 &olen, 112 &olen,
113 (const Bytef *) input, 113 (const Bytef *)input,
114 input_size)) 114 input_size))
115 return output; 115 return output;
116 GNUNET_free (output); 116 GNUNET_free(output);
117 return NULL; 117 return NULL;
118} 118}
119 119
@@ -121,8 +121,7 @@ GNUNET_decompress (const char *input,
121/** 121/**
122 * Meta data item. 122 * Meta data item.
123 */ 123 */
124struct MetaItem 124struct MetaItem {
125{
126 /** 125 /**
127 * This is a doubly linked list. 126 * This is a doubly linked list.
128 */ 127 */
@@ -162,14 +161,12 @@ struct MetaItem
162 * Format of the meta data. 161 * Format of the meta data.
163 */ 162 */
164 enum EXTRACTOR_MetaFormat format; 163 enum EXTRACTOR_MetaFormat format;
165
166}; 164};
167 165
168/** 166/**
169 * Meta data to associate with a file, directory or namespace. 167 * Meta data to associate with a file, directory or namespace.
170 */ 168 */
171struct GNUNET_CONTAINER_MetaData 169struct GNUNET_CONTAINER_MetaData {
172{
173 /** 170 /**
174 * Head of linked list of the meta data items. 171 * Head of linked list of the meta data items.
175 */ 172 */
@@ -195,7 +192,6 @@ struct GNUNET_CONTAINER_MetaData
195 * Number of items in the linked list. 192 * Number of items in the linked list.
196 */ 193 */
197 unsigned int item_count; 194 unsigned int item_count;
198
199}; 195};
200 196
201 197
@@ -205,9 +201,9 @@ struct GNUNET_CONTAINER_MetaData
205 * @return empty meta-data container 201 * @return empty meta-data container
206 */ 202 */
207struct GNUNET_CONTAINER_MetaData * 203struct GNUNET_CONTAINER_MetaData *
208GNUNET_CONTAINER_meta_data_create () 204GNUNET_CONTAINER_meta_data_create()
209{ 205{
210 return GNUNET_new (struct GNUNET_CONTAINER_MetaData); 206 return GNUNET_new(struct GNUNET_CONTAINER_MetaData);
211} 207}
212 208
213 209
@@ -217,12 +213,12 @@ GNUNET_CONTAINER_meta_data_create ()
217 * @param mi item to free 213 * @param mi item to free
218 */ 214 */
219static void 215static void
220meta_item_free (struct MetaItem *mi) 216meta_item_free(struct MetaItem *mi)
221{ 217{
222 GNUNET_free_non_null (mi->plugin_name); 218 GNUNET_free_non_null(mi->plugin_name);
223 GNUNET_free_non_null (mi->mime_type); 219 GNUNET_free_non_null(mi->mime_type);
224 GNUNET_free_non_null (mi->data); 220 GNUNET_free_non_null(mi->data);
225 GNUNET_free (mi); 221 GNUNET_free(mi);
226} 222}
227 223
228 224
@@ -233,11 +229,11 @@ meta_item_free (struct MetaItem *mi)
233 * @param md meta data that changed 229 * @param md meta data that changed
234 */ 230 */
235static void 231static void
236invalidate_sbuf (struct GNUNET_CONTAINER_MetaData *md) 232invalidate_sbuf(struct GNUNET_CONTAINER_MetaData *md)
237{ 233{
238 if (NULL == md->sbuf) 234 if (NULL == md->sbuf)
239 return; 235 return;
240 GNUNET_free (md->sbuf); 236 GNUNET_free(md->sbuf);
241 md->sbuf = NULL; 237 md->sbuf = NULL;
242 md->sbuf_size = 0; 238 md->sbuf_size = 0;
243} 239}
@@ -249,19 +245,19 @@ invalidate_sbuf (struct GNUNET_CONTAINER_MetaData *md)
249 * @param md what to free 245 * @param md what to free
250 */ 246 */
251void 247void
252GNUNET_CONTAINER_meta_data_destroy (struct GNUNET_CONTAINER_MetaData *md) 248GNUNET_CONTAINER_meta_data_destroy(struct GNUNET_CONTAINER_MetaData *md)
253{ 249{
254 struct MetaItem *pos; 250 struct MetaItem *pos;
255 251
256 if (NULL == md) 252 if (NULL == md)
257 return; 253 return;
258 while (NULL != (pos = md->items_head)) 254 while (NULL != (pos = md->items_head))
259 { 255 {
260 GNUNET_CONTAINER_DLL_remove (md->items_head, md->items_tail, pos); 256 GNUNET_CONTAINER_DLL_remove(md->items_head, md->items_tail, pos);
261 meta_item_free (pos); 257 meta_item_free(pos);
262 } 258 }
263 GNUNET_free_non_null (md->sbuf); 259 GNUNET_free_non_null(md->sbuf);
264 GNUNET_free (md); 260 GNUNET_free(md);
265} 261}
266 262
267 263
@@ -271,19 +267,19 @@ GNUNET_CONTAINER_meta_data_destroy (struct GNUNET_CONTAINER_MetaData *md)
271 * @param md metadata to manipulate 267 * @param md metadata to manipulate
272 */ 268 */
273void 269void
274GNUNET_CONTAINER_meta_data_clear (struct GNUNET_CONTAINER_MetaData *md) 270GNUNET_CONTAINER_meta_data_clear(struct GNUNET_CONTAINER_MetaData *md)
275{ 271{
276 struct MetaItem *mi; 272 struct MetaItem *mi;
277 273
278 if (NULL == md) 274 if (NULL == md)
279 return; 275 return;
280 while (NULL != (mi = md->items_head)) 276 while (NULL != (mi = md->items_head))
281 { 277 {
282 GNUNET_CONTAINER_DLL_remove (md->items_head, md->items_tail, mi); 278 GNUNET_CONTAINER_DLL_remove(md->items_head, md->items_tail, mi);
283 meta_item_free (mi); 279 meta_item_free(mi);
284 } 280 }
285 GNUNET_free_non_null (md->sbuf); 281 GNUNET_free_non_null(md->sbuf);
286 memset (md, 0, sizeof (struct GNUNET_CONTAINER_MetaData)); 282 memset(md, 0, sizeof(struct GNUNET_CONTAINER_MetaData));
287} 283}
288 284
289 285
@@ -298,10 +294,10 @@ GNUNET_CONTAINER_meta_data_clear (struct GNUNET_CONTAINER_MetaData *md)
298 * @return #GNUNET_YES if they are equal 294 * @return #GNUNET_YES if they are equal
299 */ 295 */
300int 296int
301GNUNET_CONTAINER_meta_data_test_equal (const struct GNUNET_CONTAINER_MetaData 297GNUNET_CONTAINER_meta_data_test_equal(const struct GNUNET_CONTAINER_MetaData
302 *md1, 298 *md1,
303 const struct GNUNET_CONTAINER_MetaData 299 const struct GNUNET_CONTAINER_MetaData
304 *md2) 300 *md2)
305{ 301{
306 struct MetaItem *i; 302 struct MetaItem *i;
307 struct MetaItem *j; 303 struct MetaItem *j;
@@ -312,23 +308,23 @@ GNUNET_CONTAINER_meta_data_test_equal (const struct GNUNET_CONTAINER_MetaData
312 if (md1->item_count != md2->item_count) 308 if (md1->item_count != md2->item_count)
313 return GNUNET_NO; 309 return GNUNET_NO;
314 for (i = md1->items_head; NULL != i; i = i->next) 310 for (i = md1->items_head; NULL != i; i = i->next)
315 {
316 found = GNUNET_NO;
317 for (j = md2->items_head; NULL != j; j = j->next)
318 { 311 {
319 if ((i->type == j->type) && (i->format == j->format) && 312 found = GNUNET_NO;
320 (i->data_size == j->data_size) && 313 for (j = md2->items_head; NULL != j; j = j->next)
321 (0 == memcmp (i->data, j->data, i->data_size))) 314 {
322 { 315 if ((i->type == j->type) && (i->format == j->format) &&
323 found = GNUNET_YES; 316 (i->data_size == j->data_size) &&
324 break; 317 (0 == memcmp(i->data, j->data, i->data_size)))
325 } 318 {
326 if (j->data_size < i->data_size) 319 found = GNUNET_YES;
327 break; /* elements are sorted by (decreasing) size... */ 320 break;
321 }
322 if (j->data_size < i->data_size)
323 break; /* elements are sorted by (decreasing) size... */
324 }
325 if (GNUNET_NO == found)
326 return GNUNET_NO;
328 } 327 }
329 if (GNUNET_NO == found)
330 return GNUNET_NO;
331 }
332 return GNUNET_YES; 328 return GNUNET_YES;
333} 329}
334 330
@@ -352,12 +348,12 @@ GNUNET_CONTAINER_meta_data_test_equal (const struct GNUNET_CONTAINER_MetaData
352 * data_mime_type and plugin_name are not considered for "exists" checks 348 * data_mime_type and plugin_name are not considered for "exists" checks
353 */ 349 */
354int 350int
355GNUNET_CONTAINER_meta_data_insert (struct GNUNET_CONTAINER_MetaData *md, 351GNUNET_CONTAINER_meta_data_insert(struct GNUNET_CONTAINER_MetaData *md,
356 const char *plugin_name, 352 const char *plugin_name,
357 enum EXTRACTOR_MetaType type, 353 enum EXTRACTOR_MetaType type,
358 enum EXTRACTOR_MetaFormat format, 354 enum EXTRACTOR_MetaFormat format,
359 const char *data_mime_type, const char *data, 355 const char *data_mime_type, const char *data,
360 size_t data_size) 356 size_t data_size)
361{ 357{
362 struct MetaItem *pos; 358 struct MetaItem *pos;
363 struct MetaItem *mi; 359 struct MetaItem *mi;
@@ -365,61 +361,61 @@ GNUNET_CONTAINER_meta_data_insert (struct GNUNET_CONTAINER_MetaData *md,
365 361
366 if ((EXTRACTOR_METAFORMAT_UTF8 == format) || 362 if ((EXTRACTOR_METAFORMAT_UTF8 == format) ||
367 (EXTRACTOR_METAFORMAT_C_STRING == format)) 363 (EXTRACTOR_METAFORMAT_C_STRING == format))
368 GNUNET_break ('\0' == data[data_size - 1]); 364 GNUNET_break('\0' == data[data_size - 1]);
369 365
370 for (pos = md->items_head; NULL != pos; pos = pos->next) 366 for (pos = md->items_head; NULL != pos; pos = pos->next)
371 {
372 if (pos->data_size < data_size)
373 break; /* elements are sorted by size in the list */
374 if ((pos->type == type) && (pos->data_size == data_size) &&
375 (0 == memcmp (pos->data, data, data_size)))
376 { 367 {
377 if ((NULL == pos->mime_type) && (NULL != data_mime_type)) 368 if (pos->data_size < data_size)
378 { 369 break; /* elements are sorted by size in the list */
379 pos->mime_type = GNUNET_strdup (data_mime_type); 370 if ((pos->type == type) && (pos->data_size == data_size) &&
380 invalidate_sbuf (md); 371 (0 == memcmp(pos->data, data, data_size)))
381 } 372 {
382 if ((EXTRACTOR_METAFORMAT_C_STRING == pos->format) && 373 if ((NULL == pos->mime_type) && (NULL != data_mime_type))
383 (EXTRACTOR_METAFORMAT_UTF8 == format)) 374 {
384 { 375 pos->mime_type = GNUNET_strdup(data_mime_type);
385 pos->format = EXTRACTOR_METAFORMAT_UTF8; 376 invalidate_sbuf(md);
386 invalidate_sbuf (md); 377 }
387 } 378 if ((EXTRACTOR_METAFORMAT_C_STRING == pos->format) &&
388 return GNUNET_SYSERR; 379 (EXTRACTOR_METAFORMAT_UTF8 == format))
380 {
381 pos->format = EXTRACTOR_METAFORMAT_UTF8;
382 invalidate_sbuf(md);
383 }
384 return GNUNET_SYSERR;
385 }
389 } 386 }
390 }
391 md->item_count++; 387 md->item_count++;
392 mi = GNUNET_new (struct MetaItem); 388 mi = GNUNET_new(struct MetaItem);
393 mi->type = type; 389 mi->type = type;
394 mi->format = format; 390 mi->format = format;
395 mi->data_size = data_size; 391 mi->data_size = data_size;
396 if (NULL == pos) 392 if (NULL == pos)
397 GNUNET_CONTAINER_DLL_insert_tail (md->items_head, 393 GNUNET_CONTAINER_DLL_insert_tail(md->items_head,
398 md->items_tail, 394 md->items_tail,
399 mi); 395 mi);
400 else 396 else
401 GNUNET_CONTAINER_DLL_insert_after (md->items_head, 397 GNUNET_CONTAINER_DLL_insert_after(md->items_head,
402 md->items_tail, 398 md->items_tail,
403 pos->prev, 399 pos->prev,
404 mi); 400 mi);
405 mi->mime_type = 401 mi->mime_type =
406 (NULL == data_mime_type) ? NULL : GNUNET_strdup (data_mime_type); 402 (NULL == data_mime_type) ? NULL : GNUNET_strdup(data_mime_type);
407 mi->plugin_name = (NULL == plugin_name) ? NULL : GNUNET_strdup (plugin_name); 403 mi->plugin_name = (NULL == plugin_name) ? NULL : GNUNET_strdup(plugin_name);
408 mi->data = GNUNET_malloc (data_size); 404 mi->data = GNUNET_malloc(data_size);
409 GNUNET_memcpy (mi->data, data, data_size); 405 GNUNET_memcpy(mi->data, data, data_size);
410 /* change all dir separators to POSIX style ('/') */ 406 /* change all dir separators to POSIX style ('/') */
411 if ( (EXTRACTOR_METATYPE_FILENAME == type) || 407 if ((EXTRACTOR_METATYPE_FILENAME == type) ||
412 (EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME == type) ) 408 (EXTRACTOR_METATYPE_GNUNET_ORIGINAL_FILENAME == type))
413 {
414 p = mi->data;
415 while (('\0' != *p) && (p < mi->data + data_size))
416 { 409 {
417 if ('\\' == *p) 410 p = mi->data;
418 *p = '/'; 411 while (('\0' != *p) && (p < mi->data + data_size))
419 p++; 412 {
413 if ('\\' == *p)
414 *p = '/';
415 p++;
416 }
420 } 417 }
421 } 418 invalidate_sbuf(md);
422 invalidate_sbuf (md);
423 return GNUNET_OK; 419 return GNUNET_OK;
424} 420}
425 421
@@ -441,14 +437,14 @@ GNUNET_CONTAINER_meta_data_insert (struct GNUNET_CONTAINER_MetaData *md,
441 * @return 0 (to continue) 437 * @return 0 (to continue)
442 */ 438 */
443static int 439static int
444merge_helper (void *cls, const char *plugin_name, enum EXTRACTOR_MetaType type, 440merge_helper(void *cls, const char *plugin_name, enum EXTRACTOR_MetaType type,
445 enum EXTRACTOR_MetaFormat format, const char *data_mime_type, 441 enum EXTRACTOR_MetaFormat format, const char *data_mime_type,
446 const char *data, size_t data_size) 442 const char *data, size_t data_size)
447{ 443{
448 struct GNUNET_CONTAINER_MetaData *md = cls; 444 struct GNUNET_CONTAINER_MetaData *md = cls;
449 445
450 (void) GNUNET_CONTAINER_meta_data_insert (md, plugin_name, type, format, 446 (void)GNUNET_CONTAINER_meta_data_insert(md, plugin_name, type, format,
451 data_mime_type, data, data_size); 447 data_mime_type, data, data_size);
452 return 0; 448 return 0;
453} 449}
454 450
@@ -461,10 +457,10 @@ merge_helper (void *cls, const char *plugin_name, enum EXTRACTOR_MetaType type,
461 * @param in metadata to merge 457 * @param in metadata to merge
462 */ 458 */
463void 459void
464GNUNET_CONTAINER_meta_data_merge (struct GNUNET_CONTAINER_MetaData *md, 460GNUNET_CONTAINER_meta_data_merge(struct GNUNET_CONTAINER_MetaData *md,
465 const struct GNUNET_CONTAINER_MetaData *in) 461 const struct GNUNET_CONTAINER_MetaData *in)
466{ 462{
467 GNUNET_CONTAINER_meta_data_iterate (in, &merge_helper, md); 463 GNUNET_CONTAINER_meta_data_iterate(in, &merge_helper, md);
468} 464}
469 465
470 466
@@ -479,28 +475,28 @@ GNUNET_CONTAINER_meta_data_merge (struct GNUNET_CONTAINER_MetaData *md,
479 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the item does not exist in md 475 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the item does not exist in md
480 */ 476 */
481int 477int
482GNUNET_CONTAINER_meta_data_delete (struct GNUNET_CONTAINER_MetaData *md, 478GNUNET_CONTAINER_meta_data_delete(struct GNUNET_CONTAINER_MetaData *md,
483 enum EXTRACTOR_MetaType type, 479 enum EXTRACTOR_MetaType type,
484 const char *data, size_t data_size) 480 const char *data, size_t data_size)
485{ 481{
486 struct MetaItem *pos; 482 struct MetaItem *pos;
487 483
488 for (pos = md->items_head; NULL != pos; pos = pos->next) 484 for (pos = md->items_head; NULL != pos; pos = pos->next)
489 {
490 if (pos->data_size < data_size)
491 break; /* items are sorted by (decreasing) size */
492 if ((pos->type == type) &&
493 ((NULL == data) ||
494 ((pos->data_size == data_size) &&
495 (0 == memcmp (pos->data, data, data_size)))))
496 { 485 {
497 GNUNET_CONTAINER_DLL_remove (md->items_head, md->items_tail, pos); 486 if (pos->data_size < data_size)
498 meta_item_free (pos); 487 break; /* items are sorted by (decreasing) size */
499 md->item_count--; 488 if ((pos->type == type) &&
500 invalidate_sbuf (md); 489 ((NULL == data) ||
501 return GNUNET_OK; 490 ((pos->data_size == data_size) &&
491 (0 == memcmp(pos->data, data, data_size)))))
492 {
493 GNUNET_CONTAINER_DLL_remove(md->items_head, md->items_tail, pos);
494 meta_item_free(pos);
495 md->item_count--;
496 invalidate_sbuf(md);
497 return GNUNET_OK;
498 }
502 } 499 }
503 }
504 return GNUNET_SYSERR; 500 return GNUNET_SYSERR;
505} 501}
506 502
@@ -512,21 +508,21 @@ GNUNET_CONTAINER_meta_data_delete (struct GNUNET_CONTAINER_MetaData *md,
512 * @param md metadata to modify 508 * @param md metadata to modify
513 */ 509 */
514void 510void
515GNUNET_CONTAINER_meta_data_add_publication_date (struct 511GNUNET_CONTAINER_meta_data_add_publication_date(struct
516 GNUNET_CONTAINER_MetaData *md) 512 GNUNET_CONTAINER_MetaData *md)
517{ 513{
518 const char *dat; 514 const char *dat;
519 struct GNUNET_TIME_Absolute t; 515 struct GNUNET_TIME_Absolute t;
520 516
521 t = GNUNET_TIME_absolute_get (); 517 t = GNUNET_TIME_absolute_get();
522 GNUNET_CONTAINER_meta_data_delete (md, 518 GNUNET_CONTAINER_meta_data_delete(md,
523 EXTRACTOR_METATYPE_PUBLICATION_DATE, 519 EXTRACTOR_METATYPE_PUBLICATION_DATE,
524 NULL, 0); 520 NULL, 0);
525 dat = GNUNET_STRINGS_absolute_time_to_string (t); 521 dat = GNUNET_STRINGS_absolute_time_to_string(t);
526 GNUNET_CONTAINER_meta_data_insert (md, "<gnunet>", 522 GNUNET_CONTAINER_meta_data_insert(md, "<gnunet>",
527 EXTRACTOR_METATYPE_PUBLICATION_DATE, 523 EXTRACTOR_METATYPE_PUBLICATION_DATE,
528 EXTRACTOR_METAFORMAT_UTF8, "text/plain", 524 EXTRACTOR_METAFORMAT_UTF8, "text/plain",
529 dat, strlen (dat) + 1); 525 dat, strlen(dat) + 1);
530} 526}
531 527
532 528
@@ -539,9 +535,9 @@ GNUNET_CONTAINER_meta_data_add_publication_date (struct
539 * @return number of entries 535 * @return number of entries
540 */ 536 */
541int 537int
542GNUNET_CONTAINER_meta_data_iterate (const struct GNUNET_CONTAINER_MetaData *md, 538GNUNET_CONTAINER_meta_data_iterate(const struct GNUNET_CONTAINER_MetaData *md,
543 EXTRACTOR_MetaDataProcessor iter, 539 EXTRACTOR_MetaDataProcessor iter,
544 void *iter_cls) 540 void *iter_cls)
545{ 541{
546 struct MetaItem *pos; 542 struct MetaItem *pos;
547 543
@@ -551,8 +547,8 @@ GNUNET_CONTAINER_meta_data_iterate (const struct GNUNET_CONTAINER_MetaData *md,
551 return md->item_count; 547 return md->item_count;
552 for (pos = md->items_head; NULL != pos; pos = pos->next) 548 for (pos = md->items_head; NULL != pos; pos = pos->next)
553 if (0 != 549 if (0 !=
554 iter (iter_cls, pos->plugin_name, pos->type, pos->format, 550 iter(iter_cls, pos->plugin_name, pos->type, pos->format,
555 pos->mime_type, pos->data, pos->data_size)) 551 pos->mime_type, pos->data, pos->data_size))
556 return md->item_count; 552 return md->item_count;
557 return md->item_count; 553 return md->item_count;
558} 554}
@@ -569,8 +565,8 @@ GNUNET_CONTAINER_meta_data_iterate (const struct GNUNET_CONTAINER_MetaData *md,
569 * @return NULL if no entry was found 565 * @return NULL if no entry was found
570 */ 566 */
571char * 567char *
572GNUNET_CONTAINER_meta_data_get_by_type (const struct GNUNET_CONTAINER_MetaData *md, 568GNUNET_CONTAINER_meta_data_get_by_type(const struct GNUNET_CONTAINER_MetaData *md,
573 enum EXTRACTOR_MetaType type) 569 enum EXTRACTOR_MetaType type)
574{ 570{
575 struct MetaItem *pos; 571 struct MetaItem *pos;
576 572
@@ -580,7 +576,7 @@ GNUNET_CONTAINER_meta_data_get_by_type (const struct GNUNET_CONTAINER_MetaData *
580 if ((type == pos->type) && 576 if ((type == pos->type) &&
581 ((pos->format == EXTRACTOR_METAFORMAT_UTF8) || 577 ((pos->format == EXTRACTOR_METAFORMAT_UTF8) ||
582 (pos->format == EXTRACTOR_METAFORMAT_C_STRING))) 578 (pos->format == EXTRACTOR_METAFORMAT_C_STRING)))
583 return GNUNET_strdup (pos->data); 579 return GNUNET_strdup(pos->data);
584 return NULL; 580 return NULL;
585} 581}
586 582
@@ -597,9 +593,9 @@ GNUNET_CONTAINER_meta_data_get_by_type (const struct GNUNET_CONTAINER_MetaData *
597 * otherwise client is responsible for freeing the value! 593 * otherwise client is responsible for freeing the value!
598 */ 594 */
599char * 595char *
600GNUNET_CONTAINER_meta_data_get_first_by_types (const struct 596GNUNET_CONTAINER_meta_data_get_first_by_types(const struct
601 GNUNET_CONTAINER_MetaData *md, 597 GNUNET_CONTAINER_MetaData *md,
602 ...) 598 ...)
603{ 599{
604 char *ret; 600 char *ret;
605 va_list args; 601 va_list args;
@@ -608,16 +604,16 @@ GNUNET_CONTAINER_meta_data_get_first_by_types (const struct
608 if (NULL == md) 604 if (NULL == md)
609 return NULL; 605 return NULL;
610 ret = NULL; 606 ret = NULL;
611 va_start (args, md); 607 va_start(args, md);
612 while (1) 608 while (1)
613 { 609 {
614 type = va_arg (args, int); 610 type = va_arg(args, int);
615 if (-1 == type) 611 if (-1 == type)
616 break; 612 break;
617 if (NULL != (ret = GNUNET_CONTAINER_meta_data_get_by_type (md, type))) 613 if (NULL != (ret = GNUNET_CONTAINER_meta_data_get_by_type(md, type)))
618 break; 614 break;
619 } 615 }
620 va_end (args); 616 va_end(args);
621 return ret; 617 return ret;
622} 618}
623 619
@@ -631,8 +627,8 @@ GNUNET_CONTAINER_meta_data_get_first_by_types (const struct
631 * @return number of bytes in thumbnail, 0 if not available 627 * @return number of bytes in thumbnail, 0 if not available
632 */ 628 */
633size_t 629size_t
634GNUNET_CONTAINER_meta_data_get_thumbnail (const struct GNUNET_CONTAINER_MetaData 630GNUNET_CONTAINER_meta_data_get_thumbnail(const struct GNUNET_CONTAINER_MetaData
635 * md, unsigned char **thumb) 631 * md, unsigned char **thumb)
636{ 632{
637 struct MetaItem *pos; 633 struct MetaItem *pos;
638 struct MetaItem *match; 634 struct MetaItem *match;
@@ -641,22 +637,22 @@ GNUNET_CONTAINER_meta_data_get_thumbnail (const struct GNUNET_CONTAINER_MetaData
641 return 0; 637 return 0;
642 match = NULL; 638 match = NULL;
643 for (pos = md->items_head; NULL != pos; pos = pos->next) 639 for (pos = md->items_head; NULL != pos; pos = pos->next)
644 {
645 if ((NULL != pos->mime_type) &&
646 (0 == strncasecmp ("image/", pos->mime_type, strlen ("image/"))) &&
647 (EXTRACTOR_METAFORMAT_BINARY == pos->format))
648 { 640 {
649 if (NULL == match) 641 if ((NULL != pos->mime_type) &&
650 match = pos; 642 (0 == strncasecmp("image/", pos->mime_type, strlen("image/"))) &&
651 else if ((match->type != EXTRACTOR_METATYPE_THUMBNAIL) && 643 (EXTRACTOR_METAFORMAT_BINARY == pos->format))
652 (pos->type == EXTRACTOR_METATYPE_THUMBNAIL)) 644 {
653 match = pos; 645 if (NULL == match)
646 match = pos;
647 else if ((match->type != EXTRACTOR_METATYPE_THUMBNAIL) &&
648 (pos->type == EXTRACTOR_METATYPE_THUMBNAIL))
649 match = pos;
650 }
654 } 651 }
655 }
656 if ((NULL == match) || (0 == match->data_size)) 652 if ((NULL == match) || (0 == match->data_size))
657 return 0; 653 return 0;
658 *thumb = GNUNET_malloc (match->data_size); 654 *thumb = GNUNET_malloc(match->data_size);
659 GNUNET_memcpy (*thumb, match->data, match->data_size); 655 GNUNET_memcpy(*thumb, match->data, match->data_size);
660 return match->data_size; 656 return match->data_size;
661} 657}
662 658
@@ -668,19 +664,19 @@ GNUNET_CONTAINER_meta_data_get_thumbnail (const struct GNUNET_CONTAINER_MetaData
668 * @return duplicate meta-data container 664 * @return duplicate meta-data container
669 */ 665 */
670struct GNUNET_CONTAINER_MetaData * 666struct GNUNET_CONTAINER_MetaData *
671GNUNET_CONTAINER_meta_data_duplicate (const struct GNUNET_CONTAINER_MetaData 667GNUNET_CONTAINER_meta_data_duplicate(const struct GNUNET_CONTAINER_MetaData
672 *md) 668 *md)
673{ 669{
674 struct GNUNET_CONTAINER_MetaData *ret; 670 struct GNUNET_CONTAINER_MetaData *ret;
675 struct MetaItem *pos; 671 struct MetaItem *pos;
676 672
677 if (NULL == md) 673 if (NULL == md)
678 return NULL; 674 return NULL;
679 ret = GNUNET_CONTAINER_meta_data_create (); 675 ret = GNUNET_CONTAINER_meta_data_create();
680 for (pos = md->items_tail; NULL != pos; pos = pos->prev) 676 for (pos = md->items_tail; NULL != pos; pos = pos->prev)
681 GNUNET_CONTAINER_meta_data_insert (ret, pos->plugin_name, pos->type, 677 GNUNET_CONTAINER_meta_data_insert(ret, pos->plugin_name, pos->type,
682 pos->format, pos->mime_type, pos->data, 678 pos->format, pos->mime_type, pos->data,
683 pos->data_size); 679 pos->data_size);
684 return ret; 680 return ret;
685} 681}
686 682
@@ -700,8 +696,7 @@ GNUNET_CONTAINER_meta_data_duplicate (const struct GNUNET_CONTAINER_MetaData
700/** 696/**
701 * Header for serialized meta data. 697 * Header for serialized meta data.
702 */ 698 */
703struct MetaDataHeader 699struct MetaDataHeader {
704{
705 /** 700 /**
706 * The version of the MD serialization. The highest bit is used to 701 * The version of the MD serialization. The highest bit is used to
707 * indicate compression. 702 * indicate compression.
@@ -734,8 +729,7 @@ struct MetaDataHeader
734/** 729/**
735 * Entry of serialized meta data. 730 * Entry of serialized meta data.
736 */ 731 */
737struct MetaDataEntry 732struct MetaDataEntry {
738{
739 /** 733 /**
740 * Meta data type. Corresponds to an 'enum EXTRACTOR_MetaType' 734 * Meta data type. Corresponds to an 'enum EXTRACTOR_MetaType'
741 */ 735 */
@@ -760,7 +754,6 @@ struct MetaDataEntry
760 * Number of bytes in the mime type including 0-terminator. 0 for NULL. 754 * Number of bytes in the mime type including 0-terminator. 0 for NULL.
761 */ 755 */
762 uint32_t mime_type_len; 756 uint32_t mime_type_len;
763
764}; 757};
765 758
766 759
@@ -779,11 +772,11 @@ struct MetaDataEntry
779 * space) 772 * space)
780 */ 773 */
781ssize_t 774ssize_t
782GNUNET_CONTAINER_meta_data_serialize (const struct GNUNET_CONTAINER_MetaData 775GNUNET_CONTAINER_meta_data_serialize(const struct GNUNET_CONTAINER_MetaData
783 *md, char **target, size_t max, 776 *md, char **target, size_t max,
784 enum 777 enum
785 GNUNET_CONTAINER_MetaDataSerializationOptions 778 GNUNET_CONTAINER_MetaDataSerializationOptions
786 opt) 779 opt)
787{ 780{
788 struct GNUNET_CONTAINER_MetaData *vmd; 781 struct GNUNET_CONTAINER_MetaData *vmd;
789 struct MetaItem *pos; 782 struct MetaItem *pos;
@@ -804,195 +797,195 @@ GNUNET_CONTAINER_meta_data_serialize (const struct GNUNET_CONTAINER_MetaData
804 size_t rlen; 797 size_t rlen;
805 int comp; 798 int comp;
806 799
807 if (max < sizeof (struct MetaDataHeader)) 800 if (max < sizeof(struct MetaDataHeader))
808 return GNUNET_SYSERR; /* far too small */ 801 return GNUNET_SYSERR; /* far too small */
809 if (NULL == md) 802 if (NULL == md)
810 return 0; 803 return 0;
811 804
812 if (NULL != md->sbuf) 805 if (NULL != md->sbuf)
813 {
814 /* try to use serialization cache */
815 if (md->sbuf_size <= max)
816 { 806 {
817 if (NULL == *target) 807 /* try to use serialization cache */
818 *target = GNUNET_malloc (md->sbuf_size); 808 if (md->sbuf_size <= max)
819 GNUNET_memcpy (*target, md->sbuf, md->sbuf_size); 809 {
820 return md->sbuf_size; 810 if (NULL == *target)
811 *target = GNUNET_malloc(md->sbuf_size);
812 GNUNET_memcpy(*target, md->sbuf, md->sbuf_size);
813 return md->sbuf_size;
814 }
815 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_PART))
816 return GNUNET_SYSERR; /* can say that this will fail */
817 /* need to compute a partial serialization, sbuf useless ... */
821 } 818 }
822 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_PART))
823 return GNUNET_SYSERR; /* can say that this will fail */
824 /* need to compute a partial serialization, sbuf useless ... */
825 }
826 dst = NULL; 819 dst = NULL;
827 msize = 0; 820 msize = 0;
828 for (pos = md->items_tail; NULL != pos; pos = pos->prev) 821 for (pos = md->items_tail; NULL != pos; pos = pos->prev)
829 { 822 {
830 msize += sizeof (struct MetaDataEntry); 823 msize += sizeof(struct MetaDataEntry);
831 msize += pos->data_size; 824 msize += pos->data_size;
832 if (NULL != pos->plugin_name) 825 if (NULL != pos->plugin_name)
833 msize += strlen (pos->plugin_name) + 1; 826 msize += strlen(pos->plugin_name) + 1;
834 if (NULL != pos->mime_type) 827 if (NULL != pos->mime_type)
835 msize += strlen (pos->mime_type) + 1; 828 msize += strlen(pos->mime_type) + 1;
836 } 829 }
837 size = (size_t) msize; 830 size = (size_t)msize;
838 if (size != msize) 831 if (size != msize)
839 { 832 {
840 GNUNET_break (0); /* integer overflow */ 833 GNUNET_break(0); /* integer overflow */
841 return GNUNET_SYSERR; 834 return GNUNET_SYSERR;
842 } 835 }
843 if (size >= GNUNET_MAX_MALLOC_CHECKED) 836 if (size >= GNUNET_MAX_MALLOC_CHECKED)
844 { 837 {
845 /* too large to be processed */ 838 /* too large to be processed */
846 return GNUNET_SYSERR; 839 return GNUNET_SYSERR;
847 } 840 }
848 ent = GNUNET_malloc (size); 841 ent = GNUNET_malloc(size);
849 mdata = (char *) &ent[md->item_count]; 842 mdata = (char *)&ent[md->item_count];
850 off = size - (md->item_count * sizeof (struct MetaDataEntry)); 843 off = size - (md->item_count * sizeof(struct MetaDataEntry));
851 i = 0; 844 i = 0;
852 for (pos = md->items_head; NULL != pos; pos = pos->next) 845 for (pos = md->items_head; NULL != pos; pos = pos->next)
853 { 846 {
854 ent[i].type = htonl ((uint32_t) pos->type); 847 ent[i].type = htonl((uint32_t)pos->type);
855 ent[i].format = htonl ((uint32_t) pos->format); 848 ent[i].format = htonl((uint32_t)pos->format);
856 ent[i].data_size = htonl ((uint32_t) pos->data_size); 849 ent[i].data_size = htonl((uint32_t)pos->data_size);
857 if (NULL == pos->plugin_name) 850 if (NULL == pos->plugin_name)
858 plen = 0; 851 plen = 0;
859 else 852 else
860 plen = strlen (pos->plugin_name) + 1; 853 plen = strlen(pos->plugin_name) + 1;
861 ent[i].plugin_name_len = htonl ((uint32_t) plen); 854 ent[i].plugin_name_len = htonl((uint32_t)plen);
862 if (NULL == pos->mime_type) 855 if (NULL == pos->mime_type)
863 mlen = 0; 856 mlen = 0;
864 else 857 else
865 mlen = strlen (pos->mime_type) + 1; 858 mlen = strlen(pos->mime_type) + 1;
866 ent[i].mime_type_len = htonl ((uint32_t) mlen); 859 ent[i].mime_type_len = htonl((uint32_t)mlen);
867 off -= pos->data_size; 860 off -= pos->data_size;
868 if ((EXTRACTOR_METAFORMAT_UTF8 == pos->format) || 861 if ((EXTRACTOR_METAFORMAT_UTF8 == pos->format) ||
869 (EXTRACTOR_METAFORMAT_C_STRING == pos->format)) 862 (EXTRACTOR_METAFORMAT_C_STRING == pos->format))
870 GNUNET_break ('\0' == pos->data[pos->data_size - 1]); 863 GNUNET_break('\0' == pos->data[pos->data_size - 1]);
871 GNUNET_memcpy (&mdata[off], pos->data, pos->data_size); 864 GNUNET_memcpy(&mdata[off], pos->data, pos->data_size);
872 off -= plen; 865 off -= plen;
873 if (NULL != pos->plugin_name) 866 if (NULL != pos->plugin_name)
874 GNUNET_memcpy (&mdata[off], pos->plugin_name, plen); 867 GNUNET_memcpy(&mdata[off], pos->plugin_name, plen);
875 off -= mlen; 868 off -= mlen;
876 if (NULL != pos->mime_type) 869 if (NULL != pos->mime_type)
877 GNUNET_memcpy (&mdata[off], pos->mime_type, mlen); 870 GNUNET_memcpy(&mdata[off], pos->mime_type, mlen);
878 i++; 871 i++;
879 } 872 }
880 GNUNET_assert (0 == off); 873 GNUNET_assert(0 == off);
881 874
882 clen = 0; 875 clen = 0;
883 cdata = NULL; 876 cdata = NULL;
884 left = size; 877 left = size;
885 i = 0; 878 i = 0;
886 for (pos = md->items_head; NULL != pos; pos = pos->next) 879 for (pos = md->items_head; NULL != pos; pos = pos->next)
887 {
888 comp = GNUNET_NO;
889 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_NO_COMPRESS))
890 comp = GNUNET_try_compression ((const char *) &ent[i],
891 left,
892 &cdata,
893 &clen);
894
895 if ((NULL == md->sbuf) && (0 == i))
896 { 880 {
897 /* fill 'sbuf'; this "modifies" md, but since this is only 881 comp = GNUNET_NO;
898 * an internal cache we will cast away the 'const' instead 882 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_NO_COMPRESS))
899 * of making the API look strange. */ 883 comp = GNUNET_try_compression((const char *)&ent[i],
900 vmd = (struct GNUNET_CONTAINER_MetaData *) md; 884 left,
901 hdr = GNUNET_malloc (left + sizeof (struct MetaDataHeader)); 885 &cdata,
902 hdr->size = htonl (left); 886 &clen);
903 hdr->entries = htonl (md->item_count); 887
904 if (GNUNET_YES == comp) 888 if ((NULL == md->sbuf) && (0 == i))
905 { 889 {
906 GNUNET_assert (clen < left); 890 /* fill 'sbuf'; this "modifies" md, but since this is only
907 hdr->version = htonl (2 | HEADER_COMPRESSED); 891 * an internal cache we will cast away the 'const' instead
908 GNUNET_memcpy (&hdr[1], cdata, clen); 892 * of making the API look strange. */
909 vmd->sbuf_size = clen + sizeof (struct MetaDataHeader); 893 vmd = (struct GNUNET_CONTAINER_MetaData *)md;
910 } 894 hdr = GNUNET_malloc(left + sizeof(struct MetaDataHeader));
911 else 895 hdr->size = htonl(left);
912 { 896 hdr->entries = htonl(md->item_count);
913 hdr->version = htonl (2); 897 if (GNUNET_YES == comp)
914 GNUNET_memcpy (&hdr[1], &ent[0], left); 898 {
915 vmd->sbuf_size = left + sizeof (struct MetaDataHeader); 899 GNUNET_assert(clen < left);
916 } 900 hdr->version = htonl(2 | HEADER_COMPRESSED);
917 vmd->sbuf = (char *) hdr; 901 GNUNET_memcpy(&hdr[1], cdata, clen);
902 vmd->sbuf_size = clen + sizeof(struct MetaDataHeader);
903 }
904 else
905 {
906 hdr->version = htonl(2);
907 GNUNET_memcpy(&hdr[1], &ent[0], left);
908 vmd->sbuf_size = left + sizeof(struct MetaDataHeader);
909 }
910 vmd->sbuf = (char *)hdr;
911 }
912
913 if (((left + sizeof(struct MetaDataHeader)) <= max) ||
914 ((GNUNET_YES == comp) && (clen <= max)))
915 {
916 /* success, this now fits! */
917 if (GNUNET_YES == comp)
918 {
919 if (NULL == dst)
920 dst = GNUNET_malloc(clen + sizeof(struct MetaDataHeader));
921 hdr = (struct MetaDataHeader *)dst;
922 hdr->version = htonl(2 | HEADER_COMPRESSED);
923 hdr->size = htonl(left);
924 hdr->entries = htonl(md->item_count - i);
925 GNUNET_memcpy(&dst[sizeof(struct MetaDataHeader)], cdata, clen);
926 GNUNET_free(cdata);
927 cdata = NULL;
928 GNUNET_free(ent);
929 rlen = clen + sizeof(struct MetaDataHeader);
930 }
931 else
932 {
933 if (NULL == dst)
934 dst = GNUNET_malloc(left + sizeof(struct MetaDataHeader));
935 hdr = (struct MetaDataHeader *)dst;
936 hdr->version = htonl(2);
937 hdr->entries = htonl(md->item_count - i);
938 hdr->size = htonl(left);
939 GNUNET_memcpy(&dst[sizeof(struct MetaDataHeader)], &ent[i], left);
940 GNUNET_free(ent);
941 rlen = left + sizeof(struct MetaDataHeader);
942 }
943 if (NULL != *target)
944 {
945 if (GNUNET_YES == comp)
946 GNUNET_memcpy(*target, dst, clen + sizeof(struct MetaDataHeader));
947 else
948 GNUNET_memcpy(*target, dst, left + sizeof(struct MetaDataHeader));
949 GNUNET_free(dst);
950 }
951 else
952 {
953 *target = dst;
954 }
955 return rlen;
956 }
957
958 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_PART))
959 {
960 /* does not fit! */
961 GNUNET_free(ent);
962 return GNUNET_SYSERR;
963 }
964
965 /* next iteration: ignore the corresponding meta data at the
966 * end and try again without it */
967 left -= sizeof(struct MetaDataEntry);
968 left -= pos->data_size;
969 if (NULL != pos->plugin_name)
970 left -= strlen(pos->plugin_name) + 1;
971 if (NULL != pos->mime_type)
972 left -= strlen(pos->mime_type) + 1;
973
974 GNUNET_free_non_null(cdata);
975 cdata = NULL;
976
977 i++;
918 } 978 }
919 979 GNUNET_free(ent);
920 if (((left + sizeof (struct MetaDataHeader)) <= max) ||
921 ((GNUNET_YES == comp) && (clen <= max)))
922 {
923 /* success, this now fits! */
924 if (GNUNET_YES == comp)
925 {
926 if (NULL == dst)
927 dst = GNUNET_malloc (clen + sizeof (struct MetaDataHeader));
928 hdr = (struct MetaDataHeader *) dst;
929 hdr->version = htonl (2 | HEADER_COMPRESSED);
930 hdr->size = htonl (left);
931 hdr->entries = htonl (md->item_count - i);
932 GNUNET_memcpy (&dst[sizeof (struct MetaDataHeader)], cdata, clen);
933 GNUNET_free (cdata);
934 cdata = NULL;
935 GNUNET_free (ent);
936 rlen = clen + sizeof (struct MetaDataHeader);
937 }
938 else
939 {
940 if (NULL == dst)
941 dst = GNUNET_malloc (left + sizeof (struct MetaDataHeader));
942 hdr = (struct MetaDataHeader *) dst;
943 hdr->version = htonl (2);
944 hdr->entries = htonl (md->item_count - i);
945 hdr->size = htonl (left);
946 GNUNET_memcpy (&dst[sizeof (struct MetaDataHeader)], &ent[i], left);
947 GNUNET_free (ent);
948 rlen = left + sizeof (struct MetaDataHeader);
949 }
950 if (NULL != *target)
951 {
952 if (GNUNET_YES == comp)
953 GNUNET_memcpy (*target, dst, clen + sizeof (struct MetaDataHeader));
954 else
955 GNUNET_memcpy (*target, dst, left + sizeof (struct MetaDataHeader));
956 GNUNET_free (dst);
957 }
958 else
959 {
960 *target = dst;
961 }
962 return rlen;
963 }
964
965 if (0 == (opt & GNUNET_CONTAINER_META_DATA_SERIALIZE_PART))
966 {
967 /* does not fit! */
968 GNUNET_free (ent);
969 return GNUNET_SYSERR;
970 }
971
972 /* next iteration: ignore the corresponding meta data at the
973 * end and try again without it */
974 left -= sizeof (struct MetaDataEntry);
975 left -= pos->data_size;
976 if (NULL != pos->plugin_name)
977 left -= strlen (pos->plugin_name) + 1;
978 if (NULL != pos->mime_type)
979 left -= strlen (pos->mime_type) + 1;
980
981 GNUNET_free_non_null (cdata);
982 cdata = NULL;
983
984 i++;
985 }
986 GNUNET_free (ent);
987 980
988 /* nothing fit, only write header! */ 981 /* nothing fit, only write header! */
989 ihdr.version = htonl (2); 982 ihdr.version = htonl(2);
990 ihdr.entries = htonl (0); 983 ihdr.entries = htonl(0);
991 ihdr.size = htonl (0); 984 ihdr.size = htonl(0);
992 if (NULL == *target) 985 if (NULL == *target)
993 *target = (char *) GNUNET_new (struct MetaDataHeader); 986 *target = (char *)GNUNET_new(struct MetaDataHeader);
994 GNUNET_memcpy (*target, &ihdr, sizeof (struct MetaDataHeader)); 987 GNUNET_memcpy(*target, &ihdr, sizeof(struct MetaDataHeader));
995 return sizeof (struct MetaDataHeader); 988 return sizeof(struct MetaDataHeader);
996} 989}
997 990
998 991
@@ -1003,8 +996,8 @@ GNUNET_CONTAINER_meta_data_serialize (const struct GNUNET_CONTAINER_MetaData
1003 * @return number of bytes needed for serialization, -1 on error 996 * @return number of bytes needed for serialization, -1 on error
1004 */ 997 */
1005ssize_t 998ssize_t
1006GNUNET_CONTAINER_meta_data_get_serialized_size (const struct 999GNUNET_CONTAINER_meta_data_get_serialized_size(const struct
1007 GNUNET_CONTAINER_MetaData *md) 1000 GNUNET_CONTAINER_MetaData *md)
1008{ 1001{
1009 ssize_t ret; 1002 ssize_t ret;
1010 char *ptr; 1003 char *ptr;
@@ -1013,10 +1006,10 @@ GNUNET_CONTAINER_meta_data_get_serialized_size (const struct
1013 return md->sbuf_size; 1006 return md->sbuf_size;
1014 ptr = NULL; 1007 ptr = NULL;
1015 ret = 1008 ret =
1016 GNUNET_CONTAINER_meta_data_serialize (md, &ptr, GNUNET_MAX_MALLOC_CHECKED, 1009 GNUNET_CONTAINER_meta_data_serialize(md, &ptr, GNUNET_MAX_MALLOC_CHECKED,
1017 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL); 1010 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
1018 if (-1 != ret) 1011 if (-1 != ret)
1019 GNUNET_free (ptr); 1012 GNUNET_free(ptr);
1020 return ret; 1013 return ret;
1021} 1014}
1022 1015
@@ -1030,7 +1023,7 @@ GNUNET_CONTAINER_meta_data_get_serialized_size (const struct
1030 * bad format) 1023 * bad format)
1031 */ 1024 */
1032struct GNUNET_CONTAINER_MetaData * 1025struct GNUNET_CONTAINER_MetaData *
1033GNUNET_CONTAINER_meta_data_deserialize (const char *input, size_t size) 1026GNUNET_CONTAINER_meta_data_deserialize(const char *input, size_t size)
1034{ 1027{
1035 struct GNUNET_CONTAINER_MetaData *md; 1028 struct GNUNET_CONTAINER_MetaData *md;
1036 struct MetaDataHeader hdr; 1029 struct MetaDataHeader hdr;
@@ -1052,137 +1045,137 @@ GNUNET_CONTAINER_meta_data_deserialize (const char *input, size_t size)
1052 const char *mime_type; 1045 const char *mime_type;
1053 enum EXTRACTOR_MetaFormat format; 1046 enum EXTRACTOR_MetaFormat format;
1054 1047
1055 if (size < sizeof (struct MetaDataHeader)) 1048 if (size < sizeof(struct MetaDataHeader))
1056 return NULL; 1049 return NULL;
1057 GNUNET_memcpy (&hdr, input, sizeof (struct MetaDataHeader)); 1050 GNUNET_memcpy(&hdr, input, sizeof(struct MetaDataHeader));
1058 version = ntohl (hdr.version) & HEADER_VERSION_MASK; 1051 version = ntohl(hdr.version) & HEADER_VERSION_MASK;
1059 compressed = (ntohl (hdr.version) & HEADER_COMPRESSED) != 0; 1052 compressed = (ntohl(hdr.version) & HEADER_COMPRESSED) != 0;
1060 1053
1061 if (1 == version) 1054 if (1 == version)
1062 return NULL; /* null pointer */ 1055 return NULL; /* null pointer */
1063 if (2 != version) 1056 if (2 != version)
1064 {
1065 GNUNET_break_op (0); /* unsupported version */
1066 return NULL;
1067 }
1068
1069 ic = ntohl (hdr.entries);
1070 dataSize = ntohl (hdr.size);
1071 if ( ((sizeof (struct MetaDataEntry) * ic) > dataSize) ||
1072 ( (0 != ic) &&
1073 (dataSize / ic < sizeof (struct MetaDataEntry)) ) )
1074 {
1075 GNUNET_break_op (0);
1076 return NULL;
1077 }
1078
1079 if (compressed)
1080 {
1081 if (dataSize >= GNUNET_MAX_MALLOC_CHECKED)
1082 { 1057 {
1083 /* make sure we don't blow our memory limit because of a mal-formed 1058 GNUNET_break_op(0); /* unsupported version */
1084 * message... */
1085 GNUNET_break_op (0);
1086 return NULL; 1059 return NULL;
1087 } 1060 }
1088 data = 1061
1089 GNUNET_decompress ((const char *) &input[sizeof (struct MetaDataHeader)], 1062 ic = ntohl(hdr.entries);
1090 size - sizeof (struct MetaDataHeader), 1063 dataSize = ntohl(hdr.size);
1091 dataSize); 1064 if (((sizeof(struct MetaDataEntry) * ic) > dataSize) ||
1092 if (NULL == data) 1065 ((0 != ic) &&
1093 { 1066 (dataSize / ic < sizeof(struct MetaDataEntry))))
1094 GNUNET_break_op (0);
1095 return NULL;
1096 }
1097 cdata = data;
1098 }
1099 else
1100 {
1101 data = NULL;
1102 cdata = (const char *) &input[sizeof (struct MetaDataHeader)];
1103 if (dataSize != size - sizeof (struct MetaDataHeader))
1104 { 1067 {
1105 GNUNET_break_op (0); 1068 GNUNET_break_op(0);
1106 return NULL; 1069 return NULL;
1107 } 1070 }
1108 }
1109 1071
1110 md = GNUNET_CONTAINER_meta_data_create (); 1072 if (compressed)
1111 left = dataSize - ic * sizeof (struct MetaDataEntry);
1112 mdata = &cdata[ic * sizeof (struct MetaDataEntry)];
1113 for (i = 0; i < ic; i++)
1114 {
1115 GNUNET_memcpy (&ent, &cdata[i * sizeof (struct MetaDataEntry)],
1116 sizeof (struct MetaDataEntry));
1117 format = (enum EXTRACTOR_MetaFormat) ntohl (ent.format);
1118 if ((EXTRACTOR_METAFORMAT_UTF8 != format) &&
1119 (EXTRACTOR_METAFORMAT_C_STRING != format) &&
1120 (EXTRACTOR_METAFORMAT_BINARY != format))
1121 {
1122 GNUNET_break_op (0);
1123 break;
1124 }
1125 dlen = ntohl (ent.data_size);
1126 plen = ntohl (ent.plugin_name_len);
1127 mlen = ntohl (ent.mime_type_len);
1128 if (dlen > left)
1129 {
1130 GNUNET_break_op (0);
1131 break;
1132 }
1133 left -= dlen;
1134 meta_data = &mdata[left];
1135 if ((EXTRACTOR_METAFORMAT_UTF8 == format) ||
1136 (EXTRACTOR_METAFORMAT_C_STRING == format))
1137 {
1138 if (0 == dlen)
1139 {
1140 GNUNET_break_op (0);
1141 break;
1142 }
1143 if ('\0' != meta_data[dlen - 1])
1144 {
1145 GNUNET_break_op (0);
1146 break;
1147 }
1148 }
1149 if (plen > left)
1150 { 1073 {
1151 GNUNET_break_op (0); 1074 if (dataSize >= GNUNET_MAX_MALLOC_CHECKED)
1152 break; 1075 {
1076 /* make sure we don't blow our memory limit because of a mal-formed
1077 * message... */
1078 GNUNET_break_op(0);
1079 return NULL;
1080 }
1081 data =
1082 GNUNET_decompress((const char *)&input[sizeof(struct MetaDataHeader)],
1083 size - sizeof(struct MetaDataHeader),
1084 dataSize);
1085 if (NULL == data)
1086 {
1087 GNUNET_break_op(0);
1088 return NULL;
1089 }
1090 cdata = data;
1153 } 1091 }
1154 left -= plen; 1092 else
1155 if ((plen > 0) && ('\0' != mdata[left + plen - 1]))
1156 { 1093 {
1157 GNUNET_break_op (0); 1094 data = NULL;
1158 break; 1095 cdata = (const char *)&input[sizeof(struct MetaDataHeader)];
1096 if (dataSize != size - sizeof(struct MetaDataHeader))
1097 {
1098 GNUNET_break_op(0);
1099 return NULL;
1100 }
1159 } 1101 }
1160 if (0 == plen)
1161 plugin_name = NULL;
1162 else
1163 plugin_name = &mdata[left];
1164 1102
1165 if (mlen > left) 1103 md = GNUNET_CONTAINER_meta_data_create();
1166 { 1104 left = dataSize - ic * sizeof(struct MetaDataEntry);
1167 GNUNET_break_op (0); 1105 mdata = &cdata[ic * sizeof(struct MetaDataEntry)];
1168 break; 1106 for (i = 0; i < ic; i++)
1169 }
1170 left -= mlen;
1171 if ((mlen > 0) && ('\0' != mdata[left + mlen - 1]))
1172 { 1107 {
1173 GNUNET_break_op (0); 1108 GNUNET_memcpy(&ent, &cdata[i * sizeof(struct MetaDataEntry)],
1174 break; 1109 sizeof(struct MetaDataEntry));
1110 format = (enum EXTRACTOR_MetaFormat)ntohl(ent.format);
1111 if ((EXTRACTOR_METAFORMAT_UTF8 != format) &&
1112 (EXTRACTOR_METAFORMAT_C_STRING != format) &&
1113 (EXTRACTOR_METAFORMAT_BINARY != format))
1114 {
1115 GNUNET_break_op(0);
1116 break;
1117 }
1118 dlen = ntohl(ent.data_size);
1119 plen = ntohl(ent.plugin_name_len);
1120 mlen = ntohl(ent.mime_type_len);
1121 if (dlen > left)
1122 {
1123 GNUNET_break_op(0);
1124 break;
1125 }
1126 left -= dlen;
1127 meta_data = &mdata[left];
1128 if ((EXTRACTOR_METAFORMAT_UTF8 == format) ||
1129 (EXTRACTOR_METAFORMAT_C_STRING == format))
1130 {
1131 if (0 == dlen)
1132 {
1133 GNUNET_break_op(0);
1134 break;
1135 }
1136 if ('\0' != meta_data[dlen - 1])
1137 {
1138 GNUNET_break_op(0);
1139 break;
1140 }
1141 }
1142 if (plen > left)
1143 {
1144 GNUNET_break_op(0);
1145 break;
1146 }
1147 left -= plen;
1148 if ((plen > 0) && ('\0' != mdata[left + plen - 1]))
1149 {
1150 GNUNET_break_op(0);
1151 break;
1152 }
1153 if (0 == plen)
1154 plugin_name = NULL;
1155 else
1156 plugin_name = &mdata[left];
1157
1158 if (mlen > left)
1159 {
1160 GNUNET_break_op(0);
1161 break;
1162 }
1163 left -= mlen;
1164 if ((mlen > 0) && ('\0' != mdata[left + mlen - 1]))
1165 {
1166 GNUNET_break_op(0);
1167 break;
1168 }
1169 if (0 == mlen)
1170 mime_type = NULL;
1171 else
1172 mime_type = &mdata[left];
1173 GNUNET_CONTAINER_meta_data_insert(md, plugin_name,
1174 (enum EXTRACTOR_MetaType)
1175 ntohl(ent.type), format, mime_type,
1176 meta_data, dlen);
1175 } 1177 }
1176 if (0 == mlen) 1178 GNUNET_free_non_null(data);
1177 mime_type = NULL;
1178 else
1179 mime_type = &mdata[left];
1180 GNUNET_CONTAINER_meta_data_insert (md, plugin_name,
1181 (enum EXTRACTOR_MetaType)
1182 ntohl (ent.type), format, mime_type,
1183 meta_data, dlen);
1184 }
1185 GNUNET_free_non_null (data);
1186 return md; 1179 return md;
1187} 1180}
1188 1181
diff --git a/src/util/container_multihashmap.c b/src/util/container_multihashmap.c
index bcf6dccf0..62e5311d8 100644
--- a/src/util/container_multihashmap.c
+++ b/src/util/container_multihashmap.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_multihashmap.c 21 * @file util/container_multihashmap.c
22 * @brief hash map where the same key may be present multiple times 22 * @brief hash map where the same key may be present multiple times
@@ -27,7 +27,7 @@
27#include "gnunet_container_lib.h" 27#include "gnunet_container_lib.h"
28 28
29#define LOG(kind, ...) \ 29#define LOG(kind, ...) \
30 GNUNET_log_from (kind, "util-container-multihashmap", __VA_ARGS__) 30 GNUNET_log_from(kind, "util-container-multihashmap", __VA_ARGS__)
31 31
32/** 32/**
33 * Maximum recursion depth for callbacks of 33 * Maximum recursion depth for callbacks of
@@ -41,9 +41,7 @@
41/** 41/**
42 * An entry in the hash map with the full key. 42 * An entry in the hash map with the full key.
43 */ 43 */
44struct BigMapEntry 44struct BigMapEntry {
45{
46
47 /** 45 /**
48 * Value of the entry. 46 * Value of the entry.
49 */ 47 */
@@ -64,9 +62,7 @@ struct BigMapEntry
64/** 62/**
65 * An entry in the hash map with just a pointer to the key. 63 * An entry in the hash map with just a pointer to the key.
66 */ 64 */
67struct SmallMapEntry 65struct SmallMapEntry {
68{
69
70 /** 66 /**
71 * Value of the entry. 67 * Value of the entry.
72 */ 68 */
@@ -87,8 +83,7 @@ struct SmallMapEntry
87/** 83/**
88 * Entry in the map. 84 * Entry in the map.
89 */ 85 */
90union MapEntry 86union MapEntry {
91{
92 /** 87 /**
93 * Variant used if map entries only contain a pointer to the key. 88 * Variant used if map entries only contain a pointer to the key.
94 */ 89 */
@@ -104,8 +99,7 @@ union MapEntry
104/** 99/**
105 * Internal representation of the hash map. 100 * Internal representation of the hash map.
106 */ 101 */
107struct GNUNET_CONTAINER_MultiHashMap 102struct GNUNET_CONTAINER_MultiHashMap {
108{
109 /** 103 /**
110 * All of our buckets. 104 * All of our buckets.
111 */ 105 */
@@ -152,8 +146,7 @@ struct GNUNET_CONTAINER_MultiHashMap
152 * Cursor into a multihashmap. 146 * Cursor into a multihashmap.
153 * Allows to enumerate elements asynchronously. 147 * Allows to enumerate elements asynchronously.
154 */ 148 */
155struct GNUNET_CONTAINER_MultiHashMapIterator 149struct GNUNET_CONTAINER_MultiHashMapIterator {
156{
157 /** 150 /**
158 * Position in the bucket @e idx 151 * Position in the bucket @e idx
159 */ 152 */
@@ -193,34 +186,34 @@ struct GNUNET_CONTAINER_MultiHashMapIterator
193 * @return NULL on error 186 * @return NULL on error
194 */ 187 */
195struct GNUNET_CONTAINER_MultiHashMap * 188struct GNUNET_CONTAINER_MultiHashMap *
196GNUNET_CONTAINER_multihashmap_create (unsigned int len, int do_not_copy_keys) 189GNUNET_CONTAINER_multihashmap_create(unsigned int len, int do_not_copy_keys)
197{ 190{
198 struct GNUNET_CONTAINER_MultiHashMap *hm; 191 struct GNUNET_CONTAINER_MultiHashMap *hm;
199 192
200 GNUNET_assert (len > 0); 193 GNUNET_assert(len > 0);
201 hm = GNUNET_new (struct GNUNET_CONTAINER_MultiHashMap); 194 hm = GNUNET_new(struct GNUNET_CONTAINER_MultiHashMap);
202 if (len * sizeof (union MapEntry) > GNUNET_MAX_MALLOC_CHECKED) 195 if (len * sizeof(union MapEntry) > GNUNET_MAX_MALLOC_CHECKED)
203 {
204 size_t s;
205 /* application *explicitly* requested very large map, hopefully
206 it checks the return value... */
207 s = len * sizeof (union MapEntry);
208 if ((s / sizeof (union MapEntry)) != len)
209 return NULL; /* integer overflow on multiplication */
210 if (NULL == (hm->map = GNUNET_malloc_large (s)))
211 { 196 {
212 /* out of memory */ 197 size_t s;
213 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 198 /* application *explicitly* requested very large map, hopefully
214 "Out of memory allocating large hash map (%u entries)\n", 199 it checks the return value... */
215 len); 200 s = len * sizeof(union MapEntry);
216 GNUNET_free (hm); 201 if ((s / sizeof(union MapEntry)) != len)
217 return NULL; 202 return NULL; /* integer overflow on multiplication */
203 if (NULL == (hm->map = GNUNET_malloc_large(s)))
204 {
205 /* out of memory */
206 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
207 "Out of memory allocating large hash map (%u entries)\n",
208 len);
209 GNUNET_free(hm);
210 return NULL;
211 }
218 } 212 }
219 }
220 else 213 else
221 { 214 {
222 hm->map = GNUNET_new_array (len, union MapEntry); 215 hm->map = GNUNET_new_array(len, union MapEntry);
223 } 216 }
224 hm->map_length = len; 217 hm->map_length = len;
225 hm->use_small_entries = do_not_copy_keys; 218 hm->use_small_entries = do_not_copy_keys;
226 return hm; 219 return hm;
@@ -234,44 +227,44 @@ GNUNET_CONTAINER_multihashmap_create (unsigned int len, int do_not_copy_keys)
234 * @param map the map 227 * @param map the map
235 */ 228 */
236void 229void
237GNUNET_CONTAINER_multihashmap_destroy ( 230GNUNET_CONTAINER_multihashmap_destroy(
238 struct GNUNET_CONTAINER_MultiHashMap *map) 231 struct GNUNET_CONTAINER_MultiHashMap *map)
239{ 232{
240 GNUNET_assert (0 == map->next_cache_off); 233 GNUNET_assert(0 == map->next_cache_off);
241 for (unsigned int i = 0; i < map->map_length; i++) 234 for (unsigned int i = 0; i < map->map_length; i++)
242 {
243 union MapEntry me;
244
245 me = map->map[i];
246 if (map->use_small_entries)
247 { 235 {
248 struct SmallMapEntry *sme; 236 union MapEntry me;
249 struct SmallMapEntry *nxt; 237
250 238 me = map->map[i];
251 nxt = me.sme; 239 if (map->use_small_entries)
252 while (NULL != (sme = nxt)) 240 {
253 { 241 struct SmallMapEntry *sme;
254 nxt = sme->next; 242 struct SmallMapEntry *nxt;
255 GNUNET_free (sme); 243
256 } 244 nxt = me.sme;
257 me.sme = NULL; 245 while (NULL != (sme = nxt))
258 } 246 {
259 else 247 nxt = sme->next;
260 { 248 GNUNET_free(sme);
261 struct BigMapEntry *bme; 249 }
262 struct BigMapEntry *nxt; 250 me.sme = NULL;
263 251 }
264 nxt = me.bme; 252 else
265 while (NULL != (bme = nxt)) 253 {
266 { 254 struct BigMapEntry *bme;
267 nxt = bme->next; 255 struct BigMapEntry *nxt;
268 GNUNET_free (bme); 256
269 } 257 nxt = me.bme;
270 me.bme = NULL; 258 while (NULL != (bme = nxt))
259 {
260 nxt = bme->next;
261 GNUNET_free(bme);
262 }
263 me.bme = NULL;
264 }
271 } 265 }
272 } 266 GNUNET_free(map->map);
273 GNUNET_free (map->map); 267 GNUNET_free(map);
274 GNUNET_free (map);
275} 268}
276 269
277 270
@@ -283,11 +276,11 @@ GNUNET_CONTAINER_multihashmap_destroy (
283 * @return offset into the "map" array of "map" 276 * @return offset into the "map" array of "map"
284 */ 277 */
285static unsigned int 278static unsigned int
286idx_of (const struct GNUNET_CONTAINER_MultiHashMap *map, 279idx_of(const struct GNUNET_CONTAINER_MultiHashMap *map,
287 const struct GNUNET_HashCode *key) 280 const struct GNUNET_HashCode *key)
288{ 281{
289 GNUNET_assert (map != NULL); 282 GNUNET_assert(map != NULL);
290 return (*(unsigned int *) key) % map->map_length; 283 return (*(unsigned int *)key) % map->map_length;
291} 284}
292 285
293 286
@@ -298,7 +291,7 @@ idx_of (const struct GNUNET_CONTAINER_MultiHashMap *map,
298 * @return the number of key value pairs 291 * @return the number of key value pairs
299 */ 292 */
300unsigned int 293unsigned int
301GNUNET_CONTAINER_multihashmap_size ( 294GNUNET_CONTAINER_multihashmap_size(
302 const struct GNUNET_CONTAINER_MultiHashMap *map) 295 const struct GNUNET_CONTAINER_MultiHashMap *map)
303{ 296{
304 return map->size; 297 return map->size;
@@ -316,29 +309,29 @@ GNUNET_CONTAINER_multihashmap_size (
316 * key-value pairs with value NULL 309 * key-value pairs with value NULL
317 */ 310 */
318void * 311void *
319GNUNET_CONTAINER_multihashmap_get ( 312GNUNET_CONTAINER_multihashmap_get(
320 const struct GNUNET_CONTAINER_MultiHashMap *map, 313 const struct GNUNET_CONTAINER_MultiHashMap *map,
321 const struct GNUNET_HashCode *key) 314 const struct GNUNET_HashCode *key)
322{ 315{
323 union MapEntry me; 316 union MapEntry me;
324 317
325 me = map->map[idx_of (map, key)]; 318 me = map->map[idx_of(map, key)];
326 if (map->use_small_entries) 319 if (map->use_small_entries)
327 { 320 {
328 struct SmallMapEntry *sme; 321 struct SmallMapEntry *sme;
329 322
330 for (sme = me.sme; NULL != sme; sme = sme->next) 323 for (sme = me.sme; NULL != sme; sme = sme->next)
331 if (0 == GNUNET_memcmp (key, sme->key)) 324 if (0 == GNUNET_memcmp(key, sme->key))
332 return sme->value; 325 return sme->value;
333 } 326 }
334 else 327 else
335 { 328 {
336 struct BigMapEntry *bme; 329 struct BigMapEntry *bme;
337 330
338 for (bme = me.bme; NULL != bme; bme = bme->next) 331 for (bme = me.bme; NULL != bme; bme = bme->next)
339 if (0 == GNUNET_memcmp (key, &bme->key)) 332 if (0 == GNUNET_memcmp(key, &bme->key))
340 return bme->value; 333 return bme->value;
341 } 334 }
342 return NULL; 335 return NULL;
343} 336}
344 337
@@ -353,7 +346,7 @@ GNUNET_CONTAINER_multihashmap_get (
353 * #GNUNET_SYSERR if it aborted iteration 346 * #GNUNET_SYSERR if it aborted iteration
354 */ 347 */
355int 348int
356GNUNET_CONTAINER_multihashmap_iterate ( 349GNUNET_CONTAINER_multihashmap_iterate(
357 struct GNUNET_CONTAINER_MultiHashMap *map, 350 struct GNUNET_CONTAINER_MultiHashMap *map,
358 GNUNET_CONTAINER_MulitHashMapIteratorCallback it, 351 GNUNET_CONTAINER_MulitHashMapIteratorCallback it,
359 void *it_cls) 352 void *it_cls)
@@ -363,54 +356,54 @@ GNUNET_CONTAINER_multihashmap_iterate (
363 union MapEntry *ce; 356 union MapEntry *ce;
364 struct GNUNET_HashCode kc; 357 struct GNUNET_HashCode kc;
365 358
366 GNUNET_assert (NULL != map); 359 GNUNET_assert(NULL != map);
367 ce = &map->next_cache[map->next_cache_off]; 360 ce = &map->next_cache[map->next_cache_off];
368 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 361 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
369 count = 0; 362 count = 0;
370 for (unsigned i = 0; i < map->map_length; i++) 363 for (unsigned i = 0; i < map->map_length; i++)
371 {
372 me = map->map[i];
373 if (map->use_small_entries)
374 { 364 {
375 struct SmallMapEntry *sme; 365 me = map->map[i];
376 366 if (map->use_small_entries)
377 ce->sme = me.sme;
378 while (NULL != (sme = ce->sme))
379 {
380 ce->sme = sme->next;
381 if (NULL != it)
382 { 367 {
383 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 368 struct SmallMapEntry *sme;
384 { 369
385 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 370 ce->sme = me.sme;
386 return GNUNET_SYSERR; 371 while (NULL != (sme = ce->sme))
387 } 372 {
373 ce->sme = sme->next;
374 if (NULL != it)
375 {
376 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
377 {
378 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
379 return GNUNET_SYSERR;
380 }
381 }
382 count++;
383 }
388 } 384 }
389 count++; 385 else
390 }
391 }
392 else
393 {
394 struct BigMapEntry *bme;
395
396 ce->bme = me.bme;
397 while (NULL != (bme = ce->bme))
398 {
399 ce->bme = bme->next;
400 if (NULL != it)
401 { 386 {
402 kc = bme->key; 387 struct BigMapEntry *bme;
403 if (GNUNET_OK != it (it_cls, &kc, bme->value)) 388
404 { 389 ce->bme = me.bme;
405 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 390 while (NULL != (bme = ce->bme))
406 return GNUNET_SYSERR; 391 {
407 } 392 ce->bme = bme->next;
393 if (NULL != it)
394 {
395 kc = bme->key;
396 if (GNUNET_OK != it(it_cls, &kc, bme->value))
397 {
398 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
399 return GNUNET_SYSERR;
400 }
401 }
402 count++;
403 }
408 } 404 }
409 count++;
410 }
411 } 405 }
412 } 406 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
413 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
414 return count; 407 return count;
415} 408}
416 409
@@ -423,8 +416,8 @@ GNUNET_CONTAINER_multihashmap_iterate (
423 * @param bme the entry that is about to be free'd 416 * @param bme the entry that is about to be free'd
424 */ 417 */
425static void 418static void
426update_next_cache_bme (struct GNUNET_CONTAINER_MultiHashMap *map, 419update_next_cache_bme(struct GNUNET_CONTAINER_MultiHashMap *map,
427 const struct BigMapEntry *bme) 420 const struct BigMapEntry *bme)
428{ 421{
429 for (unsigned int i = 0; i < map->next_cache_off; i++) 422 for (unsigned int i = 0; i < map->next_cache_off; i++)
430 if (map->next_cache[i].bme == bme) 423 if (map->next_cache[i].bme == bme)
@@ -440,8 +433,8 @@ update_next_cache_bme (struct GNUNET_CONTAINER_MultiHashMap *map,
440 * @param sme the entry that is about to be free'd 433 * @param sme the entry that is about to be free'd
441 */ 434 */
442static void 435static void
443update_next_cache_sme (struct GNUNET_CONTAINER_MultiHashMap *map, 436update_next_cache_sme(struct GNUNET_CONTAINER_MultiHashMap *map,
444 const struct SmallMapEntry *sme) 437 const struct SmallMapEntry *sme)
445{ 438{
446 for (unsigned int i = 0; i < map->next_cache_off; i++) 439 for (unsigned int i = 0; i < map->next_cache_off; i++)
447 if (map->next_cache[i].sme == sme) 440 if (map->next_cache[i].sme == sme)
@@ -461,59 +454,59 @@ update_next_cache_sme (struct GNUNET_CONTAINER_MultiHashMap *map,
461 * is not in the map 454 * is not in the map
462 */ 455 */
463int 456int
464GNUNET_CONTAINER_multihashmap_remove (struct GNUNET_CONTAINER_MultiHashMap *map, 457GNUNET_CONTAINER_multihashmap_remove(struct GNUNET_CONTAINER_MultiHashMap *map,
465 const struct GNUNET_HashCode *key, 458 const struct GNUNET_HashCode *key,
466 const void *value) 459 const void *value)
467{ 460{
468 union MapEntry me; 461 union MapEntry me;
469 unsigned int i; 462 unsigned int i;
470 463
471 map->modification_counter++; 464 map->modification_counter++;
472 465
473 i = idx_of (map, key); 466 i = idx_of(map, key);
474 me = map->map[i]; 467 me = map->map[i];
475 if (map->use_small_entries) 468 if (map->use_small_entries)
476 {
477 struct SmallMapEntry *p;
478
479 p = NULL;
480 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
481 { 469 {
482 if ((0 == GNUNET_memcmp (key, sme->key)) && (value == sme->value)) 470 struct SmallMapEntry *p;
483 { 471
484 if (NULL == p) 472 p = NULL;
485 map->map[i].sme = sme->next; 473 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
486 else 474 {
487 p->next = sme->next; 475 if ((0 == GNUNET_memcmp(key, sme->key)) && (value == sme->value))
488 update_next_cache_sme (map, sme); 476 {
489 GNUNET_free (sme); 477 if (NULL == p)
490 map->size--; 478 map->map[i].sme = sme->next;
491 return GNUNET_YES; 479 else
492 } 480 p->next = sme->next;
493 p = sme; 481 update_next_cache_sme(map, sme);
482 GNUNET_free(sme);
483 map->size--;
484 return GNUNET_YES;
485 }
486 p = sme;
487 }
494 } 488 }
495 }
496 else 489 else
497 {
498 struct BigMapEntry *p;
499
500 p = NULL;
501 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
502 { 490 {
503 if ((0 == GNUNET_memcmp (key, &bme->key)) && (value == bme->value)) 491 struct BigMapEntry *p;
504 { 492
505 if (NULL == p) 493 p = NULL;
506 map->map[i].bme = bme->next; 494 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
507 else 495 {
508 p->next = bme->next; 496 if ((0 == GNUNET_memcmp(key, &bme->key)) && (value == bme->value))
509 update_next_cache_bme (map, bme); 497 {
510 GNUNET_free (bme); 498 if (NULL == p)
511 map->size--; 499 map->map[i].bme = bme->next;
512 return GNUNET_YES; 500 else
513 } 501 p->next = bme->next;
514 p = bme; 502 update_next_cache_bme(map, bme);
503 GNUNET_free(bme);
504 map->size--;
505 return GNUNET_YES;
506 }
507 p = bme;
508 }
515 } 509 }
516 }
517 return GNUNET_NO; 510 return GNUNET_NO;
518} 511}
519 512
@@ -527,7 +520,7 @@ GNUNET_CONTAINER_multihashmap_remove (struct GNUNET_CONTAINER_MultiHashMap *map,
527 * @return number of values removed 520 * @return number of values removed
528 */ 521 */
529int 522int
530GNUNET_CONTAINER_multihashmap_remove_all ( 523GNUNET_CONTAINER_multihashmap_remove_all(
531 struct GNUNET_CONTAINER_MultiHashMap *map, 524 struct GNUNET_CONTAINER_MultiHashMap *map,
532 const struct GNUNET_HashCode *key) 525 const struct GNUNET_HashCode *key)
533{ 526{
@@ -538,70 +531,70 @@ GNUNET_CONTAINER_multihashmap_remove_all (
538 map->modification_counter++; 531 map->modification_counter++;
539 532
540 ret = 0; 533 ret = 0;
541 i = idx_of (map, key); 534 i = idx_of(map, key);
542 me = map->map[i]; 535 me = map->map[i];
543 if (map->use_small_entries) 536 if (map->use_small_entries)
544 {
545 struct SmallMapEntry *sme;
546 struct SmallMapEntry *p;
547
548 p = NULL;
549 sme = me.sme;
550 while (NULL != sme)
551 { 537 {
552 if (0 == GNUNET_memcmp (key, sme->key)) 538 struct SmallMapEntry *sme;
553 { 539 struct SmallMapEntry *p;
554 if (NULL == p) 540
555 map->map[i].sme = sme->next; 541 p = NULL;
556 else 542 sme = me.sme;
557 p->next = sme->next; 543 while (NULL != sme)
558 update_next_cache_sme (map, sme); 544 {
559 GNUNET_free (sme); 545 if (0 == GNUNET_memcmp(key, sme->key))
560 map->size--; 546 {
561 if (NULL == p) 547 if (NULL == p)
562 sme = map->map[i].sme; 548 map->map[i].sme = sme->next;
563 else 549 else
564 sme = p->next; 550 p->next = sme->next;
565 ret++; 551 update_next_cache_sme(map, sme);
566 } 552 GNUNET_free(sme);
567 else 553 map->size--;
568 { 554 if (NULL == p)
569 p = sme; 555 sme = map->map[i].sme;
570 sme = sme->next; 556 else
571 } 557 sme = p->next;
558 ret++;
559 }
560 else
561 {
562 p = sme;
563 sme = sme->next;
564 }
565 }
572 } 566 }
573 }
574 else 567 else
575 {
576 struct BigMapEntry *bme;
577 struct BigMapEntry *p;
578
579 p = NULL;
580 bme = me.bme;
581 while (NULL != bme)
582 { 568 {
583 if (0 == GNUNET_memcmp (key, &bme->key)) 569 struct BigMapEntry *bme;
584 { 570 struct BigMapEntry *p;
585 if (NULL == p) 571
586 map->map[i].bme = bme->next; 572 p = NULL;
587 else 573 bme = me.bme;
588 p->next = bme->next; 574 while (NULL != bme)
589 update_next_cache_bme (map, bme); 575 {
590 GNUNET_free (bme); 576 if (0 == GNUNET_memcmp(key, &bme->key))
591 map->size--; 577 {
592 if (NULL == p) 578 if (NULL == p)
593 bme = map->map[i].bme; 579 map->map[i].bme = bme->next;
594 else 580 else
595 bme = p->next; 581 p->next = bme->next;
596 ret++; 582 update_next_cache_bme(map, bme);
597 } 583 GNUNET_free(bme);
598 else 584 map->size--;
599 { 585 if (NULL == p)
600 p = bme; 586 bme = map->map[i].bme;
601 bme = bme->next; 587 else
602 } 588 bme = p->next;
589 ret++;
590 }
591 else
592 {
593 p = bme;
594 bme = bme->next;
595 }
596 }
603 } 597 }
604 }
605 return ret; 598 return ret;
606} 599}
607 600
@@ -615,12 +608,12 @@ GNUNET_CONTAINER_multihashmap_remove_all (
615 * @return #GNUNET_OK (continue to iterate) 608 * @return #GNUNET_OK (continue to iterate)
616 */ 609 */
617static int 610static int
618remove_all (void *cls, const struct GNUNET_HashCode *key, void *value) 611remove_all(void *cls, const struct GNUNET_HashCode *key, void *value)
619{ 612{
620 struct GNUNET_CONTAINER_MultiHashMap *map = cls; 613 struct GNUNET_CONTAINER_MultiHashMap *map = cls;
621 614
622 GNUNET_assert (GNUNET_YES == 615 GNUNET_assert(GNUNET_YES ==
623 GNUNET_CONTAINER_multihashmap_remove (map, key, value)); 616 GNUNET_CONTAINER_multihashmap_remove(map, key, value));
624 return GNUNET_OK; 617 return GNUNET_OK;
625} 618}
626 619
@@ -634,12 +627,12 @@ remove_all (void *cls, const struct GNUNET_HashCode *key, void *value)
634 * @return number of values removed 627 * @return number of values removed
635 */ 628 */
636unsigned int 629unsigned int
637GNUNET_CONTAINER_multihashmap_clear (struct GNUNET_CONTAINER_MultiHashMap *map) 630GNUNET_CONTAINER_multihashmap_clear(struct GNUNET_CONTAINER_MultiHashMap *map)
638{ 631{
639 unsigned int ret; 632 unsigned int ret;
640 633
641 ret = map->size; 634 ret = map->size;
642 GNUNET_CONTAINER_multihashmap_iterate (map, &remove_all, map); 635 GNUNET_CONTAINER_multihashmap_iterate(map, &remove_all, map);
643 return ret; 636 return ret;
644} 637}
645 638
@@ -654,29 +647,29 @@ GNUNET_CONTAINER_multihashmap_clear (struct GNUNET_CONTAINER_MultiHashMap *map)
654 * #GNUNET_NO if not 647 * #GNUNET_NO if not
655 */ 648 */
656int 649int
657GNUNET_CONTAINER_multihashmap_contains ( 650GNUNET_CONTAINER_multihashmap_contains(
658 const struct GNUNET_CONTAINER_MultiHashMap *map, 651 const struct GNUNET_CONTAINER_MultiHashMap *map,
659 const struct GNUNET_HashCode *key) 652 const struct GNUNET_HashCode *key)
660{ 653{
661 union MapEntry me; 654 union MapEntry me;
662 655
663 me = map->map[idx_of (map, key)]; 656 me = map->map[idx_of(map, key)];
664 if (map->use_small_entries) 657 if (map->use_small_entries)
665 { 658 {
666 struct SmallMapEntry *sme; 659 struct SmallMapEntry *sme;
667 660
668 for (sme = me.sme; NULL != sme; sme = sme->next) 661 for (sme = me.sme; NULL != sme; sme = sme->next)
669 if (0 == GNUNET_memcmp (key, sme->key)) 662 if (0 == GNUNET_memcmp(key, sme->key))
670 return GNUNET_YES; 663 return GNUNET_YES;
671 } 664 }
672 else 665 else
673 { 666 {
674 struct BigMapEntry *bme; 667 struct BigMapEntry *bme;
675 668
676 for (bme = me.bme; NULL != bme; bme = bme->next) 669 for (bme = me.bme; NULL != bme; bme = bme->next)
677 if (0 == GNUNET_memcmp (key, &bme->key)) 670 if (0 == GNUNET_memcmp(key, &bme->key))
678 return GNUNET_YES; 671 return GNUNET_YES;
679 } 672 }
680 return GNUNET_NO; 673 return GNUNET_NO;
681} 674}
682 675
@@ -692,30 +685,30 @@ GNUNET_CONTAINER_multihashmap_contains (
692 * #GNUNET_NO if not 685 * #GNUNET_NO if not
693 */ 686 */
694int 687int
695GNUNET_CONTAINER_multihashmap_contains_value ( 688GNUNET_CONTAINER_multihashmap_contains_value(
696 const struct GNUNET_CONTAINER_MultiHashMap *map, 689 const struct GNUNET_CONTAINER_MultiHashMap *map,
697 const struct GNUNET_HashCode *key, 690 const struct GNUNET_HashCode *key,
698 const void *value) 691 const void *value)
699{ 692{
700 union MapEntry me; 693 union MapEntry me;
701 694
702 me = map->map[idx_of (map, key)]; 695 me = map->map[idx_of(map, key)];
703 if (map->use_small_entries) 696 if (map->use_small_entries)
704 { 697 {
705 struct SmallMapEntry *sme; 698 struct SmallMapEntry *sme;
706 699
707 for (sme = me.sme; NULL != sme; sme = sme->next) 700 for (sme = me.sme; NULL != sme; sme = sme->next)
708 if ((0 == GNUNET_memcmp (key, sme->key)) && (sme->value == value)) 701 if ((0 == GNUNET_memcmp(key, sme->key)) && (sme->value == value))
709 return GNUNET_YES; 702 return GNUNET_YES;
710 } 703 }
711 else 704 else
712 { 705 {
713 struct BigMapEntry *bme; 706 struct BigMapEntry *bme;
714 707
715 for (bme = me.bme; NULL != bme; bme = bme->next) 708 for (bme = me.bme; NULL != bme; bme = bme->next)
716 if ((0 == GNUNET_memcmp (key, &bme->key)) && (bme->value == value)) 709 if ((0 == GNUNET_memcmp(key, &bme->key)) && (bme->value == value))
717 return GNUNET_YES; 710 return GNUNET_YES;
718 } 711 }
719 return GNUNET_NO; 712 return GNUNET_NO;
720} 713}
721 714
@@ -726,7 +719,7 @@ GNUNET_CONTAINER_multihashmap_contains_value (
726 * @param map the hash map to grow 719 * @param map the hash map to grow
727 */ 720 */
728static void 721static void
729grow (struct GNUNET_CONTAINER_MultiHashMap *map) 722grow(struct GNUNET_CONTAINER_MultiHashMap *map)
730{ 723{
731 union MapEntry *old_map; 724 union MapEntry *old_map;
732 union MapEntry *new_map; 725 union MapEntry *new_map;
@@ -736,46 +729,46 @@ grow (struct GNUNET_CONTAINER_MultiHashMap *map)
736 729
737 old_map = map->map; 730 old_map = map->map;
738 old_len = map->map_length; 731 old_len = map->map_length;
739 GNUNET_assert (0 != old_len); 732 GNUNET_assert(0 != old_len);
740 new_len = old_len * 2; 733 new_len = old_len * 2;
741 if (0 == new_len) /* 2^31 * 2 == 0 */ 734 if (0 == new_len) /* 2^31 * 2 == 0 */
742 new_len = old_len; /* never use 0 */ 735 new_len = old_len; /* never use 0 */
743 if (new_len == old_len) 736 if (new_len == old_len)
744 return; /* nothing changed */ 737 return; /* nothing changed */
745 new_map = GNUNET_malloc_large (new_len * sizeof (union MapEntry)); 738 new_map = GNUNET_malloc_large(new_len * sizeof(union MapEntry));
746 if (NULL == new_map) 739 if (NULL == new_map)
747 return; /* grow not possible */ 740 return; /* grow not possible */
748 map->modification_counter++; 741 map->modification_counter++;
749 map->map_length = new_len; 742 map->map_length = new_len;
750 map->map = new_map; 743 map->map = new_map;
751 for (unsigned int i = 0; i < old_len; i++) 744 for (unsigned int i = 0; i < old_len; i++)
752 {
753 if (map->use_small_entries)
754 {
755 struct SmallMapEntry *sme;
756
757 while (NULL != (sme = old_map[i].sme))
758 {
759 old_map[i].sme = sme->next;
760 idx = idx_of (map, sme->key);
761 sme->next = new_map[idx].sme;
762 new_map[idx].sme = sme;
763 }
764 }
765 else
766 { 745 {
767 struct BigMapEntry *bme; 746 if (map->use_small_entries)
768 747 {
769 while (NULL != (bme = old_map[i].bme)) 748 struct SmallMapEntry *sme;
770 { 749
771 old_map[i].bme = bme->next; 750 while (NULL != (sme = old_map[i].sme))
772 idx = idx_of (map, &bme->key); 751 {
773 bme->next = new_map[idx].bme; 752 old_map[i].sme = sme->next;
774 new_map[idx].bme = bme; 753 idx = idx_of(map, sme->key);
775 } 754 sme->next = new_map[idx].sme;
755 new_map[idx].sme = sme;
756 }
757 }
758 else
759 {
760 struct BigMapEntry *bme;
761
762 while (NULL != (bme = old_map[i].bme))
763 {
764 old_map[i].bme = bme->next;
765 idx = idx_of(map, &bme->key);
766 bme->next = new_map[idx].bme;
767 new_map[idx].bme = bme;
768 }
769 }
776 } 770 }
777 } 771 GNUNET_free(old_map);
778 GNUNET_free (old_map);
779} 772}
780 773
781 774
@@ -792,71 +785,71 @@ grow (struct GNUNET_CONTAINER_MultiHashMap *map)
792 * value already exists 785 * value already exists
793 */ 786 */
794int 787int
795GNUNET_CONTAINER_multihashmap_put (struct GNUNET_CONTAINER_MultiHashMap *map, 788GNUNET_CONTAINER_multihashmap_put(struct GNUNET_CONTAINER_MultiHashMap *map,
796 const struct GNUNET_HashCode *key, 789 const struct GNUNET_HashCode *key,
797 void *value, 790 void *value,
798 enum GNUNET_CONTAINER_MultiHashMapOption opt) 791 enum GNUNET_CONTAINER_MultiHashMapOption opt)
799{ 792{
800 union MapEntry me; 793 union MapEntry me;
801 unsigned int i; 794 unsigned int i;
802 795
803 i = idx_of (map, key); 796 i = idx_of(map, key);
804 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) && 797 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) &&
805 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) 798 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
806 {
807 me = map->map[i];
808 if (map->use_small_entries)
809 { 799 {
810 struct SmallMapEntry *sme; 800 me = map->map[i];
811 801 if (map->use_small_entries)
812 for (sme = me.sme; NULL != sme; sme = sme->next)
813 if (0 == GNUNET_memcmp (key, sme->key))
814 { 802 {
815 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 803 struct SmallMapEntry *sme;
816 return GNUNET_SYSERR; 804
817 sme->value = value; 805 for (sme = me.sme; NULL != sme; sme = sme->next)
818 return GNUNET_NO; 806 if (0 == GNUNET_memcmp(key, sme->key))
807 {
808 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
809 return GNUNET_SYSERR;
810 sme->value = value;
811 return GNUNET_NO;
812 }
819 } 813 }
820 } 814 else
821 else
822 {
823 struct BigMapEntry *bme;
824
825 for (bme = me.bme; NULL != bme; bme = bme->next)
826 if (0 == GNUNET_memcmp (key, &bme->key))
827 { 815 {
828 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 816 struct BigMapEntry *bme;
829 return GNUNET_SYSERR; 817
830 bme->value = value; 818 for (bme = me.bme; NULL != bme; bme = bme->next)
831 return GNUNET_NO; 819 if (0 == GNUNET_memcmp(key, &bme->key))
820 {
821 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
822 return GNUNET_SYSERR;
823 bme->value = value;
824 return GNUNET_NO;
825 }
832 } 826 }
833 } 827 }
834 }
835 if (map->size / 3 >= map->map_length / 4) 828 if (map->size / 3 >= map->map_length / 4)
836 { 829 {
837 grow (map); 830 grow(map);
838 i = idx_of (map, key); 831 i = idx_of(map, key);
839 } 832 }
840 if (map->use_small_entries) 833 if (map->use_small_entries)
841 { 834 {
842 struct SmallMapEntry *sme; 835 struct SmallMapEntry *sme;
843 836
844 sme = GNUNET_new (struct SmallMapEntry); 837 sme = GNUNET_new(struct SmallMapEntry);
845 sme->key = key; 838 sme->key = key;
846 sme->value = value; 839 sme->value = value;
847 sme->next = map->map[i].sme; 840 sme->next = map->map[i].sme;
848 map->map[i].sme = sme; 841 map->map[i].sme = sme;
849 } 842 }
850 else 843 else
851 { 844 {
852 struct BigMapEntry *bme; 845 struct BigMapEntry *bme;
853 846
854 bme = GNUNET_new (struct BigMapEntry); 847 bme = GNUNET_new(struct BigMapEntry);
855 bme->key = *key; 848 bme->key = *key;
856 bme->value = value; 849 bme->value = value;
857 bme->next = map->map[i].bme; 850 bme->next = map->map[i].bme;
858 map->map[i].bme = bme; 851 map->map[i].bme = bme;
859 } 852 }
860 map->size++; 853 map->size++;
861 return GNUNET_OK; 854 return GNUNET_OK;
862} 855}
@@ -873,7 +866,7 @@ GNUNET_CONTAINER_multihashmap_put (struct GNUNET_CONTAINER_MultiHashMap *map,
873 * #GNUNET_SYSERR if it aborted iteration 866 * #GNUNET_SYSERR if it aborted iteration
874 */ 867 */
875int 868int
876GNUNET_CONTAINER_multihashmap_get_multiple ( 869GNUNET_CONTAINER_multihashmap_get_multiple(
877 struct GNUNET_CONTAINER_MultiHashMap *map, 870 struct GNUNET_CONTAINER_MultiHashMap *map,
878 const struct GNUNET_HashCode *key, 871 const struct GNUNET_HashCode *key,
879 GNUNET_CONTAINER_MulitHashMapIteratorCallback it, 872 GNUNET_CONTAINER_MulitHashMapIteratorCallback it,
@@ -884,46 +877,46 @@ GNUNET_CONTAINER_multihashmap_get_multiple (
884 union MapEntry *ce; 877 union MapEntry *ce;
885 878
886 ce = &map->next_cache[map->next_cache_off]; 879 ce = &map->next_cache[map->next_cache_off];
887 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 880 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
888 count = 0; 881 count = 0;
889 me = &map->map[idx_of (map, key)]; 882 me = &map->map[idx_of(map, key)];
890 if (map->use_small_entries) 883 if (map->use_small_entries)
891 {
892 struct SmallMapEntry *sme;
893
894 ce->sme = me->sme;
895 while (NULL != (sme = ce->sme))
896 { 884 {
897 ce->sme = sme->next; 885 struct SmallMapEntry *sme;
898 if (0 != GNUNET_memcmp (key, sme->key)) 886
899 continue; 887 ce->sme = me->sme;
900 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, sme->value))) 888 while (NULL != (sme = ce->sme))
901 { 889 {
902 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 890 ce->sme = sme->next;
903 return GNUNET_SYSERR; 891 if (0 != GNUNET_memcmp(key, sme->key))
904 } 892 continue;
905 count++; 893 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, sme->value)))
894 {
895 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
896 return GNUNET_SYSERR;
897 }
898 count++;
899 }
906 } 900 }
907 }
908 else 901 else
909 {
910 struct BigMapEntry *bme;
911
912 ce->bme = me->bme;
913 while (NULL != (bme = ce->bme))
914 { 902 {
915 ce->bme = bme->next; 903 struct BigMapEntry *bme;
916 if (0 != GNUNET_memcmp (key, &bme->key)) 904
917 continue; 905 ce->bme = me->bme;
918 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, bme->value))) 906 while (NULL != (bme = ce->bme))
919 { 907 {
920 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 908 ce->bme = bme->next;
921 return GNUNET_SYSERR; 909 if (0 != GNUNET_memcmp(key, &bme->key))
922 } 910 continue;
923 count++; 911 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, bme->value)))
912 {
913 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
914 return GNUNET_SYSERR;
915 }
916 count++;
917 }
924 } 918 }
925 } 919 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
926 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
927 return count; 920 return count;
928} 921}
929 922
@@ -940,7 +933,7 @@ GNUNET_CONTAINER_multihashmap_get_multiple (
940 * @return the number of key value pairs processed, zero or one. 933 * @return the number of key value pairs processed, zero or one.
941 */ 934 */
942unsigned int 935unsigned int
943GNUNET_CONTAINER_multihashmap_get_random ( 936GNUNET_CONTAINER_multihashmap_get_random(
944 const struct GNUNET_CONTAINER_MultiHashMap *map, 937 const struct GNUNET_CONTAINER_MultiHashMap *map,
945 GNUNET_CONTAINER_MulitHashMapIteratorCallback it, 938 GNUNET_CONTAINER_MulitHashMapIteratorCallback it,
946 void *it_cls) 939 void *it_cls)
@@ -953,48 +946,48 @@ GNUNET_CONTAINER_multihashmap_get_random (
953 return 0; 946 return 0;
954 if (NULL == it) 947 if (NULL == it)
955 return 1; 948 return 1;
956 off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, map->size); 949 off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, map->size);
957 for (idx = 0; idx < map->map_length; idx++) 950 for (idx = 0; idx < map->map_length; idx++)
958 {
959 me = map->map[idx];
960 if (map->use_small_entries)
961 { 951 {
962 struct SmallMapEntry *sme; 952 me = map->map[idx];
963 struct SmallMapEntry *nxt; 953 if (map->use_small_entries)
964
965 nxt = me.sme;
966 while (NULL != (sme = nxt))
967 {
968 nxt = sme->next;
969 if (0 == off)
970 { 954 {
971 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 955 struct SmallMapEntry *sme;
972 return GNUNET_SYSERR; 956 struct SmallMapEntry *nxt;
973 return 1; 957
958 nxt = me.sme;
959 while (NULL != (sme = nxt))
960 {
961 nxt = sme->next;
962 if (0 == off)
963 {
964 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
965 return GNUNET_SYSERR;
966 return 1;
967 }
968 off--;
969 }
974 } 970 }
975 off--; 971 else
976 }
977 }
978 else
979 {
980 struct BigMapEntry *bme;
981 struct BigMapEntry *nxt;
982
983 nxt = me.bme;
984 while (NULL != (bme = nxt))
985 {
986 nxt = bme->next;
987 if (0 == off)
988 { 972 {
989 if (GNUNET_OK != it (it_cls, &bme->key, bme->value)) 973 struct BigMapEntry *bme;
990 return GNUNET_SYSERR; 974 struct BigMapEntry *nxt;
991 return 1; 975
976 nxt = me.bme;
977 while (NULL != (bme = nxt))
978 {
979 nxt = bme->next;
980 if (0 == off)
981 {
982 if (GNUNET_OK != it(it_cls, &bme->key, bme->value))
983 return GNUNET_SYSERR;
984 return 1;
985 }
986 off--;
987 }
992 } 988 }
993 off--;
994 }
995 } 989 }
996 } 990 GNUNET_break(0);
997 GNUNET_break (0);
998 return GNUNET_SYSERR; 991 return GNUNET_SYSERR;
999} 992}
1000 993
@@ -1012,12 +1005,12 @@ GNUNET_CONTAINER_multihashmap_get_random (
1012 * @return an iterator over the given multihashmap 'map' 1005 * @return an iterator over the given multihashmap 'map'
1013 */ 1006 */
1014struct GNUNET_CONTAINER_MultiHashMapIterator * 1007struct GNUNET_CONTAINER_MultiHashMapIterator *
1015GNUNET_CONTAINER_multihashmap_iterator_create ( 1008GNUNET_CONTAINER_multihashmap_iterator_create(
1016 const struct GNUNET_CONTAINER_MultiHashMap *map) 1009 const struct GNUNET_CONTAINER_MultiHashMap *map)
1017{ 1010{
1018 struct GNUNET_CONTAINER_MultiHashMapIterator *iter; 1011 struct GNUNET_CONTAINER_MultiHashMapIterator *iter;
1019 1012
1020 iter = GNUNET_new (struct GNUNET_CONTAINER_MultiHashMapIterator); 1013 iter = GNUNET_new(struct GNUNET_CONTAINER_MultiHashMapIterator);
1021 iter->map = map; 1014 iter->map = map;
1022 iter->modification_counter = map->modification_counter; 1015 iter->modification_counter = map->modification_counter;
1023 iter->me = map->map[0]; 1016 iter->me = map->map[0];
@@ -1040,47 +1033,47 @@ GNUNET_CONTAINER_multihashmap_iterator_create (
1040 * #GNUNET_NO if we are out of elements 1033 * #GNUNET_NO if we are out of elements
1041 */ 1034 */
1042int 1035int
1043GNUNET_CONTAINER_multihashmap_iterator_next ( 1036GNUNET_CONTAINER_multihashmap_iterator_next(
1044 struct GNUNET_CONTAINER_MultiHashMapIterator *iter, 1037 struct GNUNET_CONTAINER_MultiHashMapIterator *iter,
1045 struct GNUNET_HashCode *key, 1038 struct GNUNET_HashCode *key,
1046 const void **value) 1039 const void **value)
1047{ 1040{
1048 /* make sure the map has not been modified */ 1041 /* make sure the map has not been modified */
1049 GNUNET_assert (iter->modification_counter == iter->map->modification_counter); 1042 GNUNET_assert(iter->modification_counter == iter->map->modification_counter);
1050 1043
1051 /* look for the next entry, skipping empty buckets */ 1044 /* look for the next entry, skipping empty buckets */
1052 while (1) 1045 while (1)
1053 {
1054 if (iter->idx >= iter->map->map_length)
1055 return GNUNET_NO;
1056 if (GNUNET_YES == iter->map->use_small_entries)
1057 {
1058 if (NULL != iter->me.sme)
1059 {
1060 if (NULL != key)
1061 *key = *iter->me.sme->key;
1062 if (NULL != value)
1063 *value = iter->me.sme->value;
1064 iter->me.sme = iter->me.sme->next;
1065 return GNUNET_YES;
1066 }
1067 }
1068 else
1069 { 1046 {
1070 if (NULL != iter->me.bme) 1047 if (iter->idx >= iter->map->map_length)
1071 { 1048 return GNUNET_NO;
1072 if (NULL != key) 1049 if (GNUNET_YES == iter->map->use_small_entries)
1073 *key = iter->me.bme->key; 1050 {
1074 if (NULL != value) 1051 if (NULL != iter->me.sme)
1075 *value = iter->me.bme->value; 1052 {
1076 iter->me.bme = iter->me.bme->next; 1053 if (NULL != key)
1077 return GNUNET_YES; 1054 *key = *iter->me.sme->key;
1078 } 1055 if (NULL != value)
1056 *value = iter->me.sme->value;
1057 iter->me.sme = iter->me.sme->next;
1058 return GNUNET_YES;
1059 }
1060 }
1061 else
1062 {
1063 if (NULL != iter->me.bme)
1064 {
1065 if (NULL != key)
1066 *key = iter->me.bme->key;
1067 if (NULL != value)
1068 *value = iter->me.bme->value;
1069 iter->me.bme = iter->me.bme->next;
1070 return GNUNET_YES;
1071 }
1072 }
1073 iter->idx += 1;
1074 if (iter->idx < iter->map->map_length)
1075 iter->me = iter->map->map[iter->idx];
1079 } 1076 }
1080 iter->idx += 1;
1081 if (iter->idx < iter->map->map_length)
1082 iter->me = iter->map->map[iter->idx];
1083 }
1084} 1077}
1085 1078
1086 1079
@@ -1090,10 +1083,10 @@ GNUNET_CONTAINER_multihashmap_iterator_next (
1090 * @param iter the iterator to destroy 1083 * @param iter the iterator to destroy
1091 */ 1084 */
1092void 1085void
1093GNUNET_CONTAINER_multihashmap_iterator_destroy ( 1086GNUNET_CONTAINER_multihashmap_iterator_destroy(
1094 struct GNUNET_CONTAINER_MultiHashMapIterator *iter) 1087 struct GNUNET_CONTAINER_MultiHashMapIterator *iter)
1095{ 1088{
1096 GNUNET_free (iter); 1089 GNUNET_free(iter);
1097} 1090}
1098 1091
1099 1092
diff --git a/src/util/container_multihashmap32.c b/src/util/container_multihashmap32.c
index 0956ada67..82d908555 100644
--- a/src/util/container_multihashmap32.c
+++ b/src/util/container_multihashmap32.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_multihashmap32.c 21 * @file util/container_multihashmap32.c
22 * @brief a version of hash map implemented in container_multihashmap.c but with 22 * @brief a version of hash map implemented in container_multihashmap.c but with
@@ -29,7 +29,7 @@
29#include "gnunet_container_lib.h" 29#include "gnunet_container_lib.h"
30 30
31#define LOG(kind, ...) \ 31#define LOG(kind, ...) \
32 GNUNET_log_from (kind, "util-container-multihashmap32", __VA_ARGS__) 32 GNUNET_log_from(kind, "util-container-multihashmap32", __VA_ARGS__)
33 33
34 34
35/** 35/**
@@ -43,9 +43,7 @@
43/** 43/**
44 * An entry in the hash map. 44 * An entry in the hash map.
45 */ 45 */
46struct MapEntry 46struct MapEntry {
47{
48
49 /** 47 /**
50 * Key for the entry. 48 * Key for the entry.
51 */ 49 */
@@ -65,9 +63,7 @@ struct MapEntry
65/** 63/**
66 * Internal representation of the hash map. 64 * Internal representation of the hash map.
67 */ 65 */
68struct GNUNET_CONTAINER_MultiHashMap32 66struct GNUNET_CONTAINER_MultiHashMap32 {
69{
70
71 /** 67 /**
72 * All of our buckets. 68 * All of our buckets.
73 */ 69 */
@@ -108,8 +104,7 @@ struct GNUNET_CONTAINER_MultiHashMap32
108 * Cursor into a multihashmap. 104 * Cursor into a multihashmap.
109 * Allows to enumerate elements asynchronously. 105 * Allows to enumerate elements asynchronously.
110 */ 106 */
111struct GNUNET_CONTAINER_MultiHashMap32Iterator 107struct GNUNET_CONTAINER_MultiHashMap32Iterator {
112{
113 /** 108 /**
114 * Position in the bucket @e idx 109 * Position in the bucket @e idx
115 */ 110 */
@@ -140,18 +135,18 @@ struct GNUNET_CONTAINER_MultiHashMap32Iterator
140 * @return NULL on error 135 * @return NULL on error
141 */ 136 */
142struct GNUNET_CONTAINER_MultiHashMap32 * 137struct GNUNET_CONTAINER_MultiHashMap32 *
143GNUNET_CONTAINER_multihashmap32_create (unsigned int len) 138GNUNET_CONTAINER_multihashmap32_create(unsigned int len)
144{ 139{
145 struct GNUNET_CONTAINER_MultiHashMap32 *ret; 140 struct GNUNET_CONTAINER_MultiHashMap32 *ret;
146 141
147 GNUNET_assert (len > 0); 142 GNUNET_assert(len > 0);
148 ret = GNUNET_new (struct GNUNET_CONTAINER_MultiHashMap32); 143 ret = GNUNET_new(struct GNUNET_CONTAINER_MultiHashMap32);
149 ret->map = GNUNET_malloc_large (len * sizeof (struct MapEntry *)); 144 ret->map = GNUNET_malloc_large(len * sizeof(struct MapEntry *));
150 if (NULL == ret->map) 145 if (NULL == ret->map)
151 { 146 {
152 GNUNET_free (ret); 147 GNUNET_free(ret);
153 return NULL; 148 return NULL;
154 } 149 }
155 ret->map_length = len; 150 ret->map_length = len;
156 return ret; 151 return ret;
157} 152}
@@ -164,21 +159,21 @@ GNUNET_CONTAINER_multihashmap32_create (unsigned int len)
164 * @param map the map 159 * @param map the map
165 */ 160 */
166void 161void
167GNUNET_CONTAINER_multihashmap32_destroy ( 162GNUNET_CONTAINER_multihashmap32_destroy(
168 struct GNUNET_CONTAINER_MultiHashMap32 *map) 163 struct GNUNET_CONTAINER_MultiHashMap32 *map)
169{ 164{
170 struct MapEntry *e; 165 struct MapEntry *e;
171 166
172 for (unsigned int i = 0; i < map->map_length; i++) 167 for (unsigned int i = 0; i < map->map_length; i++)
173 {
174 while (NULL != (e = map->map[i]))
175 { 168 {
176 map->map[i] = e->next; 169 while (NULL != (e = map->map[i]))
177 GNUNET_free (e); 170 {
171 map->map[i] = e->next;
172 GNUNET_free(e);
173 }
178 } 174 }
179 } 175 GNUNET_free(map->map);
180 GNUNET_free (map->map); 176 GNUNET_free(map);
181 GNUNET_free (map);
182} 177}
183 178
184 179
@@ -190,10 +185,10 @@ GNUNET_CONTAINER_multihashmap32_destroy (
190 * @return offset into the "map" array of "m" 185 * @return offset into the "map" array of "m"
191 */ 186 */
192static unsigned int 187static unsigned int
193idx_of (const struct GNUNET_CONTAINER_MultiHashMap32 *m, const uint32_t key) 188idx_of(const struct GNUNET_CONTAINER_MultiHashMap32 *m, const uint32_t key)
194{ 189{
195 GNUNET_assert (NULL != m); 190 GNUNET_assert(NULL != m);
196 return ((unsigned int) key) % m->map_length; 191 return ((unsigned int)key) % m->map_length;
197} 192}
198 193
199 194
@@ -204,7 +199,7 @@ idx_of (const struct GNUNET_CONTAINER_MultiHashMap32 *m, const uint32_t key)
204 * @return the number of key value pairs 199 * @return the number of key value pairs
205 */ 200 */
206unsigned int 201unsigned int
207GNUNET_CONTAINER_multihashmap32_size ( 202GNUNET_CONTAINER_multihashmap32_size(
208 const struct GNUNET_CONTAINER_MultiHashMap32 *map) 203 const struct GNUNET_CONTAINER_MultiHashMap32 *map)
209{ 204{
210 return map->size; 205 return map->size;
@@ -222,19 +217,19 @@ GNUNET_CONTAINER_multihashmap32_size (
222 * key-value pairs with value NULL 217 * key-value pairs with value NULL
223 */ 218 */
224void * 219void *
225GNUNET_CONTAINER_multihashmap32_get ( 220GNUNET_CONTAINER_multihashmap32_get(
226 const struct GNUNET_CONTAINER_MultiHashMap32 *map, 221 const struct GNUNET_CONTAINER_MultiHashMap32 *map,
227 uint32_t key) 222 uint32_t key)
228{ 223{
229 struct MapEntry *e; 224 struct MapEntry *e;
230 225
231 e = map->map[idx_of (map, key)]; 226 e = map->map[idx_of(map, key)];
232 while (NULL != e) 227 while (NULL != e)
233 { 228 {
234 if (key == e->key) 229 if (key == e->key)
235 return e->value; 230 return e->value;
236 e = e->next; 231 e = e->next;
237 } 232 }
238 return NULL; 233 return NULL;
239} 234}
240 235
@@ -249,7 +244,7 @@ GNUNET_CONTAINER_multihashmap32_get (
249 * #GNUNET_SYSERR if it aborted iteration 244 * #GNUNET_SYSERR if it aborted iteration
250 */ 245 */
251int 246int
252GNUNET_CONTAINER_multihashmap32_iterate ( 247GNUNET_CONTAINER_multihashmap32_iterate(
253 struct GNUNET_CONTAINER_MultiHashMap32 *map, 248 struct GNUNET_CONTAINER_MultiHashMap32 *map,
254 GNUNET_CONTAINER_MulitHashMapIterator32Callback it, 249 GNUNET_CONTAINER_MulitHashMapIterator32Callback it,
255 void *it_cls) 250 void *it_cls)
@@ -258,29 +253,29 @@ GNUNET_CONTAINER_multihashmap32_iterate (
258 struct MapEntry **ce; 253 struct MapEntry **ce;
259 254
260 count = 0; 255 count = 0;
261 GNUNET_assert (NULL != map); 256 GNUNET_assert(NULL != map);
262 ce = &map->next_cache[map->next_cache_off]; 257 ce = &map->next_cache[map->next_cache_off];
263 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 258 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
264 for (unsigned int i = 0; i < map->map_length; i++) 259 for (unsigned int i = 0; i < map->map_length; i++)
265 {
266 struct MapEntry *e;
267
268 *ce = map->map[i];
269 while (NULL != (e = *ce))
270 { 260 {
271 *ce = e->next; 261 struct MapEntry *e;
272 if (NULL != it) 262
273 { 263 *ce = map->map[i];
274 if (GNUNET_OK != it (it_cls, e->key, e->value)) 264 while (NULL != (e = *ce))
275 { 265 {
276 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 266 *ce = e->next;
277 return GNUNET_SYSERR; 267 if (NULL != it)
268 {
269 if (GNUNET_OK != it(it_cls, e->key, e->value))
270 {
271 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
272 return GNUNET_SYSERR;
273 }
274 }
275 count++;
278 } 276 }
279 }
280 count++;
281 } 277 }
282 } 278 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
283 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
284 return count; 279 return count;
285} 280}
286 281
@@ -293,8 +288,8 @@ GNUNET_CONTAINER_multihashmap32_iterate (
293 * @param bme the entry that is about to be free'd 288 * @param bme the entry that is about to be free'd
294 */ 289 */
295static void 290static void
296update_next_cache (struct GNUNET_CONTAINER_MultiHashMap32 *map, 291update_next_cache(struct GNUNET_CONTAINER_MultiHashMap32 *map,
297 const struct MapEntry *me) 292 const struct MapEntry *me)
298{ 293{
299 for (unsigned int i = 0; i < map->next_cache_off; i++) 294 for (unsigned int i = 0; i < map->next_cache_off; i++)
300 if (map->next_cache[i] == me) 295 if (map->next_cache[i] == me)
@@ -314,7 +309,7 @@ update_next_cache (struct GNUNET_CONTAINER_MultiHashMap32 *map,
314 * is not in the map 309 * is not in the map
315 */ 310 */
316int 311int
317GNUNET_CONTAINER_multihashmap32_remove ( 312GNUNET_CONTAINER_multihashmap32_remove(
318 struct GNUNET_CONTAINER_MultiHashMap32 *map, 313 struct GNUNET_CONTAINER_MultiHashMap32 *map,
319 uint32_t key, 314 uint32_t key,
320 const void *value) 315 const void *value)
@@ -325,25 +320,25 @@ GNUNET_CONTAINER_multihashmap32_remove (
325 320
326 map->modification_counter++; 321 map->modification_counter++;
327 322
328 i = idx_of (map, key); 323 i = idx_of(map, key);
329 p = NULL; 324 p = NULL;
330 e = map->map[i]; 325 e = map->map[i];
331 while (e != NULL) 326 while (e != NULL)
332 {
333 if ((key == e->key) && (value == e->value))
334 { 327 {
335 if (p == NULL) 328 if ((key == e->key) && (value == e->value))
336 map->map[i] = e->next; 329 {
337 else 330 if (p == NULL)
338 p->next = e->next; 331 map->map[i] = e->next;
339 update_next_cache (map, e); 332 else
340 GNUNET_free (e); 333 p->next = e->next;
341 map->size--; 334 update_next_cache(map, e);
342 return GNUNET_YES; 335 GNUNET_free(e);
336 map->size--;
337 return GNUNET_YES;
338 }
339 p = e;
340 e = e->next;
343 } 341 }
344 p = e;
345 e = e->next;
346 }
347 return GNUNET_NO; 342 return GNUNET_NO;
348} 343}
349 344
@@ -357,7 +352,7 @@ GNUNET_CONTAINER_multihashmap32_remove (
357 * @return number of values removed 352 * @return number of values removed
358 */ 353 */
359int 354int
360GNUNET_CONTAINER_multihashmap32_remove_all ( 355GNUNET_CONTAINER_multihashmap32_remove_all(
361 struct GNUNET_CONTAINER_MultiHashMap32 *map, 356 struct GNUNET_CONTAINER_MultiHashMap32 *map,
362 uint32_t key) 357 uint32_t key)
363{ 358{
@@ -369,32 +364,32 @@ GNUNET_CONTAINER_multihashmap32_remove_all (
369 map->modification_counter++; 364 map->modification_counter++;
370 365
371 ret = 0; 366 ret = 0;
372 i = idx_of (map, key); 367 i = idx_of(map, key);
373 p = NULL; 368 p = NULL;
374 e = map->map[i]; 369 e = map->map[i];
375 while (e != NULL) 370 while (e != NULL)
376 {
377 if (key == e->key)
378 { 371 {
379 if (p == NULL) 372 if (key == e->key)
380 map->map[i] = e->next; 373 {
381 else 374 if (p == NULL)
382 p->next = e->next; 375 map->map[i] = e->next;
383 update_next_cache (map, e); 376 else
384 GNUNET_free (e); 377 p->next = e->next;
385 map->size--; 378 update_next_cache(map, e);
386 if (p == NULL) 379 GNUNET_free(e);
387 e = map->map[i]; 380 map->size--;
381 if (p == NULL)
382 e = map->map[i];
383 else
384 e = p->next;
385 ret++;
386 }
388 else 387 else
389 e = p->next; 388 {
390 ret++; 389 p = e;
391 } 390 e = e->next;
392 else 391 }
393 {
394 p = e;
395 e = e->next;
396 } 392 }
397 }
398 return ret; 393 return ret;
399} 394}
400 395
@@ -409,19 +404,19 @@ GNUNET_CONTAINER_multihashmap32_remove_all (
409 * #GNUNET_NO if not 404 * #GNUNET_NO if not
410 */ 405 */
411int 406int
412GNUNET_CONTAINER_multihashmap32_contains ( 407GNUNET_CONTAINER_multihashmap32_contains(
413 const struct GNUNET_CONTAINER_MultiHashMap32 *map, 408 const struct GNUNET_CONTAINER_MultiHashMap32 *map,
414 uint32_t key) 409 uint32_t key)
415{ 410{
416 struct MapEntry *e; 411 struct MapEntry *e;
417 412
418 e = map->map[idx_of (map, key)]; 413 e = map->map[idx_of(map, key)];
419 while (e != NULL) 414 while (e != NULL)
420 { 415 {
421 if (key == e->key) 416 if (key == e->key)
422 return GNUNET_YES; 417 return GNUNET_YES;
423 e = e->next; 418 e = e->next;
424 } 419 }
425 return GNUNET_NO; 420 return GNUNET_NO;
426} 421}
427 422
@@ -437,20 +432,20 @@ GNUNET_CONTAINER_multihashmap32_contains (
437 * #GNUNET_NO if not 432 * #GNUNET_NO if not
438 */ 433 */
439int 434int
440GNUNET_CONTAINER_multihashmap32_contains_value ( 435GNUNET_CONTAINER_multihashmap32_contains_value(
441 const struct GNUNET_CONTAINER_MultiHashMap32 *map, 436 const struct GNUNET_CONTAINER_MultiHashMap32 *map,
442 uint32_t key, 437 uint32_t key,
443 const void *value) 438 const void *value)
444{ 439{
445 struct MapEntry *e; 440 struct MapEntry *e;
446 441
447 e = map->map[idx_of (map, key)]; 442 e = map->map[idx_of(map, key)];
448 while (e != NULL) 443 while (e != NULL)
449 { 444 {
450 if ((key == e->key) && (e->value == value)) 445 if ((key == e->key) && (e->value == value))
451 return GNUNET_YES; 446 return GNUNET_YES;
452 e = e->next; 447 e = e->next;
453 } 448 }
454 return GNUNET_NO; 449 return GNUNET_NO;
455} 450}
456 451
@@ -461,7 +456,7 @@ GNUNET_CONTAINER_multihashmap32_contains_value (
461 * @param map the hash map to grow 456 * @param map the hash map to grow
462 */ 457 */
463static void 458static void
464grow (struct GNUNET_CONTAINER_MultiHashMap32 *map) 459grow(struct GNUNET_CONTAINER_MultiHashMap32 *map)
465{ 460{
466 struct MapEntry **old_map; 461 struct MapEntry **old_map;
467 struct MapEntry **new_map; 462 struct MapEntry **new_map;
@@ -477,23 +472,23 @@ grow (struct GNUNET_CONTAINER_MultiHashMap32 *map)
477 new_len = old_len; /* never use 0 */ 472 new_len = old_len; /* never use 0 */
478 if (new_len == old_len) 473 if (new_len == old_len)
479 return; /* nothing changed */ 474 return; /* nothing changed */
480 new_map = GNUNET_malloc_large (new_len * sizeof (struct MapEntry *)); 475 new_map = GNUNET_malloc_large(new_len * sizeof(struct MapEntry *));
481 if (NULL == new_map) 476 if (NULL == new_map)
482 return; /* grow not possible */ 477 return; /* grow not possible */
483 map->modification_counter++; 478 map->modification_counter++;
484 map->map_length = new_len; 479 map->map_length = new_len;
485 map->map = new_map; 480 map->map = new_map;
486 for (unsigned int i = 0; i < old_len; i++) 481 for (unsigned int i = 0; i < old_len; i++)
487 {
488 while (NULL != (e = old_map[i]))
489 { 482 {
490 old_map[i] = e->next; 483 while (NULL != (e = old_map[i]))
491 idx = idx_of (map, e->key); 484 {
492 e->next = new_map[idx]; 485 old_map[i] = e->next;
493 new_map[idx] = e; 486 idx = idx_of(map, e->key);
487 e->next = new_map[idx];
488 new_map[idx] = e;
489 }
494 } 490 }
495 } 491 GNUNET_free(old_map);
496 GNUNET_free (old_map);
497} 492}
498 493
499 494
@@ -510,7 +505,7 @@ grow (struct GNUNET_CONTAINER_MultiHashMap32 *map)
510 * value already exists 505 * value already exists
511 */ 506 */
512int 507int
513GNUNET_CONTAINER_multihashmap32_put ( 508GNUNET_CONTAINER_multihashmap32_put(
514 struct GNUNET_CONTAINER_MultiHashMap32 *map, 509 struct GNUNET_CONTAINER_MultiHashMap32 *map,
515 uint32_t key, 510 uint32_t key,
516 void *value, 511 void *value,
@@ -519,29 +514,29 @@ GNUNET_CONTAINER_multihashmap32_put (
519 struct MapEntry *e; 514 struct MapEntry *e;
520 unsigned int i; 515 unsigned int i;
521 516
522 i = idx_of (map, key); 517 i = idx_of(map, key);
523 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) && 518 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) &&
524 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) 519 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
525 {
526 e = map->map[i];
527 while (e != NULL)
528 { 520 {
529 if (key == e->key) 521 e = map->map[i];
530 { 522 while (e != NULL)
531 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 523 {
532 return GNUNET_SYSERR; 524 if (key == e->key)
533 e->value = value; 525 {
534 return GNUNET_NO; 526 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
535 } 527 return GNUNET_SYSERR;
536 e = e->next; 528 e->value = value;
529 return GNUNET_NO;
530 }
531 e = e->next;
532 }
537 } 533 }
538 }
539 if (map->size / 3 >= map->map_length / 4) 534 if (map->size / 3 >= map->map_length / 4)
540 { 535 {
541 grow (map); 536 grow(map);
542 i = idx_of (map, key); 537 i = idx_of(map, key);
543 } 538 }
544 e = GNUNET_new (struct MapEntry); 539 e = GNUNET_new(struct MapEntry);
545 e->key = key; 540 e->key = key;
546 e->value = value; 541 e->value = value;
547 e->next = map->map[i]; 542 e->next = map->map[i];
@@ -562,7 +557,7 @@ GNUNET_CONTAINER_multihashmap32_put (
562 * GNUNET_SYSERR if it aborted iteration 557 * GNUNET_SYSERR if it aborted iteration
563 */ 558 */
564int 559int
565GNUNET_CONTAINER_multihashmap32_get_multiple ( 560GNUNET_CONTAINER_multihashmap32_get_multiple(
566 struct GNUNET_CONTAINER_MultiHashMap32 *map, 561 struct GNUNET_CONTAINER_MultiHashMap32 *map,
567 uint32_t key, 562 uint32_t key,
568 GNUNET_CONTAINER_MulitHashMapIterator32Callback it, 563 GNUNET_CONTAINER_MulitHashMapIterator32Callback it,
@@ -574,22 +569,22 @@ GNUNET_CONTAINER_multihashmap32_get_multiple (
574 569
575 count = 0; 570 count = 0;
576 ce = &map->next_cache[map->next_cache_off]; 571 ce = &map->next_cache[map->next_cache_off];
577 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 572 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
578 573
579 *ce = map->map[idx_of (map, key)]; 574 *ce = map->map[idx_of(map, key)];
580 while (NULL != (e = *ce)) 575 while (NULL != (e = *ce))
581 {
582 *ce = e->next;
583 if (key != e->key)
584 continue;
585 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, e->value)))
586 { 576 {
587 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 577 *ce = e->next;
588 return GNUNET_SYSERR; 578 if (key != e->key)
579 continue;
580 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, e->value)))
581 {
582 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
583 return GNUNET_SYSERR;
584 }
585 count++;
589 } 586 }
590 count++; 587 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
591 }
592 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
593 return count; 588 return count;
594} 589}
595 590
@@ -607,12 +602,12 @@ GNUNET_CONTAINER_multihashmap32_get_multiple (
607 * @return an iterator over the given multihashmap @a map 602 * @return an iterator over the given multihashmap @a map
608 */ 603 */
609struct GNUNET_CONTAINER_MultiHashMap32Iterator * 604struct GNUNET_CONTAINER_MultiHashMap32Iterator *
610GNUNET_CONTAINER_multihashmap32_iterator_create ( 605GNUNET_CONTAINER_multihashmap32_iterator_create(
611 const struct GNUNET_CONTAINER_MultiHashMap32 *map) 606 const struct GNUNET_CONTAINER_MultiHashMap32 *map)
612{ 607{
613 struct GNUNET_CONTAINER_MultiHashMap32Iterator *iter; 608 struct GNUNET_CONTAINER_MultiHashMap32Iterator *iter;
614 609
615 iter = GNUNET_new (struct GNUNET_CONTAINER_MultiHashMap32Iterator); 610 iter = GNUNET_new(struct GNUNET_CONTAINER_MultiHashMap32Iterator);
616 iter->map = map; 611 iter->map = map;
617 iter->modification_counter = map->modification_counter; 612 iter->modification_counter = map->modification_counter;
618 iter->me = map->map[0]; 613 iter->me = map->map[0];
@@ -635,32 +630,32 @@ GNUNET_CONTAINER_multihashmap32_iterator_create (
635 * #GNUNET_NO if we are out of elements 630 * #GNUNET_NO if we are out of elements
636 */ 631 */
637int 632int
638GNUNET_CONTAINER_multihashmap32_iterator_next ( 633GNUNET_CONTAINER_multihashmap32_iterator_next(
639 struct GNUNET_CONTAINER_MultiHashMap32Iterator *iter, 634 struct GNUNET_CONTAINER_MultiHashMap32Iterator *iter,
640 uint32_t *key, 635 uint32_t *key,
641 const void **value) 636 const void **value)
642{ 637{
643 /* make sure the map has not been modified */ 638 /* make sure the map has not been modified */
644 GNUNET_assert (iter->modification_counter == iter->map->modification_counter); 639 GNUNET_assert(iter->modification_counter == iter->map->modification_counter);
645 640
646 /* look for the next entry, skipping empty buckets */ 641 /* look for the next entry, skipping empty buckets */
647 while (1) 642 while (1)
648 {
649 if (iter->idx >= iter->map->map_length)
650 return GNUNET_NO;
651 if (NULL != iter->me)
652 { 643 {
653 if (NULL != key) 644 if (iter->idx >= iter->map->map_length)
654 *key = iter->me->key; 645 return GNUNET_NO;
655 if (NULL != value) 646 if (NULL != iter->me)
656 *value = iter->me->value; 647 {
657 iter->me = iter->me->next; 648 if (NULL != key)
658 return GNUNET_YES; 649 *key = iter->me->key;
650 if (NULL != value)
651 *value = iter->me->value;
652 iter->me = iter->me->next;
653 return GNUNET_YES;
654 }
655 iter->idx += 1;
656 if (iter->idx < iter->map->map_length)
657 iter->me = iter->map->map[iter->idx];
659 } 658 }
660 iter->idx += 1;
661 if (iter->idx < iter->map->map_length)
662 iter->me = iter->map->map[iter->idx];
663 }
664} 659}
665 660
666 661
@@ -670,10 +665,10 @@ GNUNET_CONTAINER_multihashmap32_iterator_next (
670 * @param iter the iterator to destroy 665 * @param iter the iterator to destroy
671 */ 666 */
672void 667void
673GNUNET_CONTAINER_multihashmap32_iterator_destroy ( 668GNUNET_CONTAINER_multihashmap32_iterator_destroy(
674 struct GNUNET_CONTAINER_MultiHashMapIterator *iter) 669 struct GNUNET_CONTAINER_MultiHashMapIterator *iter)
675{ 670{
676 GNUNET_free (iter); 671 GNUNET_free(iter);
677} 672}
678 673
679 674
diff --git a/src/util/container_multipeermap.c b/src/util/container_multipeermap.c
index d03221cb5..0cd56b9fc 100644
--- a/src/util/container_multipeermap.c
+++ b/src/util/container_multipeermap.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_multipeermap.c 21 * @file util/container_multipeermap.c
22 * @brief hash map where the same key may be present multiple times 22 * @brief hash map where the same key may be present multiple times
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29#define LOG(kind, ...) \ 29#define LOG(kind, ...) \
30 GNUNET_log_from (kind, "util-container-multipeermap", __VA_ARGS__) 30 GNUNET_log_from(kind, "util-container-multipeermap", __VA_ARGS__)
31 31
32/** 32/**
33 * Maximum recursion depth for callbacks of 33 * Maximum recursion depth for callbacks of
@@ -40,9 +40,7 @@
40/** 40/**
41 * An entry in the hash map with the full key. 41 * An entry in the hash map with the full key.
42 */ 42 */
43struct BigMapEntry 43struct BigMapEntry {
44{
45
46 /** 44 /**
47 * Value of the entry. 45 * Value of the entry.
48 */ 46 */
@@ -63,9 +61,7 @@ struct BigMapEntry
63/** 61/**
64 * An entry in the hash map with just a pointer to the key. 62 * An entry in the hash map with just a pointer to the key.
65 */ 63 */
66struct SmallMapEntry 64struct SmallMapEntry {
67{
68
69 /** 65 /**
70 * Value of the entry. 66 * Value of the entry.
71 */ 67 */
@@ -86,8 +82,7 @@ struct SmallMapEntry
86/** 82/**
87 * Entry in the map. 83 * Entry in the map.
88 */ 84 */
89union MapEntry 85union MapEntry {
90{
91 /** 86 /**
92 * Variant used if map entries only contain a pointer to the key. 87 * Variant used if map entries only contain a pointer to the key.
93 */ 88 */
@@ -103,8 +98,7 @@ union MapEntry
103/** 98/**
104 * Internal representation of the hash map. 99 * Internal representation of the hash map.
105 */ 100 */
106struct GNUNET_CONTAINER_MultiPeerMap 101struct GNUNET_CONTAINER_MultiPeerMap {
107{
108 /** 102 /**
109 * All of our buckets. 103 * All of our buckets.
110 */ 104 */
@@ -151,8 +145,7 @@ struct GNUNET_CONTAINER_MultiPeerMap
151 * Cursor into a multipeermap. 145 * Cursor into a multipeermap.
152 * Allows to enumerate elements asynchronously. 146 * Allows to enumerate elements asynchronously.
153 */ 147 */
154struct GNUNET_CONTAINER_MultiPeerMapIterator 148struct GNUNET_CONTAINER_MultiPeerMapIterator {
155{
156 /** 149 /**
157 * Position in the bucket 'idx' 150 * Position in the bucket 'idx'
158 */ 151 */
@@ -192,18 +185,18 @@ struct GNUNET_CONTAINER_MultiPeerMapIterator
192 * @return NULL on error 185 * @return NULL on error
193 */ 186 */
194struct GNUNET_CONTAINER_MultiPeerMap * 187struct GNUNET_CONTAINER_MultiPeerMap *
195GNUNET_CONTAINER_multipeermap_create (unsigned int len, int do_not_copy_keys) 188GNUNET_CONTAINER_multipeermap_create(unsigned int len, int do_not_copy_keys)
196{ 189{
197 struct GNUNET_CONTAINER_MultiPeerMap *map; 190 struct GNUNET_CONTAINER_MultiPeerMap *map;
198 191
199 GNUNET_assert (len > 0); 192 GNUNET_assert(len > 0);
200 map = GNUNET_new (struct GNUNET_CONTAINER_MultiPeerMap); 193 map = GNUNET_new(struct GNUNET_CONTAINER_MultiPeerMap);
201 map->map = GNUNET_malloc_large (len * sizeof (union MapEntry)); 194 map->map = GNUNET_malloc_large(len * sizeof(union MapEntry));
202 if (NULL == map->map) 195 if (NULL == map->map)
203 { 196 {
204 GNUNET_free (map); 197 GNUNET_free(map);
205 return NULL; 198 return NULL;
206 } 199 }
207 map->map_length = len; 200 map->map_length = len;
208 map->use_small_entries = do_not_copy_keys; 201 map->use_small_entries = do_not_copy_keys;
209 return map; 202 return map;
@@ -217,44 +210,44 @@ GNUNET_CONTAINER_multipeermap_create (unsigned int len, int do_not_copy_keys)
217 * @param map the map 210 * @param map the map
218 */ 211 */
219void 212void
220GNUNET_CONTAINER_multipeermap_destroy ( 213GNUNET_CONTAINER_multipeermap_destroy(
221 struct GNUNET_CONTAINER_MultiPeerMap *map) 214 struct GNUNET_CONTAINER_MultiPeerMap *map)
222{ 215{
223 GNUNET_assert (0 == map->next_cache_off); 216 GNUNET_assert(0 == map->next_cache_off);
224 for (unsigned int i = 0; i < map->map_length; i++) 217 for (unsigned int i = 0; i < map->map_length; i++)
225 {
226 union MapEntry me;
227
228 me = map->map[i];
229 if (map->use_small_entries)
230 { 218 {
231 struct SmallMapEntry *sme; 219 union MapEntry me;
232 struct SmallMapEntry *nxt; 220
233 221 me = map->map[i];
234 nxt = me.sme; 222 if (map->use_small_entries)
235 while (NULL != (sme = nxt)) 223 {
236 { 224 struct SmallMapEntry *sme;
237 nxt = sme->next; 225 struct SmallMapEntry *nxt;
238 GNUNET_free (sme); 226
239 } 227 nxt = me.sme;
240 me.sme = NULL; 228 while (NULL != (sme = nxt))
241 } 229 {
242 else 230 nxt = sme->next;
243 { 231 GNUNET_free(sme);
244 struct BigMapEntry *bme; 232 }
245 struct BigMapEntry *nxt; 233 me.sme = NULL;
246 234 }
247 nxt = me.bme; 235 else
248 while (NULL != (bme = nxt)) 236 {
249 { 237 struct BigMapEntry *bme;
250 nxt = bme->next; 238 struct BigMapEntry *nxt;
251 GNUNET_free (bme); 239
252 } 240 nxt = me.bme;
253 me.bme = NULL; 241 while (NULL != (bme = nxt))
242 {
243 nxt = bme->next;
244 GNUNET_free(bme);
245 }
246 me.bme = NULL;
247 }
254 } 248 }
255 } 249 GNUNET_free(map->map);
256 GNUNET_free (map->map); 250 GNUNET_free(map);
257 GNUNET_free (map);
258} 251}
259 252
260 253
@@ -266,13 +259,13 @@ GNUNET_CONTAINER_multipeermap_destroy (
266 * @return offset into the "map" array of "map" 259 * @return offset into the "map" array of "map"
267 */ 260 */
268static unsigned int 261static unsigned int
269idx_of (const struct GNUNET_CONTAINER_MultiPeerMap *map, 262idx_of(const struct GNUNET_CONTAINER_MultiPeerMap *map,
270 const struct GNUNET_PeerIdentity *key) 263 const struct GNUNET_PeerIdentity *key)
271{ 264{
272 unsigned int kx; 265 unsigned int kx;
273 266
274 GNUNET_assert (NULL != map); 267 GNUNET_assert(NULL != map);
275 GNUNET_memcpy (&kx, key, sizeof (kx)); 268 GNUNET_memcpy(&kx, key, sizeof(kx));
276 return kx % map->map_length; 269 return kx % map->map_length;
277} 270}
278 271
@@ -284,7 +277,7 @@ idx_of (const struct GNUNET_CONTAINER_MultiPeerMap *map,
284 * @return the number of key value pairs 277 * @return the number of key value pairs
285 */ 278 */
286unsigned int 279unsigned int
287GNUNET_CONTAINER_multipeermap_size ( 280GNUNET_CONTAINER_multipeermap_size(
288 const struct GNUNET_CONTAINER_MultiPeerMap *map) 281 const struct GNUNET_CONTAINER_MultiPeerMap *map)
289{ 282{
290 return map->size; 283 return map->size;
@@ -302,25 +295,25 @@ GNUNET_CONTAINER_multipeermap_size (
302 * key-value pairs with value NULL 295 * key-value pairs with value NULL
303 */ 296 */
304void * 297void *
305GNUNET_CONTAINER_multipeermap_get ( 298GNUNET_CONTAINER_multipeermap_get(
306 const struct GNUNET_CONTAINER_MultiPeerMap *map, 299 const struct GNUNET_CONTAINER_MultiPeerMap *map,
307 const struct GNUNET_PeerIdentity *key) 300 const struct GNUNET_PeerIdentity *key)
308{ 301{
309 union MapEntry me; 302 union MapEntry me;
310 303
311 me = map->map[idx_of (map, key)]; 304 me = map->map[idx_of(map, key)];
312 if (map->use_small_entries) 305 if (map->use_small_entries)
313 { 306 {
314 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 307 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
315 if (0 == GNUNET_memcmp (key, sme->key)) 308 if (0 == GNUNET_memcmp(key, sme->key))
316 return sme->value; 309 return sme->value;
317 } 310 }
318 else 311 else
319 { 312 {
320 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 313 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
321 if (0 == GNUNET_memcmp (key, &bme->key)) 314 if (0 == GNUNET_memcmp(key, &bme->key))
322 return bme->value; 315 return bme->value;
323 } 316 }
324 return NULL; 317 return NULL;
325} 318}
326 319
@@ -335,7 +328,7 @@ GNUNET_CONTAINER_multipeermap_get (
335 * #GNUNET_SYSERR if it aborted iteration 328 * #GNUNET_SYSERR if it aborted iteration
336 */ 329 */
337int 330int
338GNUNET_CONTAINER_multipeermap_iterate ( 331GNUNET_CONTAINER_multipeermap_iterate(
339 struct GNUNET_CONTAINER_MultiPeerMap *map, 332 struct GNUNET_CONTAINER_MultiPeerMap *map,
340 GNUNET_CONTAINER_PeerMapIterator it, 333 GNUNET_CONTAINER_PeerMapIterator it,
341 void *it_cls) 334 void *it_cls)
@@ -346,53 +339,53 @@ GNUNET_CONTAINER_multipeermap_iterate (
346 struct GNUNET_PeerIdentity kc; 339 struct GNUNET_PeerIdentity kc;
347 340
348 count = 0; 341 count = 0;
349 GNUNET_assert (NULL != map); 342 GNUNET_assert(NULL != map);
350 ce = &map->next_cache[map->next_cache_off]; 343 ce = &map->next_cache[map->next_cache_off];
351 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 344 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
352 for (unsigned int i = 0; i < map->map_length; i++) 345 for (unsigned int i = 0; i < map->map_length; i++)
353 {
354 me = map->map[i];
355 if (map->use_small_entries)
356 { 346 {
357 struct SmallMapEntry *sme; 347 me = map->map[i];
358 348 if (map->use_small_entries)
359 ce->sme = me.sme;
360 while (NULL != (sme = ce->sme))
361 {
362 ce->sme = sme->next;
363 if (NULL != it)
364 { 349 {
365 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 350 struct SmallMapEntry *sme;
366 { 351
367 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 352 ce->sme = me.sme;
368 return GNUNET_SYSERR; 353 while (NULL != (sme = ce->sme))
369 } 354 {
355 ce->sme = sme->next;
356 if (NULL != it)
357 {
358 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
359 {
360 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
361 return GNUNET_SYSERR;
362 }
363 }
364 count++;
365 }
370 } 366 }
371 count++; 367 else
372 }
373 }
374 else
375 {
376 struct BigMapEntry *bme;
377
378 ce->bme = me.bme;
379 while (NULL != (bme = ce->bme))
380 {
381 ce->bme = bme->next;
382 if (NULL != it)
383 { 368 {
384 kc = bme->key; 369 struct BigMapEntry *bme;
385 if (GNUNET_OK != it (it_cls, &kc, bme->value)) 370
386 { 371 ce->bme = me.bme;
387 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 372 while (NULL != (bme = ce->bme))
388 return GNUNET_SYSERR; 373 {
389 } 374 ce->bme = bme->next;
375 if (NULL != it)
376 {
377 kc = bme->key;
378 if (GNUNET_OK != it(it_cls, &kc, bme->value))
379 {
380 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
381 return GNUNET_SYSERR;
382 }
383 }
384 count++;
385 }
390 } 386 }
391 count++;
392 }
393 } 387 }
394 } 388 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
395 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
396 return count; 389 return count;
397} 390}
398 391
@@ -405,8 +398,8 @@ GNUNET_CONTAINER_multipeermap_iterate (
405 * @param bme the entry that is about to be free'd 398 * @param bme the entry that is about to be free'd
406 */ 399 */
407static void 400static void
408update_next_cache_bme (struct GNUNET_CONTAINER_MultiPeerMap *map, 401update_next_cache_bme(struct GNUNET_CONTAINER_MultiPeerMap *map,
409 const struct BigMapEntry *bme) 402 const struct BigMapEntry *bme)
410{ 403{
411 for (unsigned int i = 0; i < map->next_cache_off; i++) 404 for (unsigned int i = 0; i < map->next_cache_off; i++)
412 if (map->next_cache[i].bme == bme) 405 if (map->next_cache[i].bme == bme)
@@ -422,8 +415,8 @@ update_next_cache_bme (struct GNUNET_CONTAINER_MultiPeerMap *map,
422 * @param sme the entry that is about to be free'd 415 * @param sme the entry that is about to be free'd
423 */ 416 */
424static void 417static void
425update_next_cache_sme (struct GNUNET_CONTAINER_MultiPeerMap *map, 418update_next_cache_sme(struct GNUNET_CONTAINER_MultiPeerMap *map,
426 const struct SmallMapEntry *sme) 419 const struct SmallMapEntry *sme)
427{ 420{
428 for (unsigned int i = 0; i < map->next_cache_off; i++) 421 for (unsigned int i = 0; i < map->next_cache_off; i++)
429 if (map->next_cache[i].sme == sme) 422 if (map->next_cache[i].sme == sme)
@@ -443,56 +436,56 @@ update_next_cache_sme (struct GNUNET_CONTAINER_MultiPeerMap *map,
443 * is not in the map 436 * is not in the map
444 */ 437 */
445int 438int
446GNUNET_CONTAINER_multipeermap_remove (struct GNUNET_CONTAINER_MultiPeerMap *map, 439GNUNET_CONTAINER_multipeermap_remove(struct GNUNET_CONTAINER_MultiPeerMap *map,
447 const struct GNUNET_PeerIdentity *key, 440 const struct GNUNET_PeerIdentity *key,
448 const void *value) 441 const void *value)
449{ 442{
450 union MapEntry me; 443 union MapEntry me;
451 unsigned int i; 444 unsigned int i;
452 445
453 map->modification_counter++; 446 map->modification_counter++;
454 i = idx_of (map, key); 447 i = idx_of(map, key);
455 me = map->map[i]; 448 me = map->map[i];
456 if (map->use_small_entries) 449 if (map->use_small_entries)
457 {
458 struct SmallMapEntry *p = NULL;
459
460 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
461 { 450 {
462 if ((0 == GNUNET_memcmp (key, sme->key)) && (value == sme->value)) 451 struct SmallMapEntry *p = NULL;
463 { 452
464 if (NULL == p) 453 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
465 map->map[i].sme = sme->next; 454 {
466 else 455 if ((0 == GNUNET_memcmp(key, sme->key)) && (value == sme->value))
467 p->next = sme->next; 456 {
468 update_next_cache_sme (map, sme); 457 if (NULL == p)
469 GNUNET_free (sme); 458 map->map[i].sme = sme->next;
470 map->size--; 459 else
471 return GNUNET_YES; 460 p->next = sme->next;
472 } 461 update_next_cache_sme(map, sme);
473 p = sme; 462 GNUNET_free(sme);
463 map->size--;
464 return GNUNET_YES;
465 }
466 p = sme;
467 }
474 } 468 }
475 }
476 else 469 else
477 {
478 struct BigMapEntry *p = NULL;
479
480 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
481 { 470 {
482 if ((0 == GNUNET_memcmp (key, &bme->key)) && (value == bme->value)) 471 struct BigMapEntry *p = NULL;
483 { 472
484 if (NULL == p) 473 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
485 map->map[i].bme = bme->next; 474 {
486 else 475 if ((0 == GNUNET_memcmp(key, &bme->key)) && (value == bme->value))
487 p->next = bme->next; 476 {
488 update_next_cache_bme (map, bme); 477 if (NULL == p)
489 GNUNET_free (bme); 478 map->map[i].bme = bme->next;
490 map->size--; 479 else
491 return GNUNET_YES; 480 p->next = bme->next;
492 } 481 update_next_cache_bme(map, bme);
493 p = bme; 482 GNUNET_free(bme);
483 map->size--;
484 return GNUNET_YES;
485 }
486 p = bme;
487 }
494 } 488 }
495 }
496 return GNUNET_NO; 489 return GNUNET_NO;
497} 490}
498 491
@@ -506,7 +499,7 @@ GNUNET_CONTAINER_multipeermap_remove (struct GNUNET_CONTAINER_MultiPeerMap *map,
506 * @return number of values removed 499 * @return number of values removed
507 */ 500 */
508int 501int
509GNUNET_CONTAINER_multipeermap_remove_all ( 502GNUNET_CONTAINER_multipeermap_remove_all(
510 struct GNUNET_CONTAINER_MultiPeerMap *map, 503 struct GNUNET_CONTAINER_MultiPeerMap *map,
511 const struct GNUNET_PeerIdentity *key) 504 const struct GNUNET_PeerIdentity *key)
512{ 505{
@@ -517,70 +510,70 @@ GNUNET_CONTAINER_multipeermap_remove_all (
517 map->modification_counter++; 510 map->modification_counter++;
518 511
519 ret = 0; 512 ret = 0;
520 i = idx_of (map, key); 513 i = idx_of(map, key);
521 me = map->map[i]; 514 me = map->map[i];
522 if (map->use_small_entries) 515 if (map->use_small_entries)
523 {
524 struct SmallMapEntry *sme;
525 struct SmallMapEntry *p;
526
527 p = NULL;
528 sme = me.sme;
529 while (NULL != sme)
530 { 516 {
531 if (0 == GNUNET_memcmp (key, sme->key)) 517 struct SmallMapEntry *sme;
532 { 518 struct SmallMapEntry *p;
533 if (NULL == p) 519
534 map->map[i].sme = sme->next; 520 p = NULL;
535 else 521 sme = me.sme;
536 p->next = sme->next; 522 while (NULL != sme)
537 update_next_cache_sme (map, sme); 523 {
538 GNUNET_free (sme); 524 if (0 == GNUNET_memcmp(key, sme->key))
539 map->size--; 525 {
540 if (NULL == p) 526 if (NULL == p)
541 sme = map->map[i].sme; 527 map->map[i].sme = sme->next;
542 else 528 else
543 sme = p->next; 529 p->next = sme->next;
544 ret++; 530 update_next_cache_sme(map, sme);
545 } 531 GNUNET_free(sme);
546 else 532 map->size--;
547 { 533 if (NULL == p)
548 p = sme; 534 sme = map->map[i].sme;
549 sme = sme->next; 535 else
550 } 536 sme = p->next;
537 ret++;
538 }
539 else
540 {
541 p = sme;
542 sme = sme->next;
543 }
544 }
551 } 545 }
552 }
553 else 546 else
554 {
555 struct BigMapEntry *bme;
556 struct BigMapEntry *p;
557
558 p = NULL;
559 bme = me.bme;
560 while (NULL != bme)
561 { 547 {
562 if (0 == GNUNET_memcmp (key, &bme->key)) 548 struct BigMapEntry *bme;
563 { 549 struct BigMapEntry *p;
564 if (NULL == p) 550
565 map->map[i].bme = bme->next; 551 p = NULL;
566 else 552 bme = me.bme;
567 p->next = bme->next; 553 while (NULL != bme)
568 update_next_cache_bme (map, bme); 554 {
569 GNUNET_free (bme); 555 if (0 == GNUNET_memcmp(key, &bme->key))
570 map->size--; 556 {
571 if (NULL == p) 557 if (NULL == p)
572 bme = map->map[i].bme; 558 map->map[i].bme = bme->next;
573 else 559 else
574 bme = p->next; 560 p->next = bme->next;
575 ret++; 561 update_next_cache_bme(map, bme);
576 } 562 GNUNET_free(bme);
577 else 563 map->size--;
578 { 564 if (NULL == p)
579 p = bme; 565 bme = map->map[i].bme;
580 bme = bme->next; 566 else
581 } 567 bme = p->next;
568 ret++;
569 }
570 else
571 {
572 p = bme;
573 bme = bme->next;
574 }
575 }
582 } 576 }
583 }
584 return ret; 577 return ret;
585} 578}
586 579
@@ -595,25 +588,25 @@ GNUNET_CONTAINER_multipeermap_remove_all (
595 * #GNUNET_NO if not 588 * #GNUNET_NO if not
596 */ 589 */
597int 590int
598GNUNET_CONTAINER_multipeermap_contains ( 591GNUNET_CONTAINER_multipeermap_contains(
599 const struct GNUNET_CONTAINER_MultiPeerMap *map, 592 const struct GNUNET_CONTAINER_MultiPeerMap *map,
600 const struct GNUNET_PeerIdentity *key) 593 const struct GNUNET_PeerIdentity *key)
601{ 594{
602 union MapEntry me; 595 union MapEntry me;
603 596
604 me = map->map[idx_of (map, key)]; 597 me = map->map[idx_of(map, key)];
605 if (map->use_small_entries) 598 if (map->use_small_entries)
606 { 599 {
607 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 600 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
608 if (0 == GNUNET_memcmp (key, sme->key)) 601 if (0 == GNUNET_memcmp(key, sme->key))
609 return GNUNET_YES; 602 return GNUNET_YES;
610 } 603 }
611 else 604 else
612 { 605 {
613 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 606 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
614 if (0 == GNUNET_memcmp (key, &bme->key)) 607 if (0 == GNUNET_memcmp(key, &bme->key))
615 return GNUNET_YES; 608 return GNUNET_YES;
616 } 609 }
617 return GNUNET_NO; 610 return GNUNET_NO;
618} 611}
619 612
@@ -629,26 +622,26 @@ GNUNET_CONTAINER_multipeermap_contains (
629 * #GNUNET_NO if not 622 * #GNUNET_NO if not
630 */ 623 */
631int 624int
632GNUNET_CONTAINER_multipeermap_contains_value ( 625GNUNET_CONTAINER_multipeermap_contains_value(
633 const struct GNUNET_CONTAINER_MultiPeerMap *map, 626 const struct GNUNET_CONTAINER_MultiPeerMap *map,
634 const struct GNUNET_PeerIdentity *key, 627 const struct GNUNET_PeerIdentity *key,
635 const void *value) 628 const void *value)
636{ 629{
637 union MapEntry me; 630 union MapEntry me;
638 631
639 me = map->map[idx_of (map, key)]; 632 me = map->map[idx_of(map, key)];
640 if (map->use_small_entries) 633 if (map->use_small_entries)
641 { 634 {
642 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 635 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
643 if ((0 == GNUNET_memcmp (key, sme->key)) && (sme->value == value)) 636 if ((0 == GNUNET_memcmp(key, sme->key)) && (sme->value == value))
644 return GNUNET_YES; 637 return GNUNET_YES;
645 } 638 }
646 else 639 else
647 { 640 {
648 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 641 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
649 if ((0 == GNUNET_memcmp (key, &bme->key)) && (bme->value == value)) 642 if ((0 == GNUNET_memcmp(key, &bme->key)) && (bme->value == value))
650 return GNUNET_YES; 643 return GNUNET_YES;
651 } 644 }
652 return GNUNET_NO; 645 return GNUNET_NO;
653} 646}
654 647
@@ -659,7 +652,7 @@ GNUNET_CONTAINER_multipeermap_contains_value (
659 * @param map the hash map to grow 652 * @param map the hash map to grow
660 */ 653 */
661static void 654static void
662grow (struct GNUNET_CONTAINER_MultiPeerMap *map) 655grow(struct GNUNET_CONTAINER_MultiPeerMap *map)
663{ 656{
664 union MapEntry *old_map; 657 union MapEntry *old_map;
665 union MapEntry *new_map; 658 union MapEntry *new_map;
@@ -669,46 +662,46 @@ grow (struct GNUNET_CONTAINER_MultiPeerMap *map)
669 662
670 old_map = map->map; 663 old_map = map->map;
671 old_len = map->map_length; 664 old_len = map->map_length;
672 GNUNET_assert (0 != old_len); 665 GNUNET_assert(0 != old_len);
673 new_len = old_len * 2; 666 new_len = old_len * 2;
674 if (0 == new_len) /* 2^31 * 2 == 0 */ 667 if (0 == new_len) /* 2^31 * 2 == 0 */
675 new_len = old_len; /* never use 0 */ 668 new_len = old_len; /* never use 0 */
676 if (new_len == old_len) 669 if (new_len == old_len)
677 return; /* nothing changed */ 670 return; /* nothing changed */
678 new_map = GNUNET_malloc_large (new_len * sizeof (union MapEntry)); 671 new_map = GNUNET_malloc_large(new_len * sizeof(union MapEntry));
679 if (NULL == new_map) 672 if (NULL == new_map)
680 return; /* grow not possible */ 673 return; /* grow not possible */
681 map->modification_counter++; 674 map->modification_counter++;
682 map->map_length = new_len; 675 map->map_length = new_len;
683 map->map = new_map; 676 map->map = new_map;
684 for (unsigned int i = 0; i < old_len; i++) 677 for (unsigned int i = 0; i < old_len; i++)
685 {
686 if (map->use_small_entries)
687 {
688 struct SmallMapEntry *sme;
689
690 while (NULL != (sme = old_map[i].sme))
691 {
692 old_map[i].sme = sme->next;
693 idx = idx_of (map, sme->key);
694 sme->next = new_map[idx].sme;
695 new_map[idx].sme = sme;
696 }
697 }
698 else
699 { 678 {
700 struct BigMapEntry *bme; 679 if (map->use_small_entries)
701 680 {
702 while (NULL != (bme = old_map[i].bme)) 681 struct SmallMapEntry *sme;
703 { 682
704 old_map[i].bme = bme->next; 683 while (NULL != (sme = old_map[i].sme))
705 idx = idx_of (map, &bme->key); 684 {
706 bme->next = new_map[idx].bme; 685 old_map[i].sme = sme->next;
707 new_map[idx].bme = bme; 686 idx = idx_of(map, sme->key);
708 } 687 sme->next = new_map[idx].sme;
688 new_map[idx].sme = sme;
689 }
690 }
691 else
692 {
693 struct BigMapEntry *bme;
694
695 while (NULL != (bme = old_map[i].bme))
696 {
697 old_map[i].bme = bme->next;
698 idx = idx_of(map, &bme->key);
699 bme->next = new_map[idx].bme;
700 new_map[idx].bme = bme;
701 }
702 }
709 } 703 }
710 } 704 GNUNET_free(old_map);
711 GNUNET_free (old_map);
712} 705}
713 706
714 707
@@ -725,71 +718,71 @@ grow (struct GNUNET_CONTAINER_MultiPeerMap *map)
725 * value already exists 718 * value already exists
726 */ 719 */
727int 720int
728GNUNET_CONTAINER_multipeermap_put (struct GNUNET_CONTAINER_MultiPeerMap *map, 721GNUNET_CONTAINER_multipeermap_put(struct GNUNET_CONTAINER_MultiPeerMap *map,
729 const struct GNUNET_PeerIdentity *key, 722 const struct GNUNET_PeerIdentity *key,
730 void *value, 723 void *value,
731 enum GNUNET_CONTAINER_MultiHashMapOption opt) 724 enum GNUNET_CONTAINER_MultiHashMapOption opt)
732{ 725{
733 union MapEntry me; 726 union MapEntry me;
734 unsigned int i; 727 unsigned int i;
735 728
736 i = idx_of (map, key); 729 i = idx_of(map, key);
737 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) && 730 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) &&
738 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) 731 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
739 {
740 me = map->map[i];
741 if (map->use_small_entries)
742 { 732 {
743 struct SmallMapEntry *sme; 733 me = map->map[i];
744 734 if (map->use_small_entries)
745 for (sme = me.sme; NULL != sme; sme = sme->next)
746 if (0 == GNUNET_memcmp (key, sme->key))
747 { 735 {
748 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 736 struct SmallMapEntry *sme;
749 return GNUNET_SYSERR; 737
750 sme->value = value; 738 for (sme = me.sme; NULL != sme; sme = sme->next)
751 return GNUNET_NO; 739 if (0 == GNUNET_memcmp(key, sme->key))
740 {
741 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
742 return GNUNET_SYSERR;
743 sme->value = value;
744 return GNUNET_NO;
745 }
752 } 746 }
753 } 747 else
754 else
755 {
756 struct BigMapEntry *bme;
757
758 for (bme = me.bme; NULL != bme; bme = bme->next)
759 if (0 == GNUNET_memcmp (key, &bme->key))
760 { 748 {
761 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 749 struct BigMapEntry *bme;
762 return GNUNET_SYSERR; 750
763 bme->value = value; 751 for (bme = me.bme; NULL != bme; bme = bme->next)
764 return GNUNET_NO; 752 if (0 == GNUNET_memcmp(key, &bme->key))
753 {
754 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
755 return GNUNET_SYSERR;
756 bme->value = value;
757 return GNUNET_NO;
758 }
765 } 759 }
766 } 760 }
767 }
768 if (map->size / 3 >= map->map_length / 4) 761 if (map->size / 3 >= map->map_length / 4)
769 { 762 {
770 grow (map); 763 grow(map);
771 i = idx_of (map, key); 764 i = idx_of(map, key);
772 } 765 }
773 if (map->use_small_entries) 766 if (map->use_small_entries)
774 { 767 {
775 struct SmallMapEntry *sme; 768 struct SmallMapEntry *sme;
776 769
777 sme = GNUNET_new (struct SmallMapEntry); 770 sme = GNUNET_new(struct SmallMapEntry);
778 sme->key = key; 771 sme->key = key;
779 sme->value = value; 772 sme->value = value;
780 sme->next = map->map[i].sme; 773 sme->next = map->map[i].sme;
781 map->map[i].sme = sme; 774 map->map[i].sme = sme;
782 } 775 }
783 else 776 else
784 { 777 {
785 struct BigMapEntry *bme; 778 struct BigMapEntry *bme;
786 779
787 bme = GNUNET_new (struct BigMapEntry); 780 bme = GNUNET_new(struct BigMapEntry);
788 bme->key = *key; 781 bme->key = *key;
789 bme->value = value; 782 bme->value = value;
790 bme->next = map->map[i].bme; 783 bme->next = map->map[i].bme;
791 map->map[i].bme = bme; 784 map->map[i].bme = bme;
792 } 785 }
793 map->size++; 786 map->size++;
794 return GNUNET_OK; 787 return GNUNET_OK;
795} 788}
@@ -806,7 +799,7 @@ GNUNET_CONTAINER_multipeermap_put (struct GNUNET_CONTAINER_MultiPeerMap *map,
806 * #GNUNET_SYSERR if it aborted iteration 799 * #GNUNET_SYSERR if it aborted iteration
807 */ 800 */
808int 801int
809GNUNET_CONTAINER_multipeermap_get_multiple ( 802GNUNET_CONTAINER_multipeermap_get_multiple(
810 struct GNUNET_CONTAINER_MultiPeerMap *map, 803 struct GNUNET_CONTAINER_MultiPeerMap *map,
811 const struct GNUNET_PeerIdentity *key, 804 const struct GNUNET_PeerIdentity *key,
812 GNUNET_CONTAINER_PeerMapIterator it, 805 GNUNET_CONTAINER_PeerMapIterator it,
@@ -817,46 +810,46 @@ GNUNET_CONTAINER_multipeermap_get_multiple (
817 union MapEntry *ce; 810 union MapEntry *ce;
818 811
819 ce = &map->next_cache[map->next_cache_off]; 812 ce = &map->next_cache[map->next_cache_off];
820 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 813 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
821 count = 0; 814 count = 0;
822 me = map->map[idx_of (map, key)]; 815 me = map->map[idx_of(map, key)];
823 if (map->use_small_entries) 816 if (map->use_small_entries)
824 {
825 struct SmallMapEntry *sme;
826
827 ce->sme = me.sme;
828 while (NULL != (sme = ce->sme))
829 { 817 {
830 ce->sme = sme->next; 818 struct SmallMapEntry *sme;
831 if (0 != GNUNET_memcmp (key, sme->key)) 819
832 continue; 820 ce->sme = me.sme;
833 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, sme->value))) 821 while (NULL != (sme = ce->sme))
834 { 822 {
835 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 823 ce->sme = sme->next;
836 return GNUNET_SYSERR; 824 if (0 != GNUNET_memcmp(key, sme->key))
837 } 825 continue;
838 count++; 826 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, sme->value)))
827 {
828 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
829 return GNUNET_SYSERR;
830 }
831 count++;
832 }
839 } 833 }
840 }
841 else 834 else
842 {
843 struct BigMapEntry *bme;
844
845 ce->bme = me.bme;
846 while (NULL != (bme = ce->bme))
847 { 835 {
848 ce->bme = bme->next; 836 struct BigMapEntry *bme;
849 if (0 != GNUNET_memcmp (key, &bme->key)) 837
850 continue; 838 ce->bme = me.bme;
851 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, bme->value))) 839 while (NULL != (bme = ce->bme))
852 { 840 {
853 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 841 ce->bme = bme->next;
854 return GNUNET_SYSERR; 842 if (0 != GNUNET_memcmp(key, &bme->key))
855 } 843 continue;
856 count++; 844 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, bme->value)))
845 {
846 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
847 return GNUNET_SYSERR;
848 }
849 count++;
850 }
857 } 851 }
858 } 852 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
859 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
860 return count; 853 return count;
861} 854}
862 855
@@ -873,7 +866,7 @@ GNUNET_CONTAINER_multipeermap_get_multiple (
873 * @return the number of key value pairs processed, zero or one. 866 * @return the number of key value pairs processed, zero or one.
874 */ 867 */
875unsigned int 868unsigned int
876GNUNET_CONTAINER_multipeermap_get_random ( 869GNUNET_CONTAINER_multipeermap_get_random(
877 const struct GNUNET_CONTAINER_MultiPeerMap *map, 870 const struct GNUNET_CONTAINER_MultiPeerMap *map,
878 GNUNET_CONTAINER_PeerMapIterator it, 871 GNUNET_CONTAINER_PeerMapIterator it,
879 void *it_cls) 872 void *it_cls)
@@ -885,48 +878,48 @@ GNUNET_CONTAINER_multipeermap_get_random (
885 return 0; 878 return 0;
886 if (NULL == it) 879 if (NULL == it)
887 return 1; 880 return 1;
888 off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, map->size); 881 off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, map->size);
889 for (unsigned int idx = 0; idx < map->map_length; idx++) 882 for (unsigned int idx = 0; idx < map->map_length; idx++)
890 {
891 me = map->map[idx];
892 if (map->use_small_entries)
893 { 883 {
894 struct SmallMapEntry *sme; 884 me = map->map[idx];
895 struct SmallMapEntry *nxt; 885 if (map->use_small_entries)
896
897 nxt = me.sme;
898 while (NULL != (sme = nxt))
899 {
900 nxt = sme->next;
901 if (0 == off)
902 { 886 {
903 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 887 struct SmallMapEntry *sme;
904 return GNUNET_SYSERR; 888 struct SmallMapEntry *nxt;
905 return 1; 889
890 nxt = me.sme;
891 while (NULL != (sme = nxt))
892 {
893 nxt = sme->next;
894 if (0 == off)
895 {
896 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
897 return GNUNET_SYSERR;
898 return 1;
899 }
900 off--;
901 }
906 } 902 }
907 off--; 903 else
908 }
909 }
910 else
911 {
912 struct BigMapEntry *bme;
913 struct BigMapEntry *nxt;
914
915 nxt = me.bme;
916 while (NULL != (bme = nxt))
917 {
918 nxt = bme->next;
919 if (0 == off)
920 { 904 {
921 if (GNUNET_OK != it (it_cls, &bme->key, bme->value)) 905 struct BigMapEntry *bme;
922 return GNUNET_SYSERR; 906 struct BigMapEntry *nxt;
923 return 1; 907
908 nxt = me.bme;
909 while (NULL != (bme = nxt))
910 {
911 nxt = bme->next;
912 if (0 == off)
913 {
914 if (GNUNET_OK != it(it_cls, &bme->key, bme->value))
915 return GNUNET_SYSERR;
916 return 1;
917 }
918 off--;
919 }
924 } 920 }
925 off--;
926 }
927 } 921 }
928 } 922 GNUNET_break(0);
929 GNUNET_break (0);
930 return GNUNET_SYSERR; 923 return GNUNET_SYSERR;
931} 924}
932 925
@@ -944,12 +937,12 @@ GNUNET_CONTAINER_multipeermap_get_random (
944 * @return an iterator over the given multipeermap 'map' 937 * @return an iterator over the given multipeermap 'map'
945 */ 938 */
946struct GNUNET_CONTAINER_MultiPeerMapIterator * 939struct GNUNET_CONTAINER_MultiPeerMapIterator *
947GNUNET_CONTAINER_multipeermap_iterator_create ( 940GNUNET_CONTAINER_multipeermap_iterator_create(
948 const struct GNUNET_CONTAINER_MultiPeerMap *map) 941 const struct GNUNET_CONTAINER_MultiPeerMap *map)
949{ 942{
950 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter; 943 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter;
951 944
952 iter = GNUNET_new (struct GNUNET_CONTAINER_MultiPeerMapIterator); 945 iter = GNUNET_new(struct GNUNET_CONTAINER_MultiPeerMapIterator);
953 iter->map = map; 946 iter->map = map;
954 iter->modification_counter = map->modification_counter; 947 iter->modification_counter = map->modification_counter;
955 iter->me = map->map[0]; 948 iter->me = map->map[0];
@@ -972,47 +965,47 @@ GNUNET_CONTAINER_multipeermap_iterator_create (
972 * #GNUNET_NO if we are out of elements 965 * #GNUNET_NO if we are out of elements
973 */ 966 */
974int 967int
975GNUNET_CONTAINER_multipeermap_iterator_next ( 968GNUNET_CONTAINER_multipeermap_iterator_next(
976 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter, 969 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter,
977 struct GNUNET_PeerIdentity *key, 970 struct GNUNET_PeerIdentity *key,
978 const void **value) 971 const void **value)
979{ 972{
980 /* make sure the map has not been modified */ 973 /* make sure the map has not been modified */
981 GNUNET_assert (iter->modification_counter == iter->map->modification_counter); 974 GNUNET_assert(iter->modification_counter == iter->map->modification_counter);
982 975
983 /* look for the next entry, skipping empty buckets */ 976 /* look for the next entry, skipping empty buckets */
984 while (1) 977 while (1)
985 {
986 if (iter->idx >= iter->map->map_length)
987 return GNUNET_NO;
988 if (GNUNET_YES == iter->map->use_small_entries)
989 { 978 {
990 if (NULL != iter->me.sme) 979 if (iter->idx >= iter->map->map_length)
991 { 980 return GNUNET_NO;
992 if (NULL != key) 981 if (GNUNET_YES == iter->map->use_small_entries)
993 *key = *iter->me.sme->key; 982 {
994 if (NULL != value) 983 if (NULL != iter->me.sme)
995 *value = iter->me.sme->value; 984 {
996 iter->me.sme = iter->me.sme->next; 985 if (NULL != key)
997 return GNUNET_YES; 986 *key = *iter->me.sme->key;
998 } 987 if (NULL != value)
999 } 988 *value = iter->me.sme->value;
1000 else 989 iter->me.sme = iter->me.sme->next;
1001 { 990 return GNUNET_YES;
1002 if (NULL != iter->me.bme) 991 }
1003 { 992 }
1004 if (NULL != key) 993 else
1005 *key = iter->me.bme->key; 994 {
1006 if (NULL != value) 995 if (NULL != iter->me.bme)
1007 *value = iter->me.bme->value; 996 {
1008 iter->me.bme = iter->me.bme->next; 997 if (NULL != key)
1009 return GNUNET_YES; 998 *key = iter->me.bme->key;
1010 } 999 if (NULL != value)
1000 *value = iter->me.bme->value;
1001 iter->me.bme = iter->me.bme->next;
1002 return GNUNET_YES;
1003 }
1004 }
1005 iter->idx += 1;
1006 if (iter->idx < iter->map->map_length)
1007 iter->me = iter->map->map[iter->idx];
1011 } 1008 }
1012 iter->idx += 1;
1013 if (iter->idx < iter->map->map_length)
1014 iter->me = iter->map->map[iter->idx];
1015 }
1016} 1009}
1017 1010
1018 1011
@@ -1022,10 +1015,10 @@ GNUNET_CONTAINER_multipeermap_iterator_next (
1022 * @param iter the iterator to destroy 1015 * @param iter the iterator to destroy
1023 */ 1016 */
1024void 1017void
1025GNUNET_CONTAINER_multipeermap_iterator_destroy ( 1018GNUNET_CONTAINER_multipeermap_iterator_destroy(
1026 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter) 1019 struct GNUNET_CONTAINER_MultiPeerMapIterator *iter)
1027{ 1020{
1028 GNUNET_free (iter); 1021 GNUNET_free(iter);
1029} 1022}
1030 1023
1031 1024
diff --git a/src/util/container_multishortmap.c b/src/util/container_multishortmap.c
index 0371b0a48..4f2bc149d 100644
--- a/src/util/container_multishortmap.c
+++ b/src/util/container_multishortmap.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_multishortmap.c 21 * @file util/container_multishortmap.c
22 * @brief hash map where the same key may be present multiple times 22 * @brief hash map where the same key may be present multiple times
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29#define LOG(kind, ...) \ 29#define LOG(kind, ...) \
30 GNUNET_log_from (kind, "util-container-multishortmap", __VA_ARGS__) 30 GNUNET_log_from(kind, "util-container-multishortmap", __VA_ARGS__)
31 31
32/** 32/**
33 * Maximum recursion depth for callbacks of 33 * Maximum recursion depth for callbacks of
@@ -41,9 +41,7 @@
41/** 41/**
42 * An entry in the hash map with the full key. 42 * An entry in the hash map with the full key.
43 */ 43 */
44struct BigMapEntry 44struct BigMapEntry {
45{
46
47 /** 45 /**
48 * Value of the entry. 46 * Value of the entry.
49 */ 47 */
@@ -64,9 +62,7 @@ struct BigMapEntry
64/** 62/**
65 * An entry in the hash map with just a pointer to the key. 63 * An entry in the hash map with just a pointer to the key.
66 */ 64 */
67struct SmallMapEntry 65struct SmallMapEntry {
68{
69
70 /** 66 /**
71 * Value of the entry. 67 * Value of the entry.
72 */ 68 */
@@ -87,8 +83,7 @@ struct SmallMapEntry
87/** 83/**
88 * Entry in the map. 84 * Entry in the map.
89 */ 85 */
90union MapEntry 86union MapEntry {
91{
92 /** 87 /**
93 * Variant used if map entries only contain a pointer to the key. 88 * Variant used if map entries only contain a pointer to the key.
94 */ 89 */
@@ -104,8 +99,7 @@ union MapEntry
104/** 99/**
105 * Internal representation of the hash map. 100 * Internal representation of the hash map.
106 */ 101 */
107struct GNUNET_CONTAINER_MultiShortmap 102struct GNUNET_CONTAINER_MultiShortmap {
108{
109 /** 103 /**
110 * All of our buckets. 104 * All of our buckets.
111 */ 105 */
@@ -152,8 +146,7 @@ struct GNUNET_CONTAINER_MultiShortmap
152 * Cursor into a multishortmap. 146 * Cursor into a multishortmap.
153 * Allows to enumerate elements asynchronously. 147 * Allows to enumerate elements asynchronously.
154 */ 148 */
155struct GNUNET_CONTAINER_MultiShortmapIterator 149struct GNUNET_CONTAINER_MultiShortmapIterator {
156{
157 /** 150 /**
158 * Position in the bucket 'idx' 151 * Position in the bucket 'idx'
159 */ 152 */
@@ -193,18 +186,18 @@ struct GNUNET_CONTAINER_MultiShortmapIterator
193 * @return NULL on error 186 * @return NULL on error
194 */ 187 */
195struct GNUNET_CONTAINER_MultiShortmap * 188struct GNUNET_CONTAINER_MultiShortmap *
196GNUNET_CONTAINER_multishortmap_create (unsigned int len, int do_not_copy_keys) 189GNUNET_CONTAINER_multishortmap_create(unsigned int len, int do_not_copy_keys)
197{ 190{
198 struct GNUNET_CONTAINER_MultiShortmap *map; 191 struct GNUNET_CONTAINER_MultiShortmap *map;
199 192
200 GNUNET_assert (len > 0); 193 GNUNET_assert(len > 0);
201 map = GNUNET_new (struct GNUNET_CONTAINER_MultiShortmap); 194 map = GNUNET_new(struct GNUNET_CONTAINER_MultiShortmap);
202 map->map = GNUNET_malloc_large (len * sizeof (union MapEntry)); 195 map->map = GNUNET_malloc_large(len * sizeof(union MapEntry));
203 if (NULL == map->map) 196 if (NULL == map->map)
204 { 197 {
205 GNUNET_free (map); 198 GNUNET_free(map);
206 return NULL; 199 return NULL;
207 } 200 }
208 map->map_length = len; 201 map->map_length = len;
209 map->use_small_entries = do_not_copy_keys; 202 map->use_small_entries = do_not_copy_keys;
210 return map; 203 return map;
@@ -218,44 +211,44 @@ GNUNET_CONTAINER_multishortmap_create (unsigned int len, int do_not_copy_keys)
218 * @param map the map 211 * @param map the map
219 */ 212 */
220void 213void
221GNUNET_CONTAINER_multishortmap_destroy ( 214GNUNET_CONTAINER_multishortmap_destroy(
222 struct GNUNET_CONTAINER_MultiShortmap *map) 215 struct GNUNET_CONTAINER_MultiShortmap *map)
223{ 216{
224 GNUNET_assert (0 == map->next_cache_off); 217 GNUNET_assert(0 == map->next_cache_off);
225 for (unsigned int i = 0; i < map->map_length; i++) 218 for (unsigned int i = 0; i < map->map_length; i++)
226 {
227 union MapEntry me;
228
229 me = map->map[i];
230 if (map->use_small_entries)
231 {
232 struct SmallMapEntry *sme;
233 struct SmallMapEntry *nxt;
234
235 nxt = me.sme;
236 while (NULL != (sme = nxt))
237 {
238 nxt = sme->next;
239 GNUNET_free (sme);
240 }
241 me.sme = NULL;
242 }
243 else
244 { 219 {
245 struct BigMapEntry *bme; 220 union MapEntry me;
246 struct BigMapEntry *nxt; 221
247 222 me = map->map[i];
248 nxt = me.bme; 223 if (map->use_small_entries)
249 while (NULL != (bme = nxt)) 224 {
250 { 225 struct SmallMapEntry *sme;
251 nxt = bme->next; 226 struct SmallMapEntry *nxt;
252 GNUNET_free (bme); 227
253 } 228 nxt = me.sme;
254 me.bme = NULL; 229 while (NULL != (sme = nxt))
230 {
231 nxt = sme->next;
232 GNUNET_free(sme);
233 }
234 me.sme = NULL;
235 }
236 else
237 {
238 struct BigMapEntry *bme;
239 struct BigMapEntry *nxt;
240
241 nxt = me.bme;
242 while (NULL != (bme = nxt))
243 {
244 nxt = bme->next;
245 GNUNET_free(bme);
246 }
247 me.bme = NULL;
248 }
255 } 249 }
256 } 250 GNUNET_free(map->map);
257 GNUNET_free (map->map); 251 GNUNET_free(map);
258 GNUNET_free (map);
259} 252}
260 253
261 254
@@ -267,13 +260,13 @@ GNUNET_CONTAINER_multishortmap_destroy (
267 * @return offset into the "map" array of "map" 260 * @return offset into the "map" array of "map"
268 */ 261 */
269static unsigned int 262static unsigned int
270idx_of (const struct GNUNET_CONTAINER_MultiShortmap *map, 263idx_of(const struct GNUNET_CONTAINER_MultiShortmap *map,
271 const struct GNUNET_ShortHashCode *key) 264 const struct GNUNET_ShortHashCode *key)
272{ 265{
273 unsigned int kx; 266 unsigned int kx;
274 267
275 GNUNET_assert (NULL != map); 268 GNUNET_assert(NULL != map);
276 GNUNET_memcpy (&kx, key, sizeof (kx)); 269 GNUNET_memcpy(&kx, key, sizeof(kx));
277 return kx % map->map_length; 270 return kx % map->map_length;
278} 271}
279 272
@@ -285,7 +278,7 @@ idx_of (const struct GNUNET_CONTAINER_MultiShortmap *map,
285 * @return the number of key value pairs 278 * @return the number of key value pairs
286 */ 279 */
287unsigned int 280unsigned int
288GNUNET_CONTAINER_multishortmap_size ( 281GNUNET_CONTAINER_multishortmap_size(
289 const struct GNUNET_CONTAINER_MultiShortmap *map) 282 const struct GNUNET_CONTAINER_MultiShortmap *map)
290{ 283{
291 return map->size; 284 return map->size;
@@ -303,25 +296,25 @@ GNUNET_CONTAINER_multishortmap_size (
303 * key-value pairs with value NULL 296 * key-value pairs with value NULL
304 */ 297 */
305void * 298void *
306GNUNET_CONTAINER_multishortmap_get ( 299GNUNET_CONTAINER_multishortmap_get(
307 const struct GNUNET_CONTAINER_MultiShortmap *map, 300 const struct GNUNET_CONTAINER_MultiShortmap *map,
308 const struct GNUNET_ShortHashCode *key) 301 const struct GNUNET_ShortHashCode *key)
309{ 302{
310 union MapEntry me; 303 union MapEntry me;
311 304
312 me = map->map[idx_of (map, key)]; 305 me = map->map[idx_of(map, key)];
313 if (map->use_small_entries) 306 if (map->use_small_entries)
314 { 307 {
315 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 308 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
316 if (0 == GNUNET_memcmp (key, sme->key)) 309 if (0 == GNUNET_memcmp(key, sme->key))
317 return sme->value; 310 return sme->value;
318 } 311 }
319 else 312 else
320 { 313 {
321 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 314 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
322 if (0 == GNUNET_memcmp (key, &bme->key)) 315 if (0 == GNUNET_memcmp(key, &bme->key))
323 return bme->value; 316 return bme->value;
324 } 317 }
325 return NULL; 318 return NULL;
326} 319}
327 320
@@ -336,7 +329,7 @@ GNUNET_CONTAINER_multishortmap_get (
336 * #GNUNET_SYSERR if it aborted iteration 329 * #GNUNET_SYSERR if it aborted iteration
337 */ 330 */
338int 331int
339GNUNET_CONTAINER_multishortmap_iterate ( 332GNUNET_CONTAINER_multishortmap_iterate(
340 struct GNUNET_CONTAINER_MultiShortmap *map, 333 struct GNUNET_CONTAINER_MultiShortmap *map,
341 GNUNET_CONTAINER_ShortmapIterator it, 334 GNUNET_CONTAINER_ShortmapIterator it,
342 void *it_cls) 335 void *it_cls)
@@ -347,50 +340,50 @@ GNUNET_CONTAINER_multishortmap_iterate (
347 struct GNUNET_ShortHashCode kc; 340 struct GNUNET_ShortHashCode kc;
348 341
349 count = 0; 342 count = 0;
350 GNUNET_assert (NULL != map); 343 GNUNET_assert(NULL != map);
351 ce = &map->next_cache[map->next_cache_off]; 344 ce = &map->next_cache[map->next_cache_off];
352 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 345 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
353 for (unsigned int i = 0; i < map->map_length; i++) 346 for (unsigned int i = 0; i < map->map_length; i++)
354 {
355 me = map->map[i];
356 if (map->use_small_entries)
357 { 347 {
358 struct SmallMapEntry *sme; 348 me = map->map[i];
359 349 if (map->use_small_entries)
360 ce->sme = me.sme;
361 while (NULL != (sme = ce->sme))
362 {
363 ce->sme = sme->next;
364 if ((NULL != it) && (GNUNET_OK != it (it_cls, sme->key, sme->value)))
365 { 350 {
366 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 351 struct SmallMapEntry *sme;
367 return GNUNET_SYSERR; 352
353 ce->sme = me.sme;
354 while (NULL != (sme = ce->sme))
355 {
356 ce->sme = sme->next;
357 if ((NULL != it) && (GNUNET_OK != it(it_cls, sme->key, sme->value)))
358 {
359 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
360 return GNUNET_SYSERR;
361 }
362 count++;
363 }
368 } 364 }
369 count++; 365 else
370 }
371 }
372 else
373 {
374 struct BigMapEntry *bme;
375
376 ce->bme = me.bme;
377 while (NULL != (bme = ce->bme))
378 {
379 ce->bme = bme->next;
380 if (NULL != it)
381 { 366 {
382 kc = bme->key; 367 struct BigMapEntry *bme;
383 if (GNUNET_OK != it (it_cls, &kc, bme->value)) 368
384 { 369 ce->bme = me.bme;
385 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 370 while (NULL != (bme = ce->bme))
386 return GNUNET_SYSERR; 371 {
387 } 372 ce->bme = bme->next;
373 if (NULL != it)
374 {
375 kc = bme->key;
376 if (GNUNET_OK != it(it_cls, &kc, bme->value))
377 {
378 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
379 return GNUNET_SYSERR;
380 }
381 }
382 count++;
383 }
388 } 384 }
389 count++;
390 }
391 } 385 }
392 } 386 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
393 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
394 return count; 387 return count;
395} 388}
396 389
@@ -403,8 +396,8 @@ GNUNET_CONTAINER_multishortmap_iterate (
403 * @param bme the entry that is about to be free'd 396 * @param bme the entry that is about to be free'd
404 */ 397 */
405static void 398static void
406update_next_cache_bme (struct GNUNET_CONTAINER_MultiShortmap *map, 399update_next_cache_bme(struct GNUNET_CONTAINER_MultiShortmap *map,
407 const struct BigMapEntry *bme) 400 const struct BigMapEntry *bme)
408{ 401{
409 for (unsigned int i = 0; i < map->next_cache_off; i++) 402 for (unsigned int i = 0; i < map->next_cache_off; i++)
410 if (map->next_cache[i].bme == bme) 403 if (map->next_cache[i].bme == bme)
@@ -420,8 +413,8 @@ update_next_cache_bme (struct GNUNET_CONTAINER_MultiShortmap *map,
420 * @param sme the entry that is about to be free'd 413 * @param sme the entry that is about to be free'd
421 */ 414 */
422static void 415static void
423update_next_cache_sme (struct GNUNET_CONTAINER_MultiShortmap *map, 416update_next_cache_sme(struct GNUNET_CONTAINER_MultiShortmap *map,
424 const struct SmallMapEntry *sme) 417 const struct SmallMapEntry *sme)
425{ 418{
426 for (unsigned int i = 0; i < map->next_cache_off; i++) 419 for (unsigned int i = 0; i < map->next_cache_off; i++)
427 if (map->next_cache[i].sme == sme) 420 if (map->next_cache[i].sme == sme)
@@ -441,7 +434,7 @@ update_next_cache_sme (struct GNUNET_CONTAINER_MultiShortmap *map,
441 * is not in the map 434 * is not in the map
442 */ 435 */
443int 436int
444GNUNET_CONTAINER_multishortmap_remove ( 437GNUNET_CONTAINER_multishortmap_remove(
445 struct GNUNET_CONTAINER_MultiShortmap *map, 438 struct GNUNET_CONTAINER_MultiShortmap *map,
446 const struct GNUNET_ShortHashCode *key, 439 const struct GNUNET_ShortHashCode *key,
447 const void *value) 440 const void *value)
@@ -450,48 +443,48 @@ GNUNET_CONTAINER_multishortmap_remove (
450 unsigned int i; 443 unsigned int i;
451 444
452 map->modification_counter++; 445 map->modification_counter++;
453 i = idx_of (map, key); 446 i = idx_of(map, key);
454 me = map->map[i]; 447 me = map->map[i];
455 if (map->use_small_entries) 448 if (map->use_small_entries)
456 {
457 struct SmallMapEntry *p = NULL;
458
459 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
460 { 449 {
461 if ((0 == GNUNET_memcmp (key, sme->key)) && (value == sme->value)) 450 struct SmallMapEntry *p = NULL;
462 { 451
463 if (NULL == p) 452 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
464 map->map[i].sme = sme->next; 453 {
465 else 454 if ((0 == GNUNET_memcmp(key, sme->key)) && (value == sme->value))
466 p->next = sme->next; 455 {
467 update_next_cache_sme (map, sme); 456 if (NULL == p)
468 GNUNET_free (sme); 457 map->map[i].sme = sme->next;
469 map->size--; 458 else
470 return GNUNET_YES; 459 p->next = sme->next;
471 } 460 update_next_cache_sme(map, sme);
472 p = sme; 461 GNUNET_free(sme);
462 map->size--;
463 return GNUNET_YES;
464 }
465 p = sme;
466 }
473 } 467 }
474 }
475 else 468 else
476 {
477 struct BigMapEntry *p = NULL;
478
479 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
480 { 469 {
481 if ((0 == GNUNET_memcmp (key, &bme->key)) && (value == bme->value)) 470 struct BigMapEntry *p = NULL;
482 { 471
483 if (NULL == p) 472 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
484 map->map[i].bme = bme->next; 473 {
485 else 474 if ((0 == GNUNET_memcmp(key, &bme->key)) && (value == bme->value))
486 p->next = bme->next; 475 {
487 update_next_cache_bme (map, bme); 476 if (NULL == p)
488 GNUNET_free (bme); 477 map->map[i].bme = bme->next;
489 map->size--; 478 else
490 return GNUNET_YES; 479 p->next = bme->next;
491 } 480 update_next_cache_bme(map, bme);
492 p = bme; 481 GNUNET_free(bme);
482 map->size--;
483 return GNUNET_YES;
484 }
485 p = bme;
486 }
493 } 487 }
494 }
495 return GNUNET_NO; 488 return GNUNET_NO;
496} 489}
497 490
@@ -505,7 +498,7 @@ GNUNET_CONTAINER_multishortmap_remove (
505 * @return number of values removed 498 * @return number of values removed
506 */ 499 */
507int 500int
508GNUNET_CONTAINER_multishortmap_remove_all ( 501GNUNET_CONTAINER_multishortmap_remove_all(
509 struct GNUNET_CONTAINER_MultiShortmap *map, 502 struct GNUNET_CONTAINER_MultiShortmap *map,
510 const struct GNUNET_ShortHashCode *key) 503 const struct GNUNET_ShortHashCode *key)
511{ 504{
@@ -516,70 +509,70 @@ GNUNET_CONTAINER_multishortmap_remove_all (
516 map->modification_counter++; 509 map->modification_counter++;
517 510
518 ret = 0; 511 ret = 0;
519 i = idx_of (map, key); 512 i = idx_of(map, key);
520 me = map->map[i]; 513 me = map->map[i];
521 if (map->use_small_entries) 514 if (map->use_small_entries)
522 {
523 struct SmallMapEntry *sme;
524 struct SmallMapEntry *p;
525
526 p = NULL;
527 sme = me.sme;
528 while (NULL != sme)
529 { 515 {
530 if (0 == GNUNET_memcmp (key, sme->key)) 516 struct SmallMapEntry *sme;
531 { 517 struct SmallMapEntry *p;
532 if (NULL == p) 518
533 map->map[i].sme = sme->next; 519 p = NULL;
534 else 520 sme = me.sme;
535 p->next = sme->next; 521 while (NULL != sme)
536 update_next_cache_sme (map, sme); 522 {
537 GNUNET_free (sme); 523 if (0 == GNUNET_memcmp(key, sme->key))
538 map->size--; 524 {
539 if (NULL == p) 525 if (NULL == p)
540 sme = map->map[i].sme; 526 map->map[i].sme = sme->next;
541 else 527 else
542 sme = p->next; 528 p->next = sme->next;
543 ret++; 529 update_next_cache_sme(map, sme);
544 } 530 GNUNET_free(sme);
545 else 531 map->size--;
546 { 532 if (NULL == p)
547 p = sme; 533 sme = map->map[i].sme;
548 sme = sme->next; 534 else
549 } 535 sme = p->next;
536 ret++;
537 }
538 else
539 {
540 p = sme;
541 sme = sme->next;
542 }
543 }
550 } 544 }
551 }
552 else 545 else
553 {
554 struct BigMapEntry *bme;
555 struct BigMapEntry *p;
556
557 p = NULL;
558 bme = me.bme;
559 while (NULL != bme)
560 { 546 {
561 if (0 == GNUNET_memcmp (key, &bme->key)) 547 struct BigMapEntry *bme;
562 { 548 struct BigMapEntry *p;
563 if (NULL == p) 549
564 map->map[i].bme = bme->next; 550 p = NULL;
565 else 551 bme = me.bme;
566 p->next = bme->next; 552 while (NULL != bme)
567 update_next_cache_bme (map, bme); 553 {
568 GNUNET_free (bme); 554 if (0 == GNUNET_memcmp(key, &bme->key))
569 map->size--; 555 {
570 if (NULL == p) 556 if (NULL == p)
571 bme = map->map[i].bme; 557 map->map[i].bme = bme->next;
572 else 558 else
573 bme = p->next; 559 p->next = bme->next;
574 ret++; 560 update_next_cache_bme(map, bme);
575 } 561 GNUNET_free(bme);
576 else 562 map->size--;
577 { 563 if (NULL == p)
578 p = bme; 564 bme = map->map[i].bme;
579 bme = bme->next; 565 else
580 } 566 bme = p->next;
567 ret++;
568 }
569 else
570 {
571 p = bme;
572 bme = bme->next;
573 }
574 }
581 } 575 }
582 }
583 return ret; 576 return ret;
584} 577}
585 578
@@ -594,25 +587,25 @@ GNUNET_CONTAINER_multishortmap_remove_all (
594 * #GNUNET_NO if not 587 * #GNUNET_NO if not
595 */ 588 */
596int 589int
597GNUNET_CONTAINER_multishortmap_contains ( 590GNUNET_CONTAINER_multishortmap_contains(
598 const struct GNUNET_CONTAINER_MultiShortmap *map, 591 const struct GNUNET_CONTAINER_MultiShortmap *map,
599 const struct GNUNET_ShortHashCode *key) 592 const struct GNUNET_ShortHashCode *key)
600{ 593{
601 union MapEntry me; 594 union MapEntry me;
602 595
603 me = map->map[idx_of (map, key)]; 596 me = map->map[idx_of(map, key)];
604 if (map->use_small_entries) 597 if (map->use_small_entries)
605 { 598 {
606 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 599 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
607 if (0 == GNUNET_memcmp (key, sme->key)) 600 if (0 == GNUNET_memcmp(key, sme->key))
608 return GNUNET_YES; 601 return GNUNET_YES;
609 } 602 }
610 else 603 else
611 { 604 {
612 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 605 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
613 if (0 == GNUNET_memcmp (key, &bme->key)) 606 if (0 == GNUNET_memcmp(key, &bme->key))
614 return GNUNET_YES; 607 return GNUNET_YES;
615 } 608 }
616 return GNUNET_NO; 609 return GNUNET_NO;
617} 610}
618 611
@@ -628,26 +621,26 @@ GNUNET_CONTAINER_multishortmap_contains (
628 * #GNUNET_NO if not 621 * #GNUNET_NO if not
629 */ 622 */
630int 623int
631GNUNET_CONTAINER_multishortmap_contains_value ( 624GNUNET_CONTAINER_multishortmap_contains_value(
632 const struct GNUNET_CONTAINER_MultiShortmap *map, 625 const struct GNUNET_CONTAINER_MultiShortmap *map,
633 const struct GNUNET_ShortHashCode *key, 626 const struct GNUNET_ShortHashCode *key,
634 const void *value) 627 const void *value)
635{ 628{
636 union MapEntry me; 629 union MapEntry me;
637 630
638 me = map->map[idx_of (map, key)]; 631 me = map->map[idx_of(map, key)];
639 if (map->use_small_entries) 632 if (map->use_small_entries)
640 { 633 {
641 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 634 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
642 if ((0 == GNUNET_memcmp (key, sme->key)) && (sme->value == value)) 635 if ((0 == GNUNET_memcmp(key, sme->key)) && (sme->value == value))
643 return GNUNET_YES; 636 return GNUNET_YES;
644 } 637 }
645 else 638 else
646 { 639 {
647 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 640 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
648 if ((0 == GNUNET_memcmp (key, &bme->key)) && (bme->value == value)) 641 if ((0 == GNUNET_memcmp(key, &bme->key)) && (bme->value == value))
649 return GNUNET_YES; 642 return GNUNET_YES;
650 } 643 }
651 return GNUNET_NO; 644 return GNUNET_NO;
652} 645}
653 646
@@ -658,7 +651,7 @@ GNUNET_CONTAINER_multishortmap_contains_value (
658 * @param map the hash map to grow 651 * @param map the hash map to grow
659 */ 652 */
660static void 653static void
661grow (struct GNUNET_CONTAINER_MultiShortmap *map) 654grow(struct GNUNET_CONTAINER_MultiShortmap *map)
662{ 655{
663 union MapEntry *old_map; 656 union MapEntry *old_map;
664 union MapEntry *new_map; 657 union MapEntry *new_map;
@@ -673,40 +666,40 @@ grow (struct GNUNET_CONTAINER_MultiShortmap *map)
673 new_len = old_len; /* never use 0 */ 666 new_len = old_len; /* never use 0 */
674 if (new_len == old_len) 667 if (new_len == old_len)
675 return; /* nothing changed */ 668 return; /* nothing changed */
676 new_map = GNUNET_malloc_large (new_len * sizeof (union MapEntry)); 669 new_map = GNUNET_malloc_large(new_len * sizeof(union MapEntry));
677 if (NULL == new_map) 670 if (NULL == new_map)
678 return; /* grow not possible */ 671 return; /* grow not possible */
679 map->modification_counter++; 672 map->modification_counter++;
680 map->map_length = new_len; 673 map->map_length = new_len;
681 map->map = new_map; 674 map->map = new_map;
682 for (unsigned int i = 0; i < old_len; i++) 675 for (unsigned int i = 0; i < old_len; i++)
683 {
684 if (map->use_small_entries)
685 {
686 struct SmallMapEntry *sme;
687
688 while (NULL != (sme = old_map[i].sme))
689 {
690 old_map[i].sme = sme->next;
691 idx = idx_of (map, sme->key);
692 sme->next = new_map[idx].sme;
693 new_map[idx].sme = sme;
694 }
695 }
696 else
697 { 676 {
698 struct BigMapEntry *bme; 677 if (map->use_small_entries)
699 678 {
700 while (NULL != (bme = old_map[i].bme)) 679 struct SmallMapEntry *sme;
701 { 680
702 old_map[i].bme = bme->next; 681 while (NULL != (sme = old_map[i].sme))
703 idx = idx_of (map, &bme->key); 682 {
704 bme->next = new_map[idx].bme; 683 old_map[i].sme = sme->next;
705 new_map[idx].bme = bme; 684 idx = idx_of(map, sme->key);
706 } 685 sme->next = new_map[idx].sme;
686 new_map[idx].sme = sme;
687 }
688 }
689 else
690 {
691 struct BigMapEntry *bme;
692
693 while (NULL != (bme = old_map[i].bme))
694 {
695 old_map[i].bme = bme->next;
696 idx = idx_of(map, &bme->key);
697 bme->next = new_map[idx].bme;
698 new_map[idx].bme = bme;
699 }
700 }
707 } 701 }
708 } 702 GNUNET_free(old_map);
709 GNUNET_free (old_map);
710} 703}
711 704
712 705
@@ -723,7 +716,7 @@ grow (struct GNUNET_CONTAINER_MultiShortmap *map)
723 * value already exists 716 * value already exists
724 */ 717 */
725int 718int
726GNUNET_CONTAINER_multishortmap_put ( 719GNUNET_CONTAINER_multishortmap_put(
727 struct GNUNET_CONTAINER_MultiShortmap *map, 720 struct GNUNET_CONTAINER_MultiShortmap *map,
728 const struct GNUNET_ShortHashCode *key, 721 const struct GNUNET_ShortHashCode *key,
729 void *value, 722 void *value,
@@ -732,59 +725,59 @@ GNUNET_CONTAINER_multishortmap_put (
732 union MapEntry me; 725 union MapEntry me;
733 unsigned int i; 726 unsigned int i;
734 727
735 i = idx_of (map, key); 728 i = idx_of(map, key);
736 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) && 729 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) &&
737 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) 730 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
738 {
739 me = map->map[i];
740 if (map->use_small_entries)
741 { 731 {
742 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 732 me = map->map[i];
743 if (0 == GNUNET_memcmp (key, sme->key)) 733 if (map->use_small_entries)
744 { 734 {
745 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 735 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
746 return GNUNET_SYSERR; 736 if (0 == GNUNET_memcmp(key, sme->key))
747 sme->value = value; 737 {
748 return GNUNET_NO; 738 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
739 return GNUNET_SYSERR;
740 sme->value = value;
741 return GNUNET_NO;
742 }
749 } 743 }
750 } 744 else
751 else
752 {
753 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
754 if (0 == GNUNET_memcmp (key, &bme->key))
755 { 745 {
756 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 746 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
757 return GNUNET_SYSERR; 747 if (0 == GNUNET_memcmp(key, &bme->key))
758 bme->value = value; 748 {
759 return GNUNET_NO; 749 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
750 return GNUNET_SYSERR;
751 bme->value = value;
752 return GNUNET_NO;
753 }
760 } 754 }
761 } 755 }
762 }
763 if (map->size / 3 >= map->map_length / 4) 756 if (map->size / 3 >= map->map_length / 4)
764 { 757 {
765 grow (map); 758 grow(map);
766 i = idx_of (map, key); 759 i = idx_of(map, key);
767 } 760 }
768 if (map->use_small_entries) 761 if (map->use_small_entries)
769 { 762 {
770 struct SmallMapEntry *sme; 763 struct SmallMapEntry *sme;
771 764
772 sme = GNUNET_new (struct SmallMapEntry); 765 sme = GNUNET_new(struct SmallMapEntry);
773 sme->key = key; 766 sme->key = key;
774 sme->value = value; 767 sme->value = value;
775 sme->next = map->map[i].sme; 768 sme->next = map->map[i].sme;
776 map->map[i].sme = sme; 769 map->map[i].sme = sme;
777 } 770 }
778 else 771 else
779 { 772 {
780 struct BigMapEntry *bme; 773 struct BigMapEntry *bme;
781 774
782 bme = GNUNET_new (struct BigMapEntry); 775 bme = GNUNET_new(struct BigMapEntry);
783 bme->key = *key; 776 bme->key = *key;
784 bme->value = value; 777 bme->value = value;
785 bme->next = map->map[i].bme; 778 bme->next = map->map[i].bme;
786 map->map[i].bme = bme; 779 map->map[i].bme = bme;
787 } 780 }
788 map->size++; 781 map->size++;
789 return GNUNET_OK; 782 return GNUNET_OK;
790} 783}
@@ -801,7 +794,7 @@ GNUNET_CONTAINER_multishortmap_put (
801 * #GNUNET_SYSERR if it aborted iteration 794 * #GNUNET_SYSERR if it aborted iteration
802 */ 795 */
803int 796int
804GNUNET_CONTAINER_multishortmap_get_multiple ( 797GNUNET_CONTAINER_multishortmap_get_multiple(
805 struct GNUNET_CONTAINER_MultiShortmap *map, 798 struct GNUNET_CONTAINER_MultiShortmap *map,
806 const struct GNUNET_ShortHashCode *key, 799 const struct GNUNET_ShortHashCode *key,
807 GNUNET_CONTAINER_ShortmapIterator it, 800 GNUNET_CONTAINER_ShortmapIterator it,
@@ -812,46 +805,46 @@ GNUNET_CONTAINER_multishortmap_get_multiple (
812 union MapEntry *ce; 805 union MapEntry *ce;
813 806
814 ce = &map->next_cache[map->next_cache_off]; 807 ce = &map->next_cache[map->next_cache_off];
815 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 808 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
816 count = 0; 809 count = 0;
817 me = map->map[idx_of (map, key)]; 810 me = map->map[idx_of(map, key)];
818 if (map->use_small_entries) 811 if (map->use_small_entries)
819 {
820 struct SmallMapEntry *sme;
821
822 ce->sme = me.sme;
823 while (NULL != (sme = ce->sme))
824 { 812 {
825 ce->sme = sme->next; 813 struct SmallMapEntry *sme;
826 if (0 != GNUNET_memcmp (key, sme->key)) 814
827 continue; 815 ce->sme = me.sme;
828 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, sme->value))) 816 while (NULL != (sme = ce->sme))
829 { 817 {
830 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 818 ce->sme = sme->next;
831 return GNUNET_SYSERR; 819 if (0 != GNUNET_memcmp(key, sme->key))
832 } 820 continue;
833 count++; 821 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, sme->value)))
822 {
823 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
824 return GNUNET_SYSERR;
825 }
826 count++;
827 }
834 } 828 }
835 }
836 else 829 else
837 {
838 struct BigMapEntry *bme;
839
840 ce->bme = me.bme;
841 while (NULL != (bme = ce->bme))
842 { 830 {
843 ce->bme = bme->next; 831 struct BigMapEntry *bme;
844 if (0 != GNUNET_memcmp (key, &bme->key)) 832
845 continue; 833 ce->bme = me.bme;
846 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, bme->value))) 834 while (NULL != (bme = ce->bme))
847 { 835 {
848 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 836 ce->bme = bme->next;
849 return GNUNET_SYSERR; 837 if (0 != GNUNET_memcmp(key, &bme->key))
850 } 838 continue;
851 count++; 839 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, bme->value)))
840 {
841 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
842 return GNUNET_SYSERR;
843 }
844 count++;
845 }
852 } 846 }
853 } 847 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
854 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
855 return count; 848 return count;
856} 849}
857 850
@@ -868,7 +861,7 @@ GNUNET_CONTAINER_multishortmap_get_multiple (
868 * @return the number of key value pairs processed, zero or one. 861 * @return the number of key value pairs processed, zero or one.
869 */ 862 */
870unsigned int 863unsigned int
871GNUNET_CONTAINER_multishortmap_get_random ( 864GNUNET_CONTAINER_multishortmap_get_random(
872 const struct GNUNET_CONTAINER_MultiShortmap *map, 865 const struct GNUNET_CONTAINER_MultiShortmap *map,
873 GNUNET_CONTAINER_ShortmapIterator it, 866 GNUNET_CONTAINER_ShortmapIterator it,
874 void *it_cls) 867 void *it_cls)
@@ -880,38 +873,38 @@ GNUNET_CONTAINER_multishortmap_get_random (
880 return 0; 873 return 0;
881 if (NULL == it) 874 if (NULL == it)
882 return 1; 875 return 1;
883 off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, map->size); 876 off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, map->size);
884 for (unsigned int idx = 0; idx < map->map_length; idx++) 877 for (unsigned int idx = 0; idx < map->map_length; idx++)
885 {
886 me = map->map[idx];
887 if (map->use_small_entries)
888 { 878 {
889 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 879 me = map->map[idx];
890 { 880 if (map->use_small_entries)
891 if (0 == off)
892 { 881 {
893 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 882 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
894 return GNUNET_SYSERR; 883 {
895 return 1; 884 if (0 == off)
885 {
886 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
887 return GNUNET_SYSERR;
888 return 1;
889 }
890 off--;
891 }
896 } 892 }
897 off--; 893 else
898 }
899 }
900 else
901 {
902 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
903 {
904 if (0 == off)
905 { 894 {
906 if (GNUNET_OK != it (it_cls, &bme->key, bme->value)) 895 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
907 return GNUNET_SYSERR; 896 {
908 return 1; 897 if (0 == off)
898 {
899 if (GNUNET_OK != it(it_cls, &bme->key, bme->value))
900 return GNUNET_SYSERR;
901 return 1;
902 }
903 off--;
904 }
909 } 905 }
910 off--;
911 }
912 } 906 }
913 } 907 GNUNET_break(0);
914 GNUNET_break (0);
915 return GNUNET_SYSERR; 908 return GNUNET_SYSERR;
916} 909}
917 910
@@ -929,12 +922,12 @@ GNUNET_CONTAINER_multishortmap_get_random (
929 * @return an iterator over the given multishortmap 'map' 922 * @return an iterator over the given multishortmap 'map'
930 */ 923 */
931struct GNUNET_CONTAINER_MultiShortmapIterator * 924struct GNUNET_CONTAINER_MultiShortmapIterator *
932GNUNET_CONTAINER_multishortmap_iterator_create ( 925GNUNET_CONTAINER_multishortmap_iterator_create(
933 const struct GNUNET_CONTAINER_MultiShortmap *map) 926 const struct GNUNET_CONTAINER_MultiShortmap *map)
934{ 927{
935 struct GNUNET_CONTAINER_MultiShortmapIterator *iter; 928 struct GNUNET_CONTAINER_MultiShortmapIterator *iter;
936 929
937 iter = GNUNET_new (struct GNUNET_CONTAINER_MultiShortmapIterator); 930 iter = GNUNET_new(struct GNUNET_CONTAINER_MultiShortmapIterator);
938 iter->map = map; 931 iter->map = map;
939 iter->modification_counter = map->modification_counter; 932 iter->modification_counter = map->modification_counter;
940 iter->me = map->map[0]; 933 iter->me = map->map[0];
@@ -957,47 +950,47 @@ GNUNET_CONTAINER_multishortmap_iterator_create (
957 * #GNUNET_NO if we are out of elements 950 * #GNUNET_NO if we are out of elements
958 */ 951 */
959int 952int
960GNUNET_CONTAINER_multishortmap_iterator_next ( 953GNUNET_CONTAINER_multishortmap_iterator_next(
961 struct GNUNET_CONTAINER_MultiShortmapIterator *iter, 954 struct GNUNET_CONTAINER_MultiShortmapIterator *iter,
962 struct GNUNET_ShortHashCode *key, 955 struct GNUNET_ShortHashCode *key,
963 const void **value) 956 const void **value)
964{ 957{
965 /* make sure the map has not been modified */ 958 /* make sure the map has not been modified */
966 GNUNET_assert (iter->modification_counter == iter->map->modification_counter); 959 GNUNET_assert(iter->modification_counter == iter->map->modification_counter);
967 960
968 /* look for the next entry, skipping empty buckets */ 961 /* look for the next entry, skipping empty buckets */
969 while (1) 962 while (1)
970 {
971 if (iter->idx >= iter->map->map_length)
972 return GNUNET_NO;
973 if (GNUNET_YES == iter->map->use_small_entries)
974 { 963 {
975 if (NULL != iter->me.sme) 964 if (iter->idx >= iter->map->map_length)
976 { 965 return GNUNET_NO;
977 if (NULL != key) 966 if (GNUNET_YES == iter->map->use_small_entries)
978 *key = *iter->me.sme->key; 967 {
979 if (NULL != value) 968 if (NULL != iter->me.sme)
980 *value = iter->me.sme->value; 969 {
981 iter->me.sme = iter->me.sme->next; 970 if (NULL != key)
982 return GNUNET_YES; 971 *key = *iter->me.sme->key;
983 } 972 if (NULL != value)
984 } 973 *value = iter->me.sme->value;
985 else 974 iter->me.sme = iter->me.sme->next;
986 { 975 return GNUNET_YES;
987 if (NULL != iter->me.bme) 976 }
988 { 977 }
989 if (NULL != key) 978 else
990 *key = iter->me.bme->key; 979 {
991 if (NULL != value) 980 if (NULL != iter->me.bme)
992 *value = iter->me.bme->value; 981 {
993 iter->me.bme = iter->me.bme->next; 982 if (NULL != key)
994 return GNUNET_YES; 983 *key = iter->me.bme->key;
995 } 984 if (NULL != value)
985 *value = iter->me.bme->value;
986 iter->me.bme = iter->me.bme->next;
987 return GNUNET_YES;
988 }
989 }
990 iter->idx += 1;
991 if (iter->idx < iter->map->map_length)
992 iter->me = iter->map->map[iter->idx];
996 } 993 }
997 iter->idx += 1;
998 if (iter->idx < iter->map->map_length)
999 iter->me = iter->map->map[iter->idx];
1000 }
1001} 994}
1002 995
1003 996
@@ -1007,10 +1000,10 @@ GNUNET_CONTAINER_multishortmap_iterator_next (
1007 * @param iter the iterator to destroy 1000 * @param iter the iterator to destroy
1008 */ 1001 */
1009void 1002void
1010GNUNET_CONTAINER_multishortmap_iterator_destroy ( 1003GNUNET_CONTAINER_multishortmap_iterator_destroy(
1011 struct GNUNET_CONTAINER_MultiShortmapIterator *iter) 1004 struct GNUNET_CONTAINER_MultiShortmapIterator *iter)
1012{ 1005{
1013 GNUNET_free (iter); 1006 GNUNET_free(iter);
1014} 1007}
1015 1008
1016 1009
diff --git a/src/util/container_multiuuidmap.c b/src/util/container_multiuuidmap.c
index dd21fd128..78ed7f2b7 100644
--- a/src/util/container_multiuuidmap.c
+++ b/src/util/container_multiuuidmap.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/container_multiuuidmap.c 21 * @file util/container_multiuuidmap.c
22 * @brief hash map for UUIDs where the same key may be present multiple times 22 * @brief hash map for UUIDs where the same key may be present multiple times
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29#define LOG(kind, ...) \ 29#define LOG(kind, ...) \
30 GNUNET_log_from (kind, "util-container-multiuuidmap", __VA_ARGS__) 30 GNUNET_log_from(kind, "util-container-multiuuidmap", __VA_ARGS__)
31 31
32/** 32/**
33 * Maximum recursion depth for callbacks of 33 * Maximum recursion depth for callbacks of
@@ -41,9 +41,7 @@
41/** 41/**
42 * An entry in the hash map with the full key. 42 * An entry in the hash map with the full key.
43 */ 43 */
44struct BigMapEntry 44struct BigMapEntry {
45{
46
47 /** 45 /**
48 * Value of the entry. 46 * Value of the entry.
49 */ 47 */
@@ -64,9 +62,7 @@ struct BigMapEntry
64/** 62/**
65 * An entry in the hash map with just a pointer to the key. 63 * An entry in the hash map with just a pointer to the key.
66 */ 64 */
67struct SmallMapEntry 65struct SmallMapEntry {
68{
69
70 /** 66 /**
71 * Value of the entry. 67 * Value of the entry.
72 */ 68 */
@@ -87,8 +83,7 @@ struct SmallMapEntry
87/** 83/**
88 * Entry in the map. 84 * Entry in the map.
89 */ 85 */
90union MapEntry 86union MapEntry {
91{
92 /** 87 /**
93 * Variant used if map entries only contain a pointer to the key. 88 * Variant used if map entries only contain a pointer to the key.
94 */ 89 */
@@ -104,8 +99,7 @@ union MapEntry
104/** 99/**
105 * Internal representation of the hash map. 100 * Internal representation of the hash map.
106 */ 101 */
107struct GNUNET_CONTAINER_MultiUuidmap 102struct GNUNET_CONTAINER_MultiUuidmap {
108{
109 /** 103 /**
110 * All of our buckets. 104 * All of our buckets.
111 */ 105 */
@@ -152,8 +146,7 @@ struct GNUNET_CONTAINER_MultiUuidmap
152 * Cursor into a multiuuidmap. 146 * Cursor into a multiuuidmap.
153 * Allows to enumerate elements asynchronously. 147 * Allows to enumerate elements asynchronously.
154 */ 148 */
155struct GNUNET_CONTAINER_MultiUuidmapIterator 149struct GNUNET_CONTAINER_MultiUuidmapIterator {
156{
157 /** 150 /**
158 * Position in the bucket 'idx' 151 * Position in the bucket 'idx'
159 */ 152 */
@@ -193,18 +186,18 @@ struct GNUNET_CONTAINER_MultiUuidmapIterator
193 * @return NULL on error 186 * @return NULL on error
194 */ 187 */
195struct GNUNET_CONTAINER_MultiUuidmap * 188struct GNUNET_CONTAINER_MultiUuidmap *
196GNUNET_CONTAINER_multiuuidmap_create (unsigned int len, int do_not_copy_keys) 189GNUNET_CONTAINER_multiuuidmap_create(unsigned int len, int do_not_copy_keys)
197{ 190{
198 struct GNUNET_CONTAINER_MultiUuidmap *map; 191 struct GNUNET_CONTAINER_MultiUuidmap *map;
199 192
200 GNUNET_assert (len > 0); 193 GNUNET_assert(len > 0);
201 map = GNUNET_new (struct GNUNET_CONTAINER_MultiUuidmap); 194 map = GNUNET_new(struct GNUNET_CONTAINER_MultiUuidmap);
202 map->map = GNUNET_malloc_large (len * sizeof (union MapEntry)); 195 map->map = GNUNET_malloc_large(len * sizeof(union MapEntry));
203 if (NULL == map->map) 196 if (NULL == map->map)
204 { 197 {
205 GNUNET_free (map); 198 GNUNET_free(map);
206 return NULL; 199 return NULL;
207 } 200 }
208 map->map_length = len; 201 map->map_length = len;
209 map->use_small_entries = do_not_copy_keys; 202 map->use_small_entries = do_not_copy_keys;
210 return map; 203 return map;
@@ -218,44 +211,44 @@ GNUNET_CONTAINER_multiuuidmap_create (unsigned int len, int do_not_copy_keys)
218 * @param map the map 211 * @param map the map
219 */ 212 */
220void 213void
221GNUNET_CONTAINER_multiuuidmap_destroy ( 214GNUNET_CONTAINER_multiuuidmap_destroy(
222 struct GNUNET_CONTAINER_MultiUuidmap *map) 215 struct GNUNET_CONTAINER_MultiUuidmap *map)
223{ 216{
224 GNUNET_assert (0 == map->next_cache_off); 217 GNUNET_assert(0 == map->next_cache_off);
225 for (unsigned int i = 0; i < map->map_length; i++) 218 for (unsigned int i = 0; i < map->map_length; i++)
226 {
227 union MapEntry me;
228
229 me = map->map[i];
230 if (map->use_small_entries)
231 {
232 struct SmallMapEntry *sme;
233 struct SmallMapEntry *nxt;
234
235 nxt = me.sme;
236 while (NULL != (sme = nxt))
237 {
238 nxt = sme->next;
239 GNUNET_free (sme);
240 }
241 me.sme = NULL;
242 }
243 else
244 { 219 {
245 struct BigMapEntry *bme; 220 union MapEntry me;
246 struct BigMapEntry *nxt; 221
247 222 me = map->map[i];
248 nxt = me.bme; 223 if (map->use_small_entries)
249 while (NULL != (bme = nxt)) 224 {
250 { 225 struct SmallMapEntry *sme;
251 nxt = bme->next; 226 struct SmallMapEntry *nxt;
252 GNUNET_free (bme); 227
253 } 228 nxt = me.sme;
254 me.bme = NULL; 229 while (NULL != (sme = nxt))
230 {
231 nxt = sme->next;
232 GNUNET_free(sme);
233 }
234 me.sme = NULL;
235 }
236 else
237 {
238 struct BigMapEntry *bme;
239 struct BigMapEntry *nxt;
240
241 nxt = me.bme;
242 while (NULL != (bme = nxt))
243 {
244 nxt = bme->next;
245 GNUNET_free(bme);
246 }
247 me.bme = NULL;
248 }
255 } 249 }
256 } 250 GNUNET_free(map->map);
257 GNUNET_free (map->map); 251 GNUNET_free(map);
258 GNUNET_free (map);
259} 252}
260 253
261 254
@@ -267,13 +260,13 @@ GNUNET_CONTAINER_multiuuidmap_destroy (
267 * @return offset into the "map" array of "map" 260 * @return offset into the "map" array of "map"
268 */ 261 */
269static unsigned int 262static unsigned int
270idx_of (const struct GNUNET_CONTAINER_MultiUuidmap *map, 263idx_of(const struct GNUNET_CONTAINER_MultiUuidmap *map,
271 const struct GNUNET_Uuid *key) 264 const struct GNUNET_Uuid *key)
272{ 265{
273 unsigned int kx; 266 unsigned int kx;
274 267
275 GNUNET_assert (NULL != map); 268 GNUNET_assert(NULL != map);
276 GNUNET_memcpy (&kx, key, sizeof (kx)); 269 GNUNET_memcpy(&kx, key, sizeof(kx));
277 return kx % map->map_length; 270 return kx % map->map_length;
278} 271}
279 272
@@ -285,7 +278,7 @@ idx_of (const struct GNUNET_CONTAINER_MultiUuidmap *map,
285 * @return the number of key value pairs 278 * @return the number of key value pairs
286 */ 279 */
287unsigned int 280unsigned int
288GNUNET_CONTAINER_multiuuidmap_size ( 281GNUNET_CONTAINER_multiuuidmap_size(
289 const struct GNUNET_CONTAINER_MultiUuidmap *map) 282 const struct GNUNET_CONTAINER_MultiUuidmap *map)
290{ 283{
291 return map->size; 284 return map->size;
@@ -303,25 +296,25 @@ GNUNET_CONTAINER_multiuuidmap_size (
303 * key-value pairs with value NULL 296 * key-value pairs with value NULL
304 */ 297 */
305void * 298void *
306GNUNET_CONTAINER_multiuuidmap_get ( 299GNUNET_CONTAINER_multiuuidmap_get(
307 const struct GNUNET_CONTAINER_MultiUuidmap *map, 300 const struct GNUNET_CONTAINER_MultiUuidmap *map,
308 const struct GNUNET_Uuid *key) 301 const struct GNUNET_Uuid *key)
309{ 302{
310 union MapEntry me; 303 union MapEntry me;
311 304
312 me = map->map[idx_of (map, key)]; 305 me = map->map[idx_of(map, key)];
313 if (map->use_small_entries) 306 if (map->use_small_entries)
314 { 307 {
315 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 308 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
316 if (0 == GNUNET_memcmp (key, sme->key)) 309 if (0 == GNUNET_memcmp(key, sme->key))
317 return sme->value; 310 return sme->value;
318 } 311 }
319 else 312 else
320 { 313 {
321 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 314 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
322 if (0 == GNUNET_memcmp (key, &bme->key)) 315 if (0 == GNUNET_memcmp(key, &bme->key))
323 return bme->value; 316 return bme->value;
324 } 317 }
325 return NULL; 318 return NULL;
326} 319}
327 320
@@ -336,7 +329,7 @@ GNUNET_CONTAINER_multiuuidmap_get (
336 * #GNUNET_SYSERR if it aborted iteration 329 * #GNUNET_SYSERR if it aborted iteration
337 */ 330 */
338int 331int
339GNUNET_CONTAINER_multiuuidmap_iterate ( 332GNUNET_CONTAINER_multiuuidmap_iterate(
340 struct GNUNET_CONTAINER_MultiUuidmap *map, 333 struct GNUNET_CONTAINER_MultiUuidmap *map,
341 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, 334 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it,
342 void *it_cls) 335 void *it_cls)
@@ -347,50 +340,50 @@ GNUNET_CONTAINER_multiuuidmap_iterate (
347 struct GNUNET_Uuid kc; 340 struct GNUNET_Uuid kc;
348 341
349 count = 0; 342 count = 0;
350 GNUNET_assert (NULL != map); 343 GNUNET_assert(NULL != map);
351 ce = &map->next_cache[map->next_cache_off]; 344 ce = &map->next_cache[map->next_cache_off];
352 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 345 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
353 for (unsigned int i = 0; i < map->map_length; i++) 346 for (unsigned int i = 0; i < map->map_length; i++)
354 {
355 me = map->map[i];
356 if (map->use_small_entries)
357 { 347 {
358 struct SmallMapEntry *sme; 348 me = map->map[i];
359 349 if (map->use_small_entries)
360 ce->sme = me.sme;
361 while (NULL != (sme = ce->sme))
362 {
363 ce->sme = sme->next;
364 if ((NULL != it) && (GNUNET_OK != it (it_cls, sme->key, sme->value)))
365 { 350 {
366 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 351 struct SmallMapEntry *sme;
367 return GNUNET_SYSERR; 352
353 ce->sme = me.sme;
354 while (NULL != (sme = ce->sme))
355 {
356 ce->sme = sme->next;
357 if ((NULL != it) && (GNUNET_OK != it(it_cls, sme->key, sme->value)))
358 {
359 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
360 return GNUNET_SYSERR;
361 }
362 count++;
363 }
368 } 364 }
369 count++; 365 else
370 }
371 }
372 else
373 {
374 struct BigMapEntry *bme;
375
376 ce->bme = me.bme;
377 while (NULL != (bme = ce->bme))
378 {
379 ce->bme = bme->next;
380 if (NULL != it)
381 { 366 {
382 kc = bme->key; 367 struct BigMapEntry *bme;
383 if (GNUNET_OK != it (it_cls, &kc, bme->value)) 368
384 { 369 ce->bme = me.bme;
385 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 370 while (NULL != (bme = ce->bme))
386 return GNUNET_SYSERR; 371 {
387 } 372 ce->bme = bme->next;
373 if (NULL != it)
374 {
375 kc = bme->key;
376 if (GNUNET_OK != it(it_cls, &kc, bme->value))
377 {
378 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
379 return GNUNET_SYSERR;
380 }
381 }
382 count++;
383 }
388 } 384 }
389 count++;
390 }
391 } 385 }
392 } 386 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
393 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
394 return count; 387 return count;
395} 388}
396 389
@@ -403,8 +396,8 @@ GNUNET_CONTAINER_multiuuidmap_iterate (
403 * @param bme the entry that is about to be free'd 396 * @param bme the entry that is about to be free'd
404 */ 397 */
405static void 398static void
406update_next_cache_bme (struct GNUNET_CONTAINER_MultiUuidmap *map, 399update_next_cache_bme(struct GNUNET_CONTAINER_MultiUuidmap *map,
407 const struct BigMapEntry *bme) 400 const struct BigMapEntry *bme)
408{ 401{
409 for (unsigned int i = 0; i < map->next_cache_off; i++) 402 for (unsigned int i = 0; i < map->next_cache_off; i++)
410 if (map->next_cache[i].bme == bme) 403 if (map->next_cache[i].bme == bme)
@@ -420,8 +413,8 @@ update_next_cache_bme (struct GNUNET_CONTAINER_MultiUuidmap *map,
420 * @param sme the entry that is about to be free'd 413 * @param sme the entry that is about to be free'd
421 */ 414 */
422static void 415static void
423update_next_cache_sme (struct GNUNET_CONTAINER_MultiUuidmap *map, 416update_next_cache_sme(struct GNUNET_CONTAINER_MultiUuidmap *map,
424 const struct SmallMapEntry *sme) 417 const struct SmallMapEntry *sme)
425{ 418{
426 for (unsigned int i = 0; i < map->next_cache_off; i++) 419 for (unsigned int i = 0; i < map->next_cache_off; i++)
427 if (map->next_cache[i].sme == sme) 420 if (map->next_cache[i].sme == sme)
@@ -441,56 +434,56 @@ update_next_cache_sme (struct GNUNET_CONTAINER_MultiUuidmap *map,
441 * is not in the map 434 * is not in the map
442 */ 435 */
443int 436int
444GNUNET_CONTAINER_multiuuidmap_remove (struct GNUNET_CONTAINER_MultiUuidmap *map, 437GNUNET_CONTAINER_multiuuidmap_remove(struct GNUNET_CONTAINER_MultiUuidmap *map,
445 const struct GNUNET_Uuid *key, 438 const struct GNUNET_Uuid *key,
446 const void *value) 439 const void *value)
447{ 440{
448 union MapEntry me; 441 union MapEntry me;
449 unsigned int i; 442 unsigned int i;
450 443
451 map->modification_counter++; 444 map->modification_counter++;
452 i = idx_of (map, key); 445 i = idx_of(map, key);
453 me = map->map[i]; 446 me = map->map[i];
454 if (map->use_small_entries) 447 if (map->use_small_entries)
455 {
456 struct SmallMapEntry *p = NULL;
457
458 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
459 { 448 {
460 if ((0 == GNUNET_memcmp (key, sme->key)) && (value == sme->value)) 449 struct SmallMapEntry *p = NULL;
461 { 450
462 if (NULL == p) 451 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
463 map->map[i].sme = sme->next; 452 {
464 else 453 if ((0 == GNUNET_memcmp(key, sme->key)) && (value == sme->value))
465 p->next = sme->next; 454 {
466 update_next_cache_sme (map, sme); 455 if (NULL == p)
467 GNUNET_free (sme); 456 map->map[i].sme = sme->next;
468 map->size--; 457 else
469 return GNUNET_YES; 458 p->next = sme->next;
470 } 459 update_next_cache_sme(map, sme);
471 p = sme; 460 GNUNET_free(sme);
461 map->size--;
462 return GNUNET_YES;
463 }
464 p = sme;
465 }
472 } 466 }
473 }
474 else 467 else
475 {
476 struct BigMapEntry *p = NULL;
477
478 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
479 { 468 {
480 if ((0 == GNUNET_memcmp (key, &bme->key)) && (value == bme->value)) 469 struct BigMapEntry *p = NULL;
481 { 470
482 if (NULL == p) 471 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
483 map->map[i].bme = bme->next; 472 {
484 else 473 if ((0 == GNUNET_memcmp(key, &bme->key)) && (value == bme->value))
485 p->next = bme->next; 474 {
486 update_next_cache_bme (map, bme); 475 if (NULL == p)
487 GNUNET_free (bme); 476 map->map[i].bme = bme->next;
488 map->size--; 477 else
489 return GNUNET_YES; 478 p->next = bme->next;
490 } 479 update_next_cache_bme(map, bme);
491 p = bme; 480 GNUNET_free(bme);
481 map->size--;
482 return GNUNET_YES;
483 }
484 p = bme;
485 }
492 } 486 }
493 }
494 return GNUNET_NO; 487 return GNUNET_NO;
495} 488}
496 489
@@ -504,7 +497,7 @@ GNUNET_CONTAINER_multiuuidmap_remove (struct GNUNET_CONTAINER_MultiUuidmap *map,
504 * @return number of values removed 497 * @return number of values removed
505 */ 498 */
506int 499int
507GNUNET_CONTAINER_multiuuidmap_remove_all ( 500GNUNET_CONTAINER_multiuuidmap_remove_all(
508 struct GNUNET_CONTAINER_MultiUuidmap *map, 501 struct GNUNET_CONTAINER_MultiUuidmap *map,
509 const struct GNUNET_Uuid *key) 502 const struct GNUNET_Uuid *key)
510{ 503{
@@ -515,70 +508,70 @@ GNUNET_CONTAINER_multiuuidmap_remove_all (
515 map->modification_counter++; 508 map->modification_counter++;
516 509
517 ret = 0; 510 ret = 0;
518 i = idx_of (map, key); 511 i = idx_of(map, key);
519 me = map->map[i]; 512 me = map->map[i];
520 if (map->use_small_entries) 513 if (map->use_small_entries)
521 {
522 struct SmallMapEntry *sme;
523 struct SmallMapEntry *p;
524
525 p = NULL;
526 sme = me.sme;
527 while (NULL != sme)
528 { 514 {
529 if (0 == GNUNET_memcmp (key, sme->key)) 515 struct SmallMapEntry *sme;
530 { 516 struct SmallMapEntry *p;
531 if (NULL == p) 517
532 map->map[i].sme = sme->next; 518 p = NULL;
533 else 519 sme = me.sme;
534 p->next = sme->next; 520 while (NULL != sme)
535 update_next_cache_sme (map, sme); 521 {
536 GNUNET_free (sme); 522 if (0 == GNUNET_memcmp(key, sme->key))
537 map->size--; 523 {
538 if (NULL == p) 524 if (NULL == p)
539 sme = map->map[i].sme; 525 map->map[i].sme = sme->next;
540 else 526 else
541 sme = p->next; 527 p->next = sme->next;
542 ret++; 528 update_next_cache_sme(map, sme);
543 } 529 GNUNET_free(sme);
544 else 530 map->size--;
545 { 531 if (NULL == p)
546 p = sme; 532 sme = map->map[i].sme;
547 sme = sme->next; 533 else
548 } 534 sme = p->next;
535 ret++;
536 }
537 else
538 {
539 p = sme;
540 sme = sme->next;
541 }
542 }
549 } 543 }
550 }
551 else 544 else
552 {
553 struct BigMapEntry *bme;
554 struct BigMapEntry *p;
555
556 p = NULL;
557 bme = me.bme;
558 while (NULL != bme)
559 { 545 {
560 if (0 == GNUNET_memcmp (key, &bme->key)) 546 struct BigMapEntry *bme;
561 { 547 struct BigMapEntry *p;
562 if (NULL == p) 548
563 map->map[i].bme = bme->next; 549 p = NULL;
564 else 550 bme = me.bme;
565 p->next = bme->next; 551 while (NULL != bme)
566 update_next_cache_bme (map, bme); 552 {
567 GNUNET_free (bme); 553 if (0 == GNUNET_memcmp(key, &bme->key))
568 map->size--; 554 {
569 if (NULL == p) 555 if (NULL == p)
570 bme = map->map[i].bme; 556 map->map[i].bme = bme->next;
571 else 557 else
572 bme = p->next; 558 p->next = bme->next;
573 ret++; 559 update_next_cache_bme(map, bme);
574 } 560 GNUNET_free(bme);
575 else 561 map->size--;
576 { 562 if (NULL == p)
577 p = bme; 563 bme = map->map[i].bme;
578 bme = bme->next; 564 else
579 } 565 bme = p->next;
566 ret++;
567 }
568 else
569 {
570 p = bme;
571 bme = bme->next;
572 }
573 }
580 } 574 }
581 }
582 return ret; 575 return ret;
583} 576}
584 577
@@ -593,25 +586,25 @@ GNUNET_CONTAINER_multiuuidmap_remove_all (
593 * #GNUNET_NO if not 586 * #GNUNET_NO if not
594 */ 587 */
595int 588int
596GNUNET_CONTAINER_multiuuidmap_contains ( 589GNUNET_CONTAINER_multiuuidmap_contains(
597 const struct GNUNET_CONTAINER_MultiUuidmap *map, 590 const struct GNUNET_CONTAINER_MultiUuidmap *map,
598 const struct GNUNET_Uuid *key) 591 const struct GNUNET_Uuid *key)
599{ 592{
600 union MapEntry me; 593 union MapEntry me;
601 594
602 me = map->map[idx_of (map, key)]; 595 me = map->map[idx_of(map, key)];
603 if (map->use_small_entries) 596 if (map->use_small_entries)
604 { 597 {
605 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 598 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
606 if (0 == GNUNET_memcmp (key, sme->key)) 599 if (0 == GNUNET_memcmp(key, sme->key))
607 return GNUNET_YES; 600 return GNUNET_YES;
608 } 601 }
609 else 602 else
610 { 603 {
611 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 604 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
612 if (0 == GNUNET_memcmp (key, &bme->key)) 605 if (0 == GNUNET_memcmp(key, &bme->key))
613 return GNUNET_YES; 606 return GNUNET_YES;
614 } 607 }
615 return GNUNET_NO; 608 return GNUNET_NO;
616} 609}
617 610
@@ -627,26 +620,26 @@ GNUNET_CONTAINER_multiuuidmap_contains (
627 * #GNUNET_NO if not 620 * #GNUNET_NO if not
628 */ 621 */
629int 622int
630GNUNET_CONTAINER_multiuuidmap_contains_value ( 623GNUNET_CONTAINER_multiuuidmap_contains_value(
631 const struct GNUNET_CONTAINER_MultiUuidmap *map, 624 const struct GNUNET_CONTAINER_MultiUuidmap *map,
632 const struct GNUNET_Uuid *key, 625 const struct GNUNET_Uuid *key,
633 const void *value) 626 const void *value)
634{ 627{
635 union MapEntry me; 628 union MapEntry me;
636 629
637 me = map->map[idx_of (map, key)]; 630 me = map->map[idx_of(map, key)];
638 if (map->use_small_entries) 631 if (map->use_small_entries)
639 { 632 {
640 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 633 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
641 if ((0 == GNUNET_memcmp (key, sme->key)) && (sme->value == value)) 634 if ((0 == GNUNET_memcmp(key, sme->key)) && (sme->value == value))
642 return GNUNET_YES; 635 return GNUNET_YES;
643 } 636 }
644 else 637 else
645 { 638 {
646 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next) 639 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
647 if ((0 == GNUNET_memcmp (key, &bme->key)) && (bme->value == value)) 640 if ((0 == GNUNET_memcmp(key, &bme->key)) && (bme->value == value))
648 return GNUNET_YES; 641 return GNUNET_YES;
649 } 642 }
650 return GNUNET_NO; 643 return GNUNET_NO;
651} 644}
652 645
@@ -657,7 +650,7 @@ GNUNET_CONTAINER_multiuuidmap_contains_value (
657 * @param map the hash map to grow 650 * @param map the hash map to grow
658 */ 651 */
659static void 652static void
660grow (struct GNUNET_CONTAINER_MultiUuidmap *map) 653grow(struct GNUNET_CONTAINER_MultiUuidmap *map)
661{ 654{
662 union MapEntry *old_map; 655 union MapEntry *old_map;
663 union MapEntry *new_map; 656 union MapEntry *new_map;
@@ -672,40 +665,40 @@ grow (struct GNUNET_CONTAINER_MultiUuidmap *map)
672 new_len = old_len; /* never use 0 */ 665 new_len = old_len; /* never use 0 */
673 if (new_len == old_len) 666 if (new_len == old_len)
674 return; /* nothing changed */ 667 return; /* nothing changed */
675 new_map = GNUNET_malloc_large (new_len * sizeof (union MapEntry)); 668 new_map = GNUNET_malloc_large(new_len * sizeof(union MapEntry));
676 if (NULL == new_map) 669 if (NULL == new_map)
677 return; /* grow not possible */ 670 return; /* grow not possible */
678 map->modification_counter++; 671 map->modification_counter++;
679 map->map_length = new_len; 672 map->map_length = new_len;
680 map->map = new_map; 673 map->map = new_map;
681 for (unsigned int i = 0; i < old_len; i++) 674 for (unsigned int i = 0; i < old_len; i++)
682 {
683 if (map->use_small_entries)
684 {
685 struct SmallMapEntry *sme;
686
687 while (NULL != (sme = old_map[i].sme))
688 {
689 old_map[i].sme = sme->next;
690 idx = idx_of (map, sme->key);
691 sme->next = new_map[idx].sme;
692 new_map[idx].sme = sme;
693 }
694 }
695 else
696 { 675 {
697 struct BigMapEntry *bme; 676 if (map->use_small_entries)
698 677 {
699 while (NULL != (bme = old_map[i].bme)) 678 struct SmallMapEntry *sme;
700 { 679
701 old_map[i].bme = bme->next; 680 while (NULL != (sme = old_map[i].sme))
702 idx = idx_of (map, &bme->key); 681 {
703 bme->next = new_map[idx].bme; 682 old_map[i].sme = sme->next;
704 new_map[idx].bme = bme; 683 idx = idx_of(map, sme->key);
705 } 684 sme->next = new_map[idx].sme;
685 new_map[idx].sme = sme;
686 }
687 }
688 else
689 {
690 struct BigMapEntry *bme;
691
692 while (NULL != (bme = old_map[i].bme))
693 {
694 old_map[i].bme = bme->next;
695 idx = idx_of(map, &bme->key);
696 bme->next = new_map[idx].bme;
697 new_map[idx].bme = bme;
698 }
699 }
706 } 700 }
707 } 701 GNUNET_free(old_map);
708 GNUNET_free (old_map);
709} 702}
710 703
711 704
@@ -722,67 +715,67 @@ grow (struct GNUNET_CONTAINER_MultiUuidmap *map)
722 * value already exists 715 * value already exists
723 */ 716 */
724int 717int
725GNUNET_CONTAINER_multiuuidmap_put (struct GNUNET_CONTAINER_MultiUuidmap *map, 718GNUNET_CONTAINER_multiuuidmap_put(struct GNUNET_CONTAINER_MultiUuidmap *map,
726 const struct GNUNET_Uuid *key, 719 const struct GNUNET_Uuid *key,
727 void *value, 720 void *value,
728 enum GNUNET_CONTAINER_MultiHashMapOption opt) 721 enum GNUNET_CONTAINER_MultiHashMapOption opt)
729{ 722{
730 union MapEntry me; 723 union MapEntry me;
731 unsigned int i; 724 unsigned int i;
732 725
733 i = idx_of (map, key); 726 i = idx_of(map, key);
734 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) && 727 if ((opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE) &&
735 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST)) 728 (opt != GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_FAST))
736 {
737 me = map->map[i];
738 if (map->use_small_entries)
739 { 729 {
740 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 730 me = map->map[i];
741 if (0 == GNUNET_memcmp (key, sme->key)) 731 if (map->use_small_entries)
742 { 732 {
743 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 733 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
744 return GNUNET_SYSERR; 734 if (0 == GNUNET_memcmp(key, sme->key))
745 sme->value = value; 735 {
746 return GNUNET_NO; 736 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
737 return GNUNET_SYSERR;
738 sme->value = value;
739 return GNUNET_NO;
740 }
747 } 741 }
748 } 742 else
749 else
750 {
751 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
752 if (0 == GNUNET_memcmp (key, &bme->key))
753 { 743 {
754 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY) 744 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
755 return GNUNET_SYSERR; 745 if (0 == GNUNET_memcmp(key, &bme->key))
756 bme->value = value; 746 {
757 return GNUNET_NO; 747 if (opt == GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)
748 return GNUNET_SYSERR;
749 bme->value = value;
750 return GNUNET_NO;
751 }
758 } 752 }
759 } 753 }
760 }
761 if (map->size / 3 >= map->map_length / 4) 754 if (map->size / 3 >= map->map_length / 4)
762 { 755 {
763 grow (map); 756 grow(map);
764 i = idx_of (map, key); 757 i = idx_of(map, key);
765 } 758 }
766 if (map->use_small_entries) 759 if (map->use_small_entries)
767 { 760 {
768 struct SmallMapEntry *sme; 761 struct SmallMapEntry *sme;
769 762
770 sme = GNUNET_new (struct SmallMapEntry); 763 sme = GNUNET_new(struct SmallMapEntry);
771 sme->key = key; 764 sme->key = key;
772 sme->value = value; 765 sme->value = value;
773 sme->next = map->map[i].sme; 766 sme->next = map->map[i].sme;
774 map->map[i].sme = sme; 767 map->map[i].sme = sme;
775 } 768 }
776 else 769 else
777 { 770 {
778 struct BigMapEntry *bme; 771 struct BigMapEntry *bme;
779 772
780 bme = GNUNET_new (struct BigMapEntry); 773 bme = GNUNET_new(struct BigMapEntry);
781 bme->key = *key; 774 bme->key = *key;
782 bme->value = value; 775 bme->value = value;
783 bme->next = map->map[i].bme; 776 bme->next = map->map[i].bme;
784 map->map[i].bme = bme; 777 map->map[i].bme = bme;
785 } 778 }
786 map->size++; 779 map->size++;
787 return GNUNET_OK; 780 return GNUNET_OK;
788} 781}
@@ -799,7 +792,7 @@ GNUNET_CONTAINER_multiuuidmap_put (struct GNUNET_CONTAINER_MultiUuidmap *map,
799 * #GNUNET_SYSERR if it aborted iteration 792 * #GNUNET_SYSERR if it aborted iteration
800 */ 793 */
801int 794int
802GNUNET_CONTAINER_multiuuidmap_get_multiple ( 795GNUNET_CONTAINER_multiuuidmap_get_multiple(
803 struct GNUNET_CONTAINER_MultiUuidmap *map, 796 struct GNUNET_CONTAINER_MultiUuidmap *map,
804 const struct GNUNET_Uuid *key, 797 const struct GNUNET_Uuid *key,
805 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, 798 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it,
@@ -810,46 +803,46 @@ GNUNET_CONTAINER_multiuuidmap_get_multiple (
810 union MapEntry *ce; 803 union MapEntry *ce;
811 804
812 ce = &map->next_cache[map->next_cache_off]; 805 ce = &map->next_cache[map->next_cache_off];
813 GNUNET_assert (++map->next_cache_off < NEXT_CACHE_SIZE); 806 GNUNET_assert(++map->next_cache_off < NEXT_CACHE_SIZE);
814 count = 0; 807 count = 0;
815 me = map->map[idx_of (map, key)]; 808 me = map->map[idx_of(map, key)];
816 if (map->use_small_entries) 809 if (map->use_small_entries)
817 {
818 struct SmallMapEntry *sme;
819
820 ce->sme = me.sme;
821 while (NULL != (sme = ce->sme))
822 { 810 {
823 ce->sme = sme->next; 811 struct SmallMapEntry *sme;
824 if (0 != GNUNET_memcmp (key, sme->key)) 812
825 continue; 813 ce->sme = me.sme;
826 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, sme->value))) 814 while (NULL != (sme = ce->sme))
827 { 815 {
828 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 816 ce->sme = sme->next;
829 return GNUNET_SYSERR; 817 if (0 != GNUNET_memcmp(key, sme->key))
830 } 818 continue;
831 count++; 819 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, sme->value)))
820 {
821 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
822 return GNUNET_SYSERR;
823 }
824 count++;
825 }
832 } 826 }
833 }
834 else 827 else
835 {
836 struct BigMapEntry *bme;
837
838 ce->bme = me.bme;
839 while (NULL != (bme = ce->bme))
840 { 828 {
841 ce->bme = bme->next; 829 struct BigMapEntry *bme;
842 if (0 != GNUNET_memcmp (key, &bme->key)) 830
843 continue; 831 ce->bme = me.bme;
844 if ((NULL != it) && (GNUNET_OK != it (it_cls, key, bme->value))) 832 while (NULL != (bme = ce->bme))
845 { 833 {
846 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE); 834 ce->bme = bme->next;
847 return GNUNET_SYSERR; 835 if (0 != GNUNET_memcmp(key, &bme->key))
848 } 836 continue;
849 count++; 837 if ((NULL != it) && (GNUNET_OK != it(it_cls, key, bme->value)))
838 {
839 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
840 return GNUNET_SYSERR;
841 }
842 count++;
843 }
850 } 844 }
851 } 845 GNUNET_assert(--map->next_cache_off < NEXT_CACHE_SIZE);
852 GNUNET_assert (--map->next_cache_off < NEXT_CACHE_SIZE);
853 return count; 846 return count;
854} 847}
855 848
@@ -866,7 +859,7 @@ GNUNET_CONTAINER_multiuuidmap_get_multiple (
866 * @return the number of key value pairs processed, zero or one. 859 * @return the number of key value pairs processed, zero or one.
867 */ 860 */
868unsigned int 861unsigned int
869GNUNET_CONTAINER_multiuuidmap_get_random ( 862GNUNET_CONTAINER_multiuuidmap_get_random(
870 const struct GNUNET_CONTAINER_MultiUuidmap *map, 863 const struct GNUNET_CONTAINER_MultiUuidmap *map,
871 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it, 864 GNUNET_CONTAINER_MultiUuidmapIteratorCallback it,
872 void *it_cls) 865 void *it_cls)
@@ -878,38 +871,38 @@ GNUNET_CONTAINER_multiuuidmap_get_random (
878 return 0; 871 return 0;
879 if (NULL == it) 872 if (NULL == it)
880 return 1; 873 return 1;
881 off = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, map->size); 874 off = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, map->size);
882 for (unsigned int idx = 0; idx < map->map_length; idx++) 875 for (unsigned int idx = 0; idx < map->map_length; idx++)
883 {
884 me = map->map[idx];
885 if (map->use_small_entries)
886 { 876 {
887 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next) 877 me = map->map[idx];
888 { 878 if (map->use_small_entries)
889 if (0 == off)
890 { 879 {
891 if (GNUNET_OK != it (it_cls, sme->key, sme->value)) 880 for (struct SmallMapEntry *sme = me.sme; NULL != sme; sme = sme->next)
892 return GNUNET_SYSERR; 881 {
893 return 1; 882 if (0 == off)
883 {
884 if (GNUNET_OK != it(it_cls, sme->key, sme->value))
885 return GNUNET_SYSERR;
886 return 1;
887 }
888 off--;
889 }
894 } 890 }
895 off--; 891 else
896 }
897 }
898 else
899 {
900 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
901 {
902 if (0 == off)
903 { 892 {
904 if (GNUNET_OK != it (it_cls, &bme->key, bme->value)) 893 for (struct BigMapEntry *bme = me.bme; NULL != bme; bme = bme->next)
905 return GNUNET_SYSERR; 894 {
906 return 1; 895 if (0 == off)
896 {
897 if (GNUNET_OK != it(it_cls, &bme->key, bme->value))
898 return GNUNET_SYSERR;
899 return 1;
900 }
901 off--;
902 }
907 } 903 }
908 off--;
909 }
910 } 904 }
911 } 905 GNUNET_break(0);
912 GNUNET_break (0);
913 return GNUNET_SYSERR; 906 return GNUNET_SYSERR;
914} 907}
915 908
@@ -927,12 +920,12 @@ GNUNET_CONTAINER_multiuuidmap_get_random (
927 * @return an iterator over the given multiuuidmap 'map' 920 * @return an iterator over the given multiuuidmap 'map'
928 */ 921 */
929struct GNUNET_CONTAINER_MultiUuidmapIterator * 922struct GNUNET_CONTAINER_MultiUuidmapIterator *
930GNUNET_CONTAINER_multiuuidmap_iterator_create ( 923GNUNET_CONTAINER_multiuuidmap_iterator_create(
931 const struct GNUNET_CONTAINER_MultiUuidmap *map) 924 const struct GNUNET_CONTAINER_MultiUuidmap *map)
932{ 925{
933 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter; 926 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter;
934 927
935 iter = GNUNET_new (struct GNUNET_CONTAINER_MultiUuidmapIterator); 928 iter = GNUNET_new(struct GNUNET_CONTAINER_MultiUuidmapIterator);
936 iter->map = map; 929 iter->map = map;
937 iter->modification_counter = map->modification_counter; 930 iter->modification_counter = map->modification_counter;
938 iter->me = map->map[0]; 931 iter->me = map->map[0];
@@ -955,47 +948,47 @@ GNUNET_CONTAINER_multiuuidmap_iterator_create (
955 * #GNUNET_NO if we are out of elements 948 * #GNUNET_NO if we are out of elements
956 */ 949 */
957int 950int
958GNUNET_CONTAINER_multiuuidmap_iterator_next ( 951GNUNET_CONTAINER_multiuuidmap_iterator_next(
959 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter, 952 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter,
960 struct GNUNET_Uuid *key, 953 struct GNUNET_Uuid *key,
961 const void **value) 954 const void **value)
962{ 955{
963 /* make sure the map has not been modified */ 956 /* make sure the map has not been modified */
964 GNUNET_assert (iter->modification_counter == iter->map->modification_counter); 957 GNUNET_assert(iter->modification_counter == iter->map->modification_counter);
965 958
966 /* look for the next entry, skipping empty buckets */ 959 /* look for the next entry, skipping empty buckets */
967 while (1) 960 while (1)
968 {
969 if (iter->idx >= iter->map->map_length)
970 return GNUNET_NO;
971 if (GNUNET_YES == iter->map->use_small_entries)
972 { 961 {
973 if (NULL != iter->me.sme) 962 if (iter->idx >= iter->map->map_length)
974 { 963 return GNUNET_NO;
975 if (NULL != key) 964 if (GNUNET_YES == iter->map->use_small_entries)
976 *key = *iter->me.sme->key; 965 {
977 if (NULL != value) 966 if (NULL != iter->me.sme)
978 *value = iter->me.sme->value; 967 {
979 iter->me.sme = iter->me.sme->next; 968 if (NULL != key)
980 return GNUNET_YES; 969 *key = *iter->me.sme->key;
981 } 970 if (NULL != value)
982 } 971 *value = iter->me.sme->value;
983 else 972 iter->me.sme = iter->me.sme->next;
984 { 973 return GNUNET_YES;
985 if (NULL != iter->me.bme) 974 }
986 { 975 }
987 if (NULL != key) 976 else
988 *key = iter->me.bme->key; 977 {
989 if (NULL != value) 978 if (NULL != iter->me.bme)
990 *value = iter->me.bme->value; 979 {
991 iter->me.bme = iter->me.bme->next; 980 if (NULL != key)
992 return GNUNET_YES; 981 *key = iter->me.bme->key;
993 } 982 if (NULL != value)
983 *value = iter->me.bme->value;
984 iter->me.bme = iter->me.bme->next;
985 return GNUNET_YES;
986 }
987 }
988 iter->idx += 1;
989 if (iter->idx < iter->map->map_length)
990 iter->me = iter->map->map[iter->idx];
994 } 991 }
995 iter->idx += 1;
996 if (iter->idx < iter->map->map_length)
997 iter->me = iter->map->map[iter->idx];
998 }
999} 992}
1000 993
1001 994
@@ -1005,10 +998,10 @@ GNUNET_CONTAINER_multiuuidmap_iterator_next (
1005 * @param iter the iterator to destroy 998 * @param iter the iterator to destroy
1006 */ 999 */
1007void 1000void
1008GNUNET_CONTAINER_multiuuidmap_iterator_destroy ( 1001GNUNET_CONTAINER_multiuuidmap_iterator_destroy(
1009 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter) 1002 struct GNUNET_CONTAINER_MultiUuidmapIterator *iter)
1010{ 1003{
1011 GNUNET_free (iter); 1004 GNUNET_free(iter);
1012} 1005}
1013 1006
1014 1007
diff --git a/src/util/crypto_abe.c b/src/util/crypto_abe.c
index 1d69a01ae..d702738de 100644
--- a/src/util/crypto_abe.c
+++ b/src/util/crypto_abe.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21 21
22/** 22/**
23 * @file util/crypto_random.c 23 * @file util/crypto_random.c
@@ -32,57 +32,55 @@
32 32
33#include "gnunet_crypto_lib.h" 33#include "gnunet_crypto_lib.h"
34 34
35struct GNUNET_CRYPTO_AbeMasterKey 35struct GNUNET_CRYPTO_AbeMasterKey {
36{
37 gabe_pub_t* pub; 36 gabe_pub_t* pub;
38 gabe_msk_t* msk; 37 gabe_msk_t* msk;
39}; 38};
40 39
41struct GNUNET_CRYPTO_AbeKey 40struct GNUNET_CRYPTO_AbeKey {
42{
43 gabe_pub_t* pub; 41 gabe_pub_t* pub;
44 gabe_prv_t* prv; 42 gabe_prv_t* prv;
45}; 43};
46 44
47static int 45static int
48init_aes( element_t k, int enc, 46init_aes(element_t k, int enc,
49 gcry_cipher_hd_t* handle, 47 gcry_cipher_hd_t* handle,
50 struct GNUNET_CRYPTO_SymmetricSessionKey *key, 48 struct GNUNET_CRYPTO_SymmetricSessionKey *key,
51 unsigned char* iv) 49 unsigned char* iv)
52{ 50{
53 int rc; 51 int rc;
54 int key_len; 52 int key_len;
55 unsigned char* key_buf; 53 unsigned char* key_buf;
56 54
57 key_len = element_length_in_bytes(k) < 33 ? 3 : element_length_in_bytes(k); 55 key_len = element_length_in_bytes(k) < 33 ? 3 : element_length_in_bytes(k);
58 key_buf = (unsigned char*) malloc(key_len); 56 key_buf = (unsigned char*)malloc(key_len);
59 element_to_bytes(key_buf, k); 57 element_to_bytes(key_buf, k);
60 58
61 GNUNET_memcpy (key->aes_key, 59 GNUNET_memcpy(key->aes_key,
62 key_buf, 60 key_buf,
63 GNUNET_CRYPTO_AES_KEY_LENGTH); 61 GNUNET_CRYPTO_AES_KEY_LENGTH);
64 GNUNET_assert (0 == 62 GNUNET_assert(0 ==
65 gcry_cipher_open (handle, GCRY_CIPHER_AES256, 63 gcry_cipher_open(handle, GCRY_CIPHER_AES256,
66 GCRY_CIPHER_MODE_CFB, 0)); 64 GCRY_CIPHER_MODE_CFB, 0));
67 rc = gcry_cipher_setkey (*handle, 65 rc = gcry_cipher_setkey(*handle,
68 key->aes_key, 66 key->aes_key,
69 sizeof (key->aes_key)); 67 sizeof(key->aes_key));
70 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 68 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
71 memset (iv, 0, 16); //TODO make reasonable 69 memset(iv, 0, 16); //TODO make reasonable
72 rc = gcry_cipher_setiv (*handle, 70 rc = gcry_cipher_setiv(*handle,
73 iv, 71 iv,
74 16); 72 16);
75 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 73 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
76 74
77 free(key_buf); 75 free(key_buf);
78 return rc; 76 return rc;
79} 77}
80 78
81static int 79static int
82aes_128_cbc_encrypt( char* pt, 80aes_128_cbc_encrypt(char* pt,
83 int size, 81 int size,
84 element_t k, 82 element_t k,
85 char **ct ) 83 char **ct)
86{ 84{
87 gcry_cipher_hd_t handle; 85 gcry_cipher_hd_t handle;
88 struct GNUNET_CRYPTO_SymmetricSessionKey skey; 86 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
@@ -91,34 +89,35 @@ aes_128_cbc_encrypt( char* pt,
91 int padding; 89 int padding;
92 int buf_size; 90 int buf_size;
93 uint8_t len[4]; 91 uint8_t len[4];
92
94 init_aes(k, 1, &handle, &skey, iv); 93 init_aes(k, 1, &handle, &skey, iv);
95 94
96 /* TODO make less crufty */ 95 /* TODO make less crufty */
97 96
98 /* stuff in real length (big endian) before padding */ 97 /* stuff in real length (big endian) before padding */
99 len[0] = (size & 0xff000000)>>24; 98 len[0] = (size & 0xff000000) >> 24;
100 len[1] = (size & 0xff0000)>>16; 99 len[1] = (size & 0xff0000) >> 16;
101 len[2] = (size & 0xff00)>>8; 100 len[2] = (size & 0xff00) >> 8;
102 len[3] = (size & 0xff)>>0; 101 len[3] = (size & 0xff) >> 0;
103 padding = 16 - ((4+size) % 16); 102 padding = 16 - ((4 + size) % 16);
104 buf_size = 4 + size + padding; 103 buf_size = 4 + size + padding;
105 buf = GNUNET_malloc (buf_size); 104 buf = GNUNET_malloc(buf_size);
106 GNUNET_memcpy (buf, len, 4); 105 GNUNET_memcpy(buf, len, 4);
107 GNUNET_memcpy (buf+4, pt, size); 106 GNUNET_memcpy(buf + 4, pt, size);
108 *ct = GNUNET_malloc (buf_size); 107 *ct = GNUNET_malloc(buf_size);
109 108
110 GNUNET_assert (0 == gcry_cipher_encrypt (handle, *ct, buf_size, buf, buf_size)); 109 GNUNET_assert(0 == gcry_cipher_encrypt(handle, *ct, buf_size, buf, buf_size));
111 gcry_cipher_close (handle); 110 gcry_cipher_close(handle);
112 //AES_cbc_encrypt(pt->data, ct->data, pt->len, &key, iv, AES_ENCRYPT); 111 //AES_cbc_encrypt(pt->data, ct->data, pt->len, &key, iv, AES_ENCRYPT);
113 GNUNET_free (buf); 112 GNUNET_free(buf);
114 return buf_size; 113 return buf_size;
115} 114}
116 115
117static int 116static int
118aes_128_cbc_decrypt( char* ct, 117aes_128_cbc_decrypt(char* ct,
119 int size, 118 int size,
120 element_t k, 119 element_t k,
121 char **pt ) 120 char **pt)
122{ 121{
123 struct GNUNET_CRYPTO_SymmetricSessionKey skey; 122 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
124 gcry_cipher_hd_t handle; 123 gcry_cipher_hd_t handle;
@@ -128,108 +127,109 @@ aes_128_cbc_decrypt( char* ct,
128 127
129 init_aes(k, 1, &handle, &skey, iv); 128 init_aes(k, 1, &handle, &skey, iv);
130 129
131 tmp = GNUNET_malloc (size); 130 tmp = GNUNET_malloc(size);
132 131
133 //AES_cbc_encrypt(ct->data, pt->data, ct->len, &key, iv, AES_DECRYPT); 132 //AES_cbc_encrypt(ct->data, pt->data, ct->len, &key, iv, AES_DECRYPT);
134 GNUNET_assert (0 == gcry_cipher_decrypt (handle, tmp, size, ct, size)); 133 GNUNET_assert(0 == gcry_cipher_decrypt(handle, tmp, size, ct, size));
135 gcry_cipher_close (handle); 134 gcry_cipher_close(handle);
136 /* TODO make less crufty */ 135 /* TODO make less crufty */
137 136
138 /* get real length */ 137 /* get real length */
139 len = 0; 138 len = 0;
140 len = len 139 len = len
141 | ((tmp[0])<<24) | ((tmp[1])<<16) 140 | ((tmp[0]) << 24) | ((tmp[1]) << 16)
142 | ((tmp[2])<<8) | ((tmp[3])<<0); 141 | ((tmp[2]) << 8) | ((tmp[3]) << 0);
143 /* truncate any garbage from the padding */ 142 /* truncate any garbage from the padding */
144 *pt = GNUNET_malloc (len); 143 *pt = GNUNET_malloc(len);
145 GNUNET_memcpy (*pt, tmp+4, len); 144 GNUNET_memcpy(*pt, tmp + 4, len);
146 GNUNET_free (tmp); 145 GNUNET_free(tmp);
147 return len; 146 return len;
148} 147}
149 148
150struct GNUNET_CRYPTO_AbeMasterKey* 149struct GNUNET_CRYPTO_AbeMasterKey*
151GNUNET_CRYPTO_cpabe_create_master_key (void) 150GNUNET_CRYPTO_cpabe_create_master_key(void)
152{ 151{
153 struct GNUNET_CRYPTO_AbeMasterKey* key; 152 struct GNUNET_CRYPTO_AbeMasterKey* key;
154 key = GNUNET_new (struct GNUNET_CRYPTO_AbeMasterKey); 153
154 key = GNUNET_new(struct GNUNET_CRYPTO_AbeMasterKey);
155 gabe_setup(&key->pub, &key->msk); 155 gabe_setup(&key->pub, &key->msk);
156 GNUNET_assert (NULL != key->pub); 156 GNUNET_assert(NULL != key->pub);
157 GNUNET_assert (NULL != key->msk); 157 GNUNET_assert(NULL != key->msk);
158 return key; 158 return key;
159} 159}
160 160
161void 161void
162GNUNET_CRYPTO_cpabe_delete_master_key (struct GNUNET_CRYPTO_AbeMasterKey *key) 162GNUNET_CRYPTO_cpabe_delete_master_key(struct GNUNET_CRYPTO_AbeMasterKey *key)
163{ 163{
164 gabe_msk_free (key->msk); 164 gabe_msk_free(key->msk);
165 gabe_pub_free (key->pub); 165 gabe_pub_free(key->pub);
166 //GNUNET_free (key->msk); 166 //GNUNET_free (key->msk);
167 //gabe_msk_free (key->msk); //For some reason free of pub implicit? 167 //gabe_msk_free (key->msk); //For some reason free of pub implicit?
168 GNUNET_free (key); 168 GNUNET_free(key);
169} 169}
170 170
171struct GNUNET_CRYPTO_AbeKey* 171struct GNUNET_CRYPTO_AbeKey*
172GNUNET_CRYPTO_cpabe_create_key (struct GNUNET_CRYPTO_AbeMasterKey *key, 172GNUNET_CRYPTO_cpabe_create_key(struct GNUNET_CRYPTO_AbeMasterKey *key,
173 char **attrs) 173 char **attrs)
174{ 174{
175 struct GNUNET_CRYPTO_AbeKey *prv_key; 175 struct GNUNET_CRYPTO_AbeKey *prv_key;
176 int size; 176 int size;
177 char *tmp; 177 char *tmp;
178 178
179 prv_key = GNUNET_new (struct GNUNET_CRYPTO_AbeKey); 179 prv_key = GNUNET_new(struct GNUNET_CRYPTO_AbeKey);
180 prv_key->prv = gabe_keygen(key->pub, key->msk, attrs); 180 prv_key->prv = gabe_keygen(key->pub, key->msk, attrs);
181 size = gabe_pub_serialize(key->pub, &tmp); 181 size = gabe_pub_serialize(key->pub, &tmp);
182 prv_key->pub = gabe_pub_unserialize(tmp, size); 182 prv_key->pub = gabe_pub_unserialize(tmp, size);
183 GNUNET_free (tmp); 183 GNUNET_free(tmp);
184 GNUNET_assert (NULL != prv_key->prv); 184 GNUNET_assert(NULL != prv_key->prv);
185 return prv_key; 185 return prv_key;
186} 186}
187 187
188void 188void
189GNUNET_CRYPTO_cpabe_delete_key (struct GNUNET_CRYPTO_AbeKey *key, 189GNUNET_CRYPTO_cpabe_delete_key(struct GNUNET_CRYPTO_AbeKey *key,
190 int delete_pub) 190 int delete_pub)
191{ 191{
192 //Memory management in gabe is buggy 192 //Memory management in gabe is buggy
193 gabe_prv_free (key->prv); 193 gabe_prv_free(key->prv);
194 if (GNUNET_YES == delete_pub) 194 if (GNUNET_YES == delete_pub)
195 gabe_pub_free (key->pub); 195 gabe_pub_free(key->pub);
196 GNUNET_free (key); 196 GNUNET_free(key);
197} 197}
198 198
199ssize_t 199ssize_t
200write_cpabe (void **result, 200write_cpabe(void **result,
201 uint32_t file_len, 201 uint32_t file_len,
202 char* cph_buf, 202 char* cph_buf,
203 int cph_buf_len, 203 int cph_buf_len,
204 char* aes_buf, 204 char* aes_buf,
205 int aes_buf_len) 205 int aes_buf_len)
206{ 206{
207 char *ptr; 207 char *ptr;
208 uint32_t *len; 208 uint32_t *len;
209 209
210 *result = GNUNET_malloc (12 + cph_buf_len + aes_buf_len); 210 *result = GNUNET_malloc(12 + cph_buf_len + aes_buf_len);
211 ptr = *result; 211 ptr = *result;
212 len = (uint32_t*) ptr; 212 len = (uint32_t*)ptr;
213 *len = htonl (file_len); 213 *len = htonl(file_len);
214 ptr += 4; 214 ptr += 4;
215 len = (uint32_t*) ptr; 215 len = (uint32_t*)ptr;
216 *len = htonl (aes_buf_len); 216 *len = htonl(aes_buf_len);
217 ptr += 4; 217 ptr += 4;
218 GNUNET_memcpy (ptr, aes_buf, aes_buf_len); 218 GNUNET_memcpy(ptr, aes_buf, aes_buf_len);
219 ptr += aes_buf_len; 219 ptr += aes_buf_len;
220 len = (uint32_t*) ptr; 220 len = (uint32_t*)ptr;
221 *len = htonl (cph_buf_len); 221 *len = htonl(cph_buf_len);
222 ptr += 4; 222 ptr += 4;
223 GNUNET_memcpy (ptr, cph_buf, cph_buf_len); 223 GNUNET_memcpy(ptr, cph_buf, cph_buf_len);
224 return 12 + cph_buf_len + aes_buf_len; 224 return 12 + cph_buf_len + aes_buf_len;
225} 225}
226 226
227ssize_t 227ssize_t
228read_cpabe (const void *data, 228read_cpabe(const void *data,
229 char** cph_buf, 229 char** cph_buf,
230 int *cph_buf_len, 230 int *cph_buf_len,
231 char** aes_buf, 231 char** aes_buf,
232 int *aes_buf_len) 232 int *aes_buf_len)
233{ 233{
234 int buf_len; 234 int buf_len;
235 char *ptr; 235 char *ptr;
@@ -237,29 +237,29 @@ read_cpabe (const void *data,
237 237
238 ptr = (char*)data; 238 ptr = (char*)data;
239 len = (uint32_t*)ptr; 239 len = (uint32_t*)ptr;
240 buf_len = ntohl (*len); 240 buf_len = ntohl(*len);
241 ptr += 4; 241 ptr += 4;
242 len = (uint32_t*)ptr; 242 len = (uint32_t*)ptr;
243 *aes_buf_len = ntohl (*len); 243 *aes_buf_len = ntohl(*len);
244 ptr += 4; 244 ptr += 4;
245 *aes_buf = GNUNET_malloc (*aes_buf_len); 245 *aes_buf = GNUNET_malloc(*aes_buf_len);
246 GNUNET_memcpy (*aes_buf, ptr, *aes_buf_len); 246 GNUNET_memcpy(*aes_buf, ptr, *aes_buf_len);
247 ptr += *aes_buf_len; 247 ptr += *aes_buf_len;
248 len = (uint32_t*)ptr; 248 len = (uint32_t*)ptr;
249 *cph_buf_len = ntohl (*len); 249 *cph_buf_len = ntohl(*len);
250 ptr += 4; 250 ptr += 4;
251 *cph_buf = GNUNET_malloc (*cph_buf_len); 251 *cph_buf = GNUNET_malloc(*cph_buf_len);
252 GNUNET_memcpy (*cph_buf, ptr, *cph_buf_len); 252 GNUNET_memcpy(*cph_buf, ptr, *cph_buf_len);
253 253
254 return buf_len; 254 return buf_len;
255} 255}
256 256
257ssize_t 257ssize_t
258GNUNET_CRYPTO_cpabe_encrypt (const void *block, 258GNUNET_CRYPTO_cpabe_encrypt(const void *block,
259 size_t size, 259 size_t size,
260 const char *policy, 260 const char *policy,
261 const struct GNUNET_CRYPTO_AbeMasterKey *key, 261 const struct GNUNET_CRYPTO_AbeMasterKey *key,
262 void **result) 262 void **result)
263{ 263{
264 gabe_cph_t* cph; 264 gabe_cph_t* cph;
265 char* plt; 265 char* plt;
@@ -270,15 +270,15 @@ GNUNET_CRYPTO_cpabe_encrypt (const void *block,
270 int aes_buf_len; 270 int aes_buf_len;
271 ssize_t result_len; 271 ssize_t result_len;
272 272
273 if( !(cph = gabe_enc(key->pub, m, (char*)policy)) ) 273 if (!(cph = gabe_enc(key->pub, m, (char*)policy)))
274 return GNUNET_SYSERR; 274 return GNUNET_SYSERR;
275 cph_buf_len = gabe_cph_serialize(cph, 275 cph_buf_len = gabe_cph_serialize(cph,
276 &cph_buf); 276 &cph_buf);
277 gabe_cph_free(cph); 277 gabe_cph_free(cph);
278 GNUNET_free (cph); 278 GNUNET_free(cph);
279 plt = GNUNET_memdup (block, size); 279 plt = GNUNET_memdup(block, size);
280 aes_buf_len = aes_128_cbc_encrypt(plt, size, m, &aes_buf); 280 aes_buf_len = aes_128_cbc_encrypt(plt, size, m, &aes_buf);
281 GNUNET_free (plt); 281 GNUNET_free(plt);
282 element_clear(m); 282 element_clear(m);
283 result_len = write_cpabe(result, size, cph_buf, cph_buf_len, aes_buf, aes_buf_len); 283 result_len = write_cpabe(result, size, cph_buf, cph_buf_len, aes_buf, aes_buf_len);
284 GNUNET_free(cph_buf); 284 GNUNET_free(cph_buf);
@@ -287,10 +287,10 @@ GNUNET_CRYPTO_cpabe_encrypt (const void *block,
287} 287}
288 288
289ssize_t 289ssize_t
290GNUNET_CRYPTO_cpabe_decrypt (const void *block, 290GNUNET_CRYPTO_cpabe_decrypt(const void *block,
291 size_t size, 291 size_t size,
292 const struct GNUNET_CRYPTO_AbeKey *key, 292 const struct GNUNET_CRYPTO_AbeKey *key,
293 void **result) 293 void **result)
294{ 294{
295 char* aes_buf; 295 char* aes_buf;
296 char* cph_buf; 296 char* cph_buf;
@@ -302,22 +302,23 @@ GNUNET_CRYPTO_cpabe_decrypt (const void *block,
302 302
303 read_cpabe(block, &cph_buf, &cph_buf_size, &aes_buf, &aes_buf_size); 303 read_cpabe(block, &cph_buf, &cph_buf_size, &aes_buf, &aes_buf_size);
304 cph = gabe_cph_unserialize(key->pub, cph_buf, cph_buf_size); 304 cph = gabe_cph_unserialize(key->pub, cph_buf, cph_buf_size);
305 if( !gabe_dec(key->pub, key->prv, cph, m) ) { 305 if (!gabe_dec(key->pub, key->prv, cph, m))
306 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 306 {
307 "%s\n", gabe_error()); 307 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
308 GNUNET_free (aes_buf); 308 "%s\n", gabe_error());
309 GNUNET_free (cph_buf); 309 GNUNET_free(aes_buf);
310 gabe_cph_free(cph); 310 GNUNET_free(cph_buf);
311 GNUNET_free (cph); 311 gabe_cph_free(cph);
312 element_clear (m); 312 GNUNET_free(cph);
313 return GNUNET_SYSERR; 313 element_clear(m);
314 } 314 return GNUNET_SYSERR;
315 }
315 gabe_cph_free(cph); 316 gabe_cph_free(cph);
316 GNUNET_free (cph); 317 GNUNET_free(cph);
317 plt_len = aes_128_cbc_decrypt(aes_buf, aes_buf_size, m, (char**)result); 318 plt_len = aes_128_cbc_decrypt(aes_buf, aes_buf_size, m, (char**)result);
318 GNUNET_free (cph_buf); 319 GNUNET_free(cph_buf);
319 GNUNET_free (aes_buf); 320 GNUNET_free(aes_buf);
320 element_clear (m); 321 element_clear(m);
321 //freeing is buggy in gabe 322 //freeing is buggy in gabe
322 //gabe_prv_free (prv); 323 //gabe_prv_free (prv);
323 //gabe_pub_free (pub); 324 //gabe_pub_free (pub);
@@ -325,8 +326,8 @@ GNUNET_CRYPTO_cpabe_decrypt (const void *block,
325} 326}
326 327
327ssize_t 328ssize_t
328GNUNET_CRYPTO_cpabe_serialize_key (const struct GNUNET_CRYPTO_AbeKey *key, 329GNUNET_CRYPTO_cpabe_serialize_key(const struct GNUNET_CRYPTO_AbeKey *key,
329 void **result) 330 void **result)
330{ 331{
331 ssize_t len; 332 ssize_t len;
332 char *pub; 333 char *pub;
@@ -334,21 +335,21 @@ GNUNET_CRYPTO_cpabe_serialize_key (const struct GNUNET_CRYPTO_AbeKey *key,
334 int pub_len; 335 int pub_len;
335 int prv_len; 336 int prv_len;
336 337
337 pub_len = gabe_pub_serialize (key->pub, &pub); 338 pub_len = gabe_pub_serialize(key->pub, &pub);
338 prv_len = gabe_prv_serialize (key->prv, &prv); 339 prv_len = gabe_prv_serialize(key->prv, &prv);
339 340
340 len = pub_len + prv_len + 12; 341 len = pub_len + prv_len + 12;
341 write_cpabe (result, len, pub, pub_len, prv, prv_len); 342 write_cpabe(result, len, pub, pub_len, prv, prv_len);
342 343
343 GNUNET_free (pub); 344 GNUNET_free(pub);
344 GNUNET_free (prv); 345 GNUNET_free(prv);
345 346
346 return len; 347 return len;
347} 348}
348 349
349struct GNUNET_CRYPTO_AbeKey* 350struct GNUNET_CRYPTO_AbeKey*
350GNUNET_CRYPTO_cpabe_deserialize_key (const void *data, 351GNUNET_CRYPTO_cpabe_deserialize_key(const void *data,
351 size_t len) 352 size_t len)
352{ 353{
353 struct GNUNET_CRYPTO_AbeKey *key; 354 struct GNUNET_CRYPTO_AbeKey *key;
354 char *pub; 355 char *pub;
@@ -356,23 +357,23 @@ GNUNET_CRYPTO_cpabe_deserialize_key (const void *data,
356 int prv_len; 357 int prv_len;
357 int pub_len; 358 int pub_len;
358 359
359 key = GNUNET_new (struct GNUNET_CRYPTO_AbeKey); 360 key = GNUNET_new(struct GNUNET_CRYPTO_AbeKey);
360 read_cpabe (data, 361 read_cpabe(data,
361 &pub, 362 &pub,
362 &pub_len, 363 &pub_len,
363 &prv, 364 &prv,
364 &prv_len); 365 &prv_len);
365 key->pub = gabe_pub_unserialize (pub, pub_len); 366 key->pub = gabe_pub_unserialize(pub, pub_len);
366 key->prv = gabe_prv_unserialize (key->pub, prv, prv_len); 367 key->prv = gabe_prv_unserialize(key->pub, prv, prv_len);
367 368
368 GNUNET_free (pub); 369 GNUNET_free(pub);
369 GNUNET_free (prv); 370 GNUNET_free(prv);
370 return key; 371 return key;
371} 372}
372 373
373ssize_t 374ssize_t
374GNUNET_CRYPTO_cpabe_serialize_master_key (const struct GNUNET_CRYPTO_AbeMasterKey *key, 375GNUNET_CRYPTO_cpabe_serialize_master_key(const struct GNUNET_CRYPTO_AbeMasterKey *key,
375 void **result) 376 void **result)
376{ 377{
377 ssize_t len; 378 ssize_t len;
378 char *pub; 379 char *pub;
@@ -380,21 +381,21 @@ GNUNET_CRYPTO_cpabe_serialize_master_key (const struct GNUNET_CRYPTO_AbeMasterKe
380 int pub_len; 381 int pub_len;
381 int msk_len; 382 int msk_len;
382 383
383 pub_len = gabe_pub_serialize (key->pub, &pub); 384 pub_len = gabe_pub_serialize(key->pub, &pub);
384 msk_len = gabe_msk_serialize (key->msk, &msk); 385 msk_len = gabe_msk_serialize(key->msk, &msk);
385 386
386 len = pub_len + msk_len + 12; 387 len = pub_len + msk_len + 12;
387 write_cpabe (result, len, pub, pub_len, msk, msk_len); 388 write_cpabe(result, len, pub, pub_len, msk, msk_len);
388 389
389 GNUNET_free (pub); 390 GNUNET_free(pub);
390 GNUNET_free (msk); 391 GNUNET_free(msk);
391 392
392 return len; 393 return len;
393} 394}
394 395
395struct GNUNET_CRYPTO_AbeMasterKey* 396struct GNUNET_CRYPTO_AbeMasterKey*
396GNUNET_CRYPTO_cpabe_deserialize_master_key (const void *data, 397GNUNET_CRYPTO_cpabe_deserialize_master_key(const void *data,
397 size_t len) 398 size_t len)
398{ 399{
399 struct GNUNET_CRYPTO_AbeMasterKey *key; 400 struct GNUNET_CRYPTO_AbeMasterKey *key;
400 char *msk; 401 char *msk;
@@ -402,17 +403,17 @@ GNUNET_CRYPTO_cpabe_deserialize_master_key (const void *data,
402 int msk_len; 403 int msk_len;
403 int pub_len; 404 int pub_len;
404 405
405 key = GNUNET_new (struct GNUNET_CRYPTO_AbeMasterKey); 406 key = GNUNET_new(struct GNUNET_CRYPTO_AbeMasterKey);
406 read_cpabe (data, 407 read_cpabe(data,
407 &pub, 408 &pub,
408 &pub_len, 409 &pub_len,
409 &msk, 410 &msk,
410 &msk_len); 411 &msk_len);
411 key->pub = gabe_pub_unserialize (pub, pub_len); 412 key->pub = gabe_pub_unserialize(pub, pub_len);
412 key->msk = gabe_msk_unserialize (key->pub, msk, msk_len); 413 key->msk = gabe_msk_unserialize(key->pub, msk, msk_len);
413 414
414 GNUNET_free (pub); 415 GNUNET_free(pub);
415 GNUNET_free (msk); 416 GNUNET_free(msk);
416 417
417 return key; 418 return key;
418} 419}
diff --git a/src/util/crypto_crc.c b/src/util/crypto_crc.c
index 3d8e23e24..e547ef329 100644
--- a/src/util/crypto_crc.c
+++ b/src/util/crypto_crc.c
@@ -11,7 +11,7 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
@@ -20,7 +20,7 @@
20 For the actual CRC-32 code: 20 For the actual CRC-32 code:
21 Copyright abandoned; this code is in the public domain. 21 Copyright abandoned; this code is in the public domain.
22 Provided to GNUnet by peter@horizon.com 22 Provided to GNUnet by peter@horizon.com
23*/ 23 */
24 24
25/** 25/**
26 * @file util/crypto_crc.c 26 * @file util/crypto_crc.c
@@ -30,7 +30,7 @@
30#include "platform.h" 30#include "platform.h"
31#include "gnunet_crypto_lib.h" 31#include "gnunet_crypto_lib.h"
32 32
33#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-crc", __VA_ARGS__) 33#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-crc", __VA_ARGS__)
34 34
35/* Avoid wasting space on 8-byte longs. */ 35/* Avoid wasting space on 8-byte longs. */
36#if UINT_MAX >= 0xffffffff 36#if UINT_MAX >= 0xffffffff
@@ -53,7 +53,7 @@ static GNUNET_uLong crc_table[256];
53 * even on a table that someone else is using concurrently. 53 * even on a table that someone else is using concurrently.
54 */ 54 */
55static void 55static void
56crc_init () 56crc_init()
57{ 57{
58 static int once; 58 static int once;
59 unsigned int i, j; 59 unsigned int i, j;
@@ -64,12 +64,12 @@ crc_init ()
64 once = 1; 64 once = 1;
65 crc_table[0] = 0; 65 crc_table[0] = 0;
66 for (i = 128; i; i >>= 1) 66 for (i = 128; i; i >>= 1)
67 { 67 {
68 h = (h >> 1) ^ ((h & 1) ? POLYNOMIAL : 0); 68 h = (h >> 1) ^ ((h & 1) ? POLYNOMIAL : 0);
69 /* h is now crc_table[i] */ 69 /* h is now crc_table[i] */
70 for (j = 0; j < 256; j += 2 * i) 70 for (j = 0; j < 256; j += 2 * i)
71 crc_table[i + j] = crc_table[j] ^ h; 71 crc_table[i + j] = crc_table[j] ^ h;
72 } 72 }
73} 73}
74 74
75/* 75/*
@@ -83,10 +83,10 @@ crc_init ()
83 * property of detecting all burst errors of length 32 bits or less. 83 * property of detecting all burst errors of length 32 bits or less.
84 */ 84 */
85static GNUNET_uLong 85static GNUNET_uLong
86crc32 (GNUNET_uLong crc, const char *buf, size_t len) 86crc32(GNUNET_uLong crc, const char *buf, size_t len)
87{ 87{
88 crc_init (); 88 crc_init();
89 GNUNET_assert (crc_table[255] != 0); 89 GNUNET_assert(crc_table[255] != 0);
90 crc ^= 0xffffffff; 90 crc ^= 0xffffffff;
91 while (len--) 91 while (len--)
92 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff]; 92 crc = (crc >> 8) ^ crc_table[(crc ^ *buf++) & 0xff];
@@ -102,12 +102,12 @@ crc32 (GNUNET_uLong crc, const char *buf, size_t len)
102 * @return the resulting CRC32 checksum 102 * @return the resulting CRC32 checksum
103 */ 103 */
104int32_t 104int32_t
105GNUNET_CRYPTO_crc32_n (const void *buf, size_t len) 105GNUNET_CRYPTO_crc32_n(const void *buf, size_t len)
106{ 106{
107 GNUNET_uLong crc; 107 GNUNET_uLong crc;
108 108
109 crc = crc32 (0L, Z_NULL, 0); 109 crc = crc32(0L, Z_NULL, 0);
110 crc = crc32 (crc, (char *) buf, len); 110 crc = crc32(crc, (char *)buf, len);
111 return crc; 111 return crc;
112} 112}
113 113
@@ -121,9 +121,10 @@ GNUNET_CRYPTO_crc32_n (const void *buf, size_t len)
121 * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish() to get actual crc16) 121 * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish() to get actual crc16)
122 */ 122 */
123uint32_t 123uint32_t
124GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len) 124GNUNET_CRYPTO_crc16_step(uint32_t sum, const void *buf, size_t len)
125{ 125{
126 const uint16_t *hdr = buf; 126 const uint16_t *hdr = buf;
127
127 for (; len >= 2; len -= 2) 128 for (; len >= 2; len -= 2)
128 sum += *(hdr++); 129 sum += *(hdr++);
129 if (len == 1) 130 if (len == 1)
@@ -139,7 +140,7 @@ GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len)
139 * @return crc16 value 140 * @return crc16 value
140 */ 141 */
141uint16_t 142uint16_t
142GNUNET_CRYPTO_crc16_finish (uint32_t sum) 143GNUNET_CRYPTO_crc16_finish(uint32_t sum)
143{ 144{
144 sum = (sum >> 16) + (sum & 0xFFFF); 145 sum = (sum >> 16) + (sum & 0xFFFF);
145 sum += (sum >> 16); 146 sum += (sum >> 16);
@@ -156,12 +157,12 @@ GNUNET_CRYPTO_crc16_finish (uint32_t sum)
156 * @return crc16 value 157 * @return crc16 value
157 */ 158 */
158uint16_t 159uint16_t
159GNUNET_CRYPTO_crc16_n (const void *buf, size_t len) 160GNUNET_CRYPTO_crc16_n(const void *buf, size_t len)
160{ 161{
161 const uint16_t *hdr = buf; 162 const uint16_t *hdr = buf;
162 uint32_t sum = GNUNET_CRYPTO_crc16_step (0, hdr, len); 163 uint32_t sum = GNUNET_CRYPTO_crc16_step(0, hdr, len);
163 164
164 return GNUNET_CRYPTO_crc16_finish (sum); 165 return GNUNET_CRYPTO_crc16_finish(sum);
165} 166}
166 167
167 168
@@ -174,8 +175,8 @@ GNUNET_CRYPTO_crc16_n (const void *buf, size_t len)
174 * @return crc8 value 175 * @return crc8 value
175 */ 176 */
176uint8_t 177uint8_t
177GNUNET_CRYPTO_crc8_n (const void *buf, 178GNUNET_CRYPTO_crc8_n(const void *buf,
178 size_t len) 179 size_t len)
179{ 180{
180 const uint8_t *data = buf; 181 const uint8_t *data = buf;
181 unsigned int crc = 0; 182 unsigned int crc = 0;
@@ -183,16 +184,16 @@ GNUNET_CRYPTO_crc8_n (const void *buf,
183 int j; 184 int j;
184 185
185 for (j = len; 0 != j; j--) 186 for (j = len; 0 != j; j--)
186 {
187 crc ^= (*data++ << 8);
188 for (i = 8; 0 != i; i--)
189 { 187 {
190 if (0 != (crc & 0x8000)) 188 crc ^= (*data++ << 8);
191 crc ^= (0x1070 << 3); 189 for (i = 8; 0 != i; i--)
192 crc <<= 1; 190 {
191 if (0 != (crc & 0x8000))
192 crc ^= (0x1070 << 3);
193 crc <<= 1;
194 }
193 } 195 }
194 } 196 return (uint8_t)(crc >> 8);
195 return (uint8_t) (crc >> 8);
196} 197}
197 198
198 199
diff --git a/src/util/crypto_ecc.c b/src/util/crypto_ecc.c
index 9e6f533f3..d954dfd98 100644
--- a/src/util/crypto_ecc.c
+++ b/src/util/crypto_ecc.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_ecc.c 22 * @file util/crypto_ecc.c
@@ -39,13 +39,13 @@
39 */ 39 */
40#define CURVE "Ed25519" 40#define CURVE "Ed25519"
41 41
42#define LOG(kind, ...) GNUNET_log_from (kind, "util-crypto-ecc", __VA_ARGS__) 42#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-ecc", __VA_ARGS__)
43 43
44#define LOG_STRERROR(kind, syscall) \ 44#define LOG_STRERROR(kind, syscall) \
45 GNUNET_log_from_strerror (kind, "util-crypto-ecc", syscall) 45 GNUNET_log_from_strerror(kind, "util-crypto-ecc", syscall)
46 46
47#define LOG_STRERROR_FILE(kind, syscall, filename) \ 47#define LOG_STRERROR_FILE(kind, syscall, filename) \
48 GNUNET_log_from_strerror_file (kind, "util-crypto-ecc", syscall, filename) 48 GNUNET_log_from_strerror_file(kind, "util-crypto-ecc", syscall, filename)
49 49
50/** 50/**
51 * Log an error message at log-level 'level' that indicates 51 * Log an error message at log-level 'level' that indicates
@@ -54,14 +54,14 @@
54 */ 54 */
55#define LOG_GCRY(level, cmd, rc) \ 55#define LOG_GCRY(level, cmd, rc) \
56 do \ 56 do \
57 { \ 57 { \
58 LOG (level, \ 58 LOG(level, \
59 _ ("`%s' failed at %s:%d with error: %s\n"), \ 59 _("`%s' failed at %s:%d with error: %s\n"), \
60 cmd, \ 60 cmd, \
61 __FILE__, \ 61 __FILE__, \
62 __LINE__, \ 62 __LINE__, \
63 gcry_strerror (rc)); \ 63 gcry_strerror(rc)); \
64 } while (0) 64 } while (0)
65 65
66 66
67/** 67/**
@@ -74,10 +74,10 @@
74 * @return 0 on success 74 * @return 0 on success
75 */ 75 */
76static int 76static int
77key_from_sexp (gcry_mpi_t *array, 77key_from_sexp(gcry_mpi_t *array,
78 gcry_sexp_t sexp, 78 gcry_sexp_t sexp,
79 const char *topname, 79 const char *topname,
80 const char *elems) 80 const char *elems)
81{ 81{
82 gcry_sexp_t list; 82 gcry_sexp_t list;
83 gcry_sexp_t l2; 83 gcry_sexp_t l2;
@@ -85,43 +85,43 @@ key_from_sexp (gcry_mpi_t *array,
85 unsigned int i; 85 unsigned int i;
86 unsigned int idx; 86 unsigned int idx;
87 87
88 list = gcry_sexp_find_token (sexp, topname, 0); 88 list = gcry_sexp_find_token(sexp, topname, 0);
89 if (! list) 89 if (!list)
90 return 1; 90 return 1;
91 l2 = gcry_sexp_cadr (list); 91 l2 = gcry_sexp_cadr(list);
92 gcry_sexp_release (list); 92 gcry_sexp_release(list);
93 list = l2; 93 list = l2;
94 if (! list) 94 if (!list)
95 return 2; 95 return 2;
96 96
97 idx = 0; 97 idx = 0;
98 for (s = elems; *s; s++, idx++) 98 for (s = elems; *s; s++, idx++)
99 {
100 l2 = gcry_sexp_find_token (list, s, 1);
101 if (! l2)
102 {
103 for (i = 0; i < idx; i++)
104 {
105 gcry_free (array[i]);
106 array[i] = NULL;
107 }
108 gcry_sexp_release (list);
109 return 3; /* required parameter not found */
110 }
111 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
112 gcry_sexp_release (l2);
113 if (! array[idx])
114 { 99 {
115 for (i = 0; i < idx; i++) 100 l2 = gcry_sexp_find_token(list, s, 1);
116 { 101 if (!l2)
117 gcry_free (array[i]); 102 {
118 array[i] = NULL; 103 for (i = 0; i < idx; i++)
119 } 104 {
120 gcry_sexp_release (list); 105 gcry_free(array[i]);
121 return 4; /* required parameter is invalid */ 106 array[i] = NULL;
107 }
108 gcry_sexp_release(list);
109 return 3; /* required parameter not found */
110 }
111 array[idx] = gcry_sexp_nth_mpi(l2, 1, GCRYMPI_FMT_USG);
112 gcry_sexp_release(l2);
113 if (!array[idx])
114 {
115 for (i = 0; i < idx; i++)
116 {
117 gcry_free(array[i]);
118 array[i] = NULL;
119 }
120 gcry_sexp_release(list);
121 return 4; /* required parameter is invalid */
122 }
122 } 123 }
123 } 124 gcry_sexp_release(list);
124 gcry_sexp_release (list);
125 return 0; 125 return 0;
126} 126}
127 127
@@ -134,28 +134,28 @@ key_from_sexp (gcry_mpi_t *array,
134 * @return NULL on error 134 * @return NULL on error
135 */ 135 */
136static gcry_sexp_t 136static gcry_sexp_t
137decode_private_ecdsa_key (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv) 137decode_private_ecdsa_key(const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv)
138{ 138{
139 gcry_sexp_t result; 139 gcry_sexp_t result;
140 int rc; 140 int rc;
141 141
142 rc = gcry_sexp_build (&result, 142 rc = gcry_sexp_build(&result,
143 NULL, 143 NULL,
144 "(private-key(ecc(curve \"" CURVE "\")" 144 "(private-key(ecc(curve \"" CURVE "\")"
145 "(d %b)))", 145 "(d %b)))",
146 (int) sizeof (priv->d), 146 (int)sizeof(priv->d),
147 priv->d); 147 priv->d);
148 if (0 != rc) 148 if (0 != rc)
149 { 149 {
150 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 150 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
151 GNUNET_assert (0); 151 GNUNET_assert(0);
152 } 152 }
153#if EXTRA_CHECKS 153#if EXTRA_CHECKS
154 if (0 != (rc = gcry_pk_testkey (result))) 154 if (0 != (rc = gcry_pk_testkey(result)))
155 { 155 {
156 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 156 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
157 GNUNET_assert (0); 157 GNUNET_assert(0);
158 } 158 }
159#endif 159#endif
160 return result; 160 return result;
161} 161}
@@ -169,28 +169,28 @@ decode_private_ecdsa_key (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv)
169 * @return NULL on error 169 * @return NULL on error
170 */ 170 */
171static gcry_sexp_t 171static gcry_sexp_t
172decode_private_eddsa_key (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv) 172decode_private_eddsa_key(const struct GNUNET_CRYPTO_EddsaPrivateKey *priv)
173{ 173{
174 gcry_sexp_t result; 174 gcry_sexp_t result;
175 int rc; 175 int rc;
176 176
177 rc = gcry_sexp_build (&result, 177 rc = gcry_sexp_build(&result,
178 NULL, 178 NULL,
179 "(private-key(ecc(curve \"" CURVE "\")" 179 "(private-key(ecc(curve \"" CURVE "\")"
180 "(flags eddsa)(d %b)))", 180 "(flags eddsa)(d %b)))",
181 (int) sizeof (priv->d), 181 (int)sizeof(priv->d),
182 priv->d); 182 priv->d);
183 if (0 != rc) 183 if (0 != rc)
184 { 184 {
185 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 185 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
186 GNUNET_assert (0); 186 GNUNET_assert(0);
187 } 187 }
188#if EXTRA_CHECKS 188#if EXTRA_CHECKS
189 if (0 != (rc = gcry_pk_testkey (result))) 189 if (0 != (rc = gcry_pk_testkey(result)))
190 { 190 {
191 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 191 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
192 GNUNET_assert (0); 192 GNUNET_assert(0);
193 } 193 }
194#endif 194#endif
195 return result; 195 return result;
196} 196}
@@ -204,28 +204,28 @@ decode_private_eddsa_key (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv)
204 * @return NULL on error 204 * @return NULL on error
205 */ 205 */
206static gcry_sexp_t 206static gcry_sexp_t
207decode_private_ecdhe_key (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv) 207decode_private_ecdhe_key(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv)
208{ 208{
209 gcry_sexp_t result; 209 gcry_sexp_t result;
210 int rc; 210 int rc;
211 211
212 rc = gcry_sexp_build (&result, 212 rc = gcry_sexp_build(&result,
213 NULL, 213 NULL,
214 "(private-key(ecc(curve \"" CURVE "\")" 214 "(private-key(ecc(curve \"" CURVE "\")"
215 "(d %b)))", 215 "(d %b)))",
216 (int) sizeof (priv->d), 216 (int)sizeof(priv->d),
217 priv->d); 217 priv->d);
218 if (0 != rc) 218 if (0 != rc)
219 { 219 {
220 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 220 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
221 GNUNET_assert (0); 221 GNUNET_assert(0);
222 } 222 }
223#if EXTRA_CHECKS 223#if EXTRA_CHECKS
224 if (0 != (rc = gcry_pk_testkey (result))) 224 if (0 != (rc = gcry_pk_testkey(result)))
225 { 225 {
226 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 226 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
227 GNUNET_assert (0); 227 GNUNET_assert(0);
228 } 228 }
229#endif 229#endif
230 return result; 230 return result;
231} 231}
@@ -238,7 +238,7 @@ decode_private_ecdhe_key (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv)
238 * @param pub where to write the public key 238 * @param pub where to write the public key
239 */ 239 */
240void 240void
241GNUNET_CRYPTO_ecdsa_key_get_public ( 241GNUNET_CRYPTO_ecdsa_key_get_public(
242 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, 242 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
243 struct GNUNET_CRYPTO_EcdsaPublicKey *pub) 243 struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
244{ 244{
@@ -246,19 +246,19 @@ GNUNET_CRYPTO_ecdsa_key_get_public (
246 gcry_ctx_t ctx; 246 gcry_ctx_t ctx;
247 gcry_mpi_t q; 247 gcry_mpi_t q;
248 248
249 BENCHMARK_START (ecdsa_key_get_public); 249 BENCHMARK_START(ecdsa_key_get_public);
250 250
251 sexp = decode_private_ecdsa_key (priv); 251 sexp = decode_private_ecdsa_key(priv);
252 GNUNET_assert (NULL != sexp); 252 GNUNET_assert(NULL != sexp);
253 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL)); 253 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, sexp, NULL));
254 gcry_sexp_release (sexp); 254 gcry_sexp_release(sexp);
255 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0); 255 q = gcry_mpi_ec_get_mpi("q@eddsa", ctx, 0);
256 GNUNET_assert (NULL != q); 256 GNUNET_assert(NULL != q);
257 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q); 257 GNUNET_CRYPTO_mpi_print_unsigned(pub->q_y, sizeof(pub->q_y), q);
258 gcry_mpi_release (q); 258 gcry_mpi_release(q);
259 gcry_ctx_release (ctx); 259 gcry_ctx_release(ctx);
260 260
261 BENCHMARK_END (ecdsa_key_get_public); 261 BENCHMARK_END(ecdsa_key_get_public);
262} 262}
263 263
264 264
@@ -269,7 +269,7 @@ GNUNET_CRYPTO_ecdsa_key_get_public (
269 * @param pub where to write the public key 269 * @param pub where to write the public key
270 */ 270 */
271void 271void
272GNUNET_CRYPTO_eddsa_key_get_public ( 272GNUNET_CRYPTO_eddsa_key_get_public(
273 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, 273 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
274 struct GNUNET_CRYPTO_EddsaPublicKey *pub) 274 struct GNUNET_CRYPTO_EddsaPublicKey *pub)
275{ 275{
@@ -277,19 +277,19 @@ GNUNET_CRYPTO_eddsa_key_get_public (
277 gcry_ctx_t ctx; 277 gcry_ctx_t ctx;
278 gcry_mpi_t q; 278 gcry_mpi_t q;
279 279
280 BENCHMARK_START (eddsa_key_get_public); 280 BENCHMARK_START(eddsa_key_get_public);
281 281
282 sexp = decode_private_eddsa_key (priv); 282 sexp = decode_private_eddsa_key(priv);
283 GNUNET_assert (NULL != sexp); 283 GNUNET_assert(NULL != sexp);
284 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL)); 284 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, sexp, NULL));
285 gcry_sexp_release (sexp); 285 gcry_sexp_release(sexp);
286 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0); 286 q = gcry_mpi_ec_get_mpi("q@eddsa", ctx, 0);
287 GNUNET_assert (q); 287 GNUNET_assert(q);
288 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q); 288 GNUNET_CRYPTO_mpi_print_unsigned(pub->q_y, sizeof(pub->q_y), q);
289 gcry_mpi_release (q); 289 gcry_mpi_release(q);
290 gcry_ctx_release (ctx); 290 gcry_ctx_release(ctx);
291 291
292 BENCHMARK_END (eddsa_key_get_public); 292 BENCHMARK_END(eddsa_key_get_public);
293} 293}
294 294
295 295
@@ -300,7 +300,7 @@ GNUNET_CRYPTO_eddsa_key_get_public (
300 * @param pub where to write the public key 300 * @param pub where to write the public key
301 */ 301 */
302void 302void
303GNUNET_CRYPTO_ecdhe_key_get_public ( 303GNUNET_CRYPTO_ecdhe_key_get_public(
304 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, 304 const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
305 struct GNUNET_CRYPTO_EcdhePublicKey *pub) 305 struct GNUNET_CRYPTO_EcdhePublicKey *pub)
306{ 306{
@@ -308,19 +308,19 @@ GNUNET_CRYPTO_ecdhe_key_get_public (
308 gcry_ctx_t ctx; 308 gcry_ctx_t ctx;
309 gcry_mpi_t q; 309 gcry_mpi_t q;
310 310
311 BENCHMARK_START (ecdhe_key_get_public); 311 BENCHMARK_START(ecdhe_key_get_public);
312 312
313 sexp = decode_private_ecdhe_key (priv); 313 sexp = decode_private_ecdhe_key(priv);
314 GNUNET_assert (NULL != sexp); 314 GNUNET_assert(NULL != sexp);
315 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, sexp, NULL)); 315 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, sexp, NULL));
316 gcry_sexp_release (sexp); 316 gcry_sexp_release(sexp);
317 q = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0); 317 q = gcry_mpi_ec_get_mpi("q@eddsa", ctx, 0);
318 GNUNET_assert (q); 318 GNUNET_assert(q);
319 GNUNET_CRYPTO_mpi_print_unsigned (pub->q_y, sizeof (pub->q_y), q); 319 GNUNET_CRYPTO_mpi_print_unsigned(pub->q_y, sizeof(pub->q_y), q);
320 gcry_mpi_release (q); 320 gcry_mpi_release(q);
321 gcry_ctx_release (ctx); 321 gcry_ctx_release(ctx);
322 322
323 BENCHMARK_END (ecdhe_key_get_public); 323 BENCHMARK_END(ecdhe_key_get_public);
324} 324}
325 325
326 326
@@ -331,27 +331,27 @@ GNUNET_CRYPTO_ecdhe_key_get_public (
331 * @return string representing @a pub 331 * @return string representing @a pub
332 */ 332 */
333char * 333char *
334GNUNET_CRYPTO_ecdsa_public_key_to_string ( 334GNUNET_CRYPTO_ecdsa_public_key_to_string(
335 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub) 335 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
336{ 336{
337 char *pubkeybuf; 337 char *pubkeybuf;
338 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8; 338 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8;
339 char *end; 339 char *end;
340 340
341 if (keylen % 5 > 0) 341 if (keylen % 5 > 0)
342 keylen += 5 - keylen % 5; 342 keylen += 5 - keylen % 5;
343 keylen /= 5; 343 keylen /= 5;
344 pubkeybuf = GNUNET_malloc (keylen + 1); 344 pubkeybuf = GNUNET_malloc(keylen + 1);
345 end = 345 end =
346 GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 346 GNUNET_STRINGS_data_to_string((unsigned char *)pub,
347 sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey), 347 sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey),
348 pubkeybuf, 348 pubkeybuf,
349 keylen); 349 keylen);
350 if (NULL == end) 350 if (NULL == end)
351 { 351 {
352 GNUNET_free (pubkeybuf); 352 GNUNET_free(pubkeybuf);
353 return NULL; 353 return NULL;
354 } 354 }
355 *end = '\0'; 355 *end = '\0';
356 return pubkeybuf; 356 return pubkeybuf;
357} 357}
@@ -364,27 +364,27 @@ GNUNET_CRYPTO_ecdsa_public_key_to_string (
364 * @return string representing @a pub 364 * @return string representing @a pub
365 */ 365 */
366char * 366char *
367GNUNET_CRYPTO_eddsa_public_key_to_string ( 367GNUNET_CRYPTO_eddsa_public_key_to_string(
368 const struct GNUNET_CRYPTO_EddsaPublicKey *pub) 368 const struct GNUNET_CRYPTO_EddsaPublicKey *pub)
369{ 369{
370 char *pubkeybuf; 370 char *pubkeybuf;
371 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) * 8; 371 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)) * 8;
372 char *end; 372 char *end;
373 373
374 if (keylen % 5 > 0) 374 if (keylen % 5 > 0)
375 keylen += 5 - keylen % 5; 375 keylen += 5 - keylen % 5;
376 keylen /= 5; 376 keylen /= 5;
377 pubkeybuf = GNUNET_malloc (keylen + 1); 377 pubkeybuf = GNUNET_malloc(keylen + 1);
378 end = 378 end =
379 GNUNET_STRINGS_data_to_string ((unsigned char *) pub, 379 GNUNET_STRINGS_data_to_string((unsigned char *)pub,
380 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey), 380 sizeof(struct GNUNET_CRYPTO_EddsaPublicKey),
381 pubkeybuf, 381 pubkeybuf,
382 keylen); 382 keylen);
383 if (NULL == end) 383 if (NULL == end)
384 { 384 {
385 GNUNET_free (pubkeybuf); 385 GNUNET_free(pubkeybuf);
386 return NULL; 386 return NULL;
387 } 387 }
388 *end = '\0'; 388 *end = '\0';
389 return pubkeybuf; 389 return pubkeybuf;
390} 390}
@@ -397,27 +397,27 @@ GNUNET_CRYPTO_eddsa_public_key_to_string (
397 * @return string representing @a pub 397 * @return string representing @a pub
398 */ 398 */
399char * 399char *
400GNUNET_CRYPTO_eddsa_private_key_to_string ( 400GNUNET_CRYPTO_eddsa_private_key_to_string(
401 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv) 401 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv)
402{ 402{
403 char *privkeybuf; 403 char *privkeybuf;
404 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)) * 8; 404 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey)) * 8;
405 char *end; 405 char *end;
406 406
407 if (keylen % 5 > 0) 407 if (keylen % 5 > 0)
408 keylen += 5 - keylen % 5; 408 keylen += 5 - keylen % 5;
409 keylen /= 5; 409 keylen /= 5;
410 privkeybuf = GNUNET_malloc (keylen + 1); 410 privkeybuf = GNUNET_malloc(keylen + 1);
411 end = GNUNET_STRINGS_data_to_string ((unsigned char *) priv, 411 end = GNUNET_STRINGS_data_to_string((unsigned char *)priv,
412 sizeof ( 412 sizeof(
413 struct GNUNET_CRYPTO_EddsaPrivateKey), 413 struct GNUNET_CRYPTO_EddsaPrivateKey),
414 privkeybuf, 414 privkeybuf,
415 keylen); 415 keylen);
416 if (NULL == end) 416 if (NULL == end)
417 { 417 {
418 GNUNET_free (privkeybuf); 418 GNUNET_free(privkeybuf);
419 return NULL; 419 return NULL;
420 } 420 }
421 *end = '\0'; 421 *end = '\0';
422 return privkeybuf; 422 return privkeybuf;
423} 423}
@@ -430,27 +430,27 @@ GNUNET_CRYPTO_eddsa_private_key_to_string (
430 * @return string representing @a priv 430 * @return string representing @a priv
431 */ 431 */
432char * 432char *
433GNUNET_CRYPTO_ecdsa_private_key_to_string ( 433GNUNET_CRYPTO_ecdsa_private_key_to_string(
434 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv) 434 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv)
435{ 435{
436 char *privkeybuf; 436 char *privkeybuf;
437 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)) * 8; 437 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey)) * 8;
438 char *end; 438 char *end;
439 439
440 if (keylen % 5 > 0) 440 if (keylen % 5 > 0)
441 keylen += 5 - keylen % 5; 441 keylen += 5 - keylen % 5;
442 keylen /= 5; 442 keylen /= 5;
443 privkeybuf = GNUNET_malloc (keylen + 1); 443 privkeybuf = GNUNET_malloc(keylen + 1);
444 end = GNUNET_STRINGS_data_to_string ((unsigned char *) priv, 444 end = GNUNET_STRINGS_data_to_string((unsigned char *)priv,
445 sizeof ( 445 sizeof(
446 struct GNUNET_CRYPTO_EcdsaPrivateKey), 446 struct GNUNET_CRYPTO_EcdsaPrivateKey),
447 privkeybuf, 447 privkeybuf,
448 keylen); 448 keylen);
449 if (NULL == end) 449 if (NULL == end)
450 { 450 {
451 GNUNET_free (privkeybuf); 451 GNUNET_free(privkeybuf);
452 return NULL; 452 return NULL;
453 } 453 }
454 *end = '\0'; 454 *end = '\0';
455 return privkeybuf; 455 return privkeybuf;
456} 456}
@@ -465,12 +465,12 @@ GNUNET_CRYPTO_ecdsa_private_key_to_string (
465 * @return #GNUNET_OK on success 465 * @return #GNUNET_OK on success
466 */ 466 */
467int 467int
468GNUNET_CRYPTO_ecdsa_public_key_from_string ( 468GNUNET_CRYPTO_ecdsa_public_key_from_string(
469 const char *enc, 469 const char *enc,
470 size_t enclen, 470 size_t enclen,
471 struct GNUNET_CRYPTO_EcdsaPublicKey *pub) 471 struct GNUNET_CRYPTO_EcdsaPublicKey *pub)
472{ 472{
473 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8; 473 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EcdsaPublicKey)) * 8;
474 474
475 if (keylen % 5 > 0) 475 if (keylen % 5 > 0)
476 keylen += 5 - keylen % 5; 476 keylen += 5 - keylen % 5;
@@ -479,11 +479,11 @@ GNUNET_CRYPTO_ecdsa_public_key_from_string (
479 return GNUNET_SYSERR; 479 return GNUNET_SYSERR;
480 480
481 if (GNUNET_OK != 481 if (GNUNET_OK !=
482 GNUNET_STRINGS_string_to_data (enc, 482 GNUNET_STRINGS_string_to_data(enc,
483 enclen, 483 enclen,
484 pub, 484 pub,
485 sizeof ( 485 sizeof(
486 struct GNUNET_CRYPTO_EcdsaPublicKey))) 486 struct GNUNET_CRYPTO_EcdsaPublicKey)))
487 return GNUNET_SYSERR; 487 return GNUNET_SYSERR;
488 return GNUNET_OK; 488 return GNUNET_OK;
489} 489}
@@ -498,12 +498,12 @@ GNUNET_CRYPTO_ecdsa_public_key_from_string (
498 * @return #GNUNET_OK on success 498 * @return #GNUNET_OK on success
499 */ 499 */
500int 500int
501GNUNET_CRYPTO_eddsa_public_key_from_string ( 501GNUNET_CRYPTO_eddsa_public_key_from_string(
502 const char *enc, 502 const char *enc,
503 size_t enclen, 503 size_t enclen,
504 struct GNUNET_CRYPTO_EddsaPublicKey *pub) 504 struct GNUNET_CRYPTO_EddsaPublicKey *pub)
505{ 505{
506 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)) * 8; 506 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EddsaPublicKey)) * 8;
507 507
508 if (keylen % 5 > 0) 508 if (keylen % 5 > 0)
509 keylen += 5 - keylen % 5; 509 keylen += 5 - keylen % 5;
@@ -512,11 +512,11 @@ GNUNET_CRYPTO_eddsa_public_key_from_string (
512 return GNUNET_SYSERR; 512 return GNUNET_SYSERR;
513 513
514 if (GNUNET_OK != 514 if (GNUNET_OK !=
515 GNUNET_STRINGS_string_to_data (enc, 515 GNUNET_STRINGS_string_to_data(enc,
516 enclen, 516 enclen,
517 pub, 517 pub,
518 sizeof ( 518 sizeof(
519 struct GNUNET_CRYPTO_EddsaPublicKey))) 519 struct GNUNET_CRYPTO_EddsaPublicKey)))
520 return GNUNET_SYSERR; 520 return GNUNET_SYSERR;
521 return GNUNET_OK; 521 return GNUNET_OK;
522} 522}
@@ -531,12 +531,12 @@ GNUNET_CRYPTO_eddsa_public_key_from_string (
531 * @return #GNUNET_OK on success 531 * @return #GNUNET_OK on success
532 */ 532 */
533int 533int
534GNUNET_CRYPTO_eddsa_private_key_from_string ( 534GNUNET_CRYPTO_eddsa_private_key_from_string(
535 const char *enc, 535 const char *enc,
536 size_t enclen, 536 size_t enclen,
537 struct GNUNET_CRYPTO_EddsaPrivateKey *priv) 537 struct GNUNET_CRYPTO_EddsaPrivateKey *priv)
538{ 538{
539 size_t keylen = (sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)) * 8; 539 size_t keylen = (sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey)) * 8;
540 540
541 if (keylen % 5 > 0) 541 if (keylen % 5 > 0)
542 keylen += 5 - keylen % 5; 542 keylen += 5 - keylen % 5;
@@ -545,18 +545,18 @@ GNUNET_CRYPTO_eddsa_private_key_from_string (
545 return GNUNET_SYSERR; 545 return GNUNET_SYSERR;
546 546
547 if (GNUNET_OK != 547 if (GNUNET_OK !=
548 GNUNET_STRINGS_string_to_data (enc, 548 GNUNET_STRINGS_string_to_data(enc,
549 enclen, 549 enclen,
550 priv, 550 priv,
551 sizeof ( 551 sizeof(
552 struct GNUNET_CRYPTO_EddsaPrivateKey))) 552 struct GNUNET_CRYPTO_EddsaPrivateKey)))
553 return GNUNET_SYSERR; 553 return GNUNET_SYSERR;
554#if CRYPTO_BUG 554#if CRYPTO_BUG
555 if (GNUNET_OK != check_eddsa_key (priv)) 555 if (GNUNET_OK != check_eddsa_key(priv))
556 { 556 {
557 GNUNET_break (0); 557 GNUNET_break(0);
558 return GNUNET_OK; 558 return GNUNET_OK;
559 } 559 }
560#endif 560#endif
561 return GNUNET_OK; 561 return GNUNET_OK;
562} 562}
@@ -569,9 +569,9 @@ GNUNET_CRYPTO_eddsa_private_key_from_string (
569 * @param pk location of the key 569 * @param pk location of the key
570 */ 570 */
571void 571void
572GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk) 572GNUNET_CRYPTO_ecdhe_key_clear(struct GNUNET_CRYPTO_EcdhePrivateKey *pk)
573{ 573{
574 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EcdhePrivateKey)); 574 memset(pk, 0, sizeof(struct GNUNET_CRYPTO_EcdhePrivateKey));
575} 575}
576 576
577 577
@@ -582,9 +582,9 @@ GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk)
582 * @param pk location of the key 582 * @param pk location of the key
583 */ 583 */
584void 584void
585GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk) 585GNUNET_CRYPTO_ecdsa_key_clear(struct GNUNET_CRYPTO_EcdsaPrivateKey *pk)
586{ 586{
587 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)); 587 memset(pk, 0, sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey));
588} 588}
589 589
590 590
@@ -595,9 +595,9 @@ GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk)
595 * @param pk location of the key 595 * @param pk location of the key
596 */ 596 */
597void 597void
598GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk) 598GNUNET_CRYPTO_eddsa_key_clear(struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
599{ 599{
600 memset (pk, 0, sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)); 600 memset(pk, 0, sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey));
601} 601}
602 602
603 603
@@ -607,16 +607,16 @@ GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk)
607 * @return fresh private key 607 * @return fresh private key
608 */ 608 */
609struct GNUNET_CRYPTO_EcdhePrivateKey * 609struct GNUNET_CRYPTO_EcdhePrivateKey *
610GNUNET_CRYPTO_ecdhe_key_create () 610GNUNET_CRYPTO_ecdhe_key_create()
611{ 611{
612 struct GNUNET_CRYPTO_EcdhePrivateKey *priv; 612 struct GNUNET_CRYPTO_EcdhePrivateKey *priv;
613 613
614 priv = GNUNET_new (struct GNUNET_CRYPTO_EcdhePrivateKey); 614 priv = GNUNET_new(struct GNUNET_CRYPTO_EcdhePrivateKey);
615 if (GNUNET_OK != GNUNET_CRYPTO_ecdhe_key_create2 (priv)) 615 if (GNUNET_OK != GNUNET_CRYPTO_ecdhe_key_create2(priv))
616 { 616 {
617 GNUNET_free (priv); 617 GNUNET_free(priv);
618 return NULL; 618 return NULL;
619 } 619 }
620 return priv; 620 return priv;
621} 621}
622 622
@@ -629,54 +629,54 @@ GNUNET_CRYPTO_ecdhe_key_create ()
629 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 629 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
630 */ 630 */
631int 631int
632GNUNET_CRYPTO_ecdhe_key_create2 (struct GNUNET_CRYPTO_EcdhePrivateKey *pk) 632GNUNET_CRYPTO_ecdhe_key_create2(struct GNUNET_CRYPTO_EcdhePrivateKey *pk)
633{ 633{
634 gcry_sexp_t priv_sexp; 634 gcry_sexp_t priv_sexp;
635 gcry_sexp_t s_keyparam; 635 gcry_sexp_t s_keyparam;
636 gcry_mpi_t d; 636 gcry_mpi_t d;
637 int rc; 637 int rc;
638 638
639 BENCHMARK_START (ecdhe_key_create); 639 BENCHMARK_START(ecdhe_key_create);
640 640
641 /* NOTE: For libgcrypt >= 1.7, we do not need the 'eddsa' flag here, 641 /* NOTE: For libgcrypt >= 1.7, we do not need the 'eddsa' flag here,
642 but should also be harmless. For libgcrypt < 1.7, using 'eddsa' 642 but should also be harmless. For libgcrypt < 1.7, using 'eddsa'
643 disables an expensive key testing routine. We do not want to run 643 disables an expensive key testing routine. We do not want to run
644 the expensive check for ECDHE, as we generate TONS of keys to 644 the expensive check for ECDHE, as we generate TONS of keys to
645 use for a very short time. */ 645 use for a very short time. */
646 if (0 != (rc = gcry_sexp_build (&s_keyparam, 646 if (0 != (rc = gcry_sexp_build(&s_keyparam,
647 NULL, 647 NULL,
648 "(genkey(ecc(curve \"" CURVE "\")" 648 "(genkey(ecc(curve \"" CURVE "\")"
649 "(flags eddsa no-keytest)))"))) 649 "(flags eddsa no-keytest)))")))
650 { 650 {
651 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 651 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
652 return GNUNET_SYSERR; 652 return GNUNET_SYSERR;
653 } 653 }
654 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam))) 654 if (0 != (rc = gcry_pk_genkey(&priv_sexp, s_keyparam)))
655 { 655 {
656 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc); 656 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
657 gcry_sexp_release (s_keyparam); 657 gcry_sexp_release(s_keyparam);
658 return GNUNET_SYSERR; 658 return GNUNET_SYSERR;
659 } 659 }
660 gcry_sexp_release (s_keyparam); 660 gcry_sexp_release(s_keyparam);
661#if EXTRA_CHECKS 661#if EXTRA_CHECKS
662 if (0 != (rc = gcry_pk_testkey (priv_sexp))) 662 if (0 != (rc = gcry_pk_testkey(priv_sexp)))
663 { 663 {
664 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 664 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
665 gcry_sexp_release (priv_sexp); 665 gcry_sexp_release(priv_sexp);
666 return GNUNET_SYSERR; 666 return GNUNET_SYSERR;
667 } 667 }
668#endif 668#endif
669 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d"))) 669 if (0 != (rc = key_from_sexp(&d, priv_sexp, "private-key", "d")))
670 { 670 {
671 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc); 671 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
672 gcry_sexp_release (priv_sexp); 672 gcry_sexp_release(priv_sexp);
673 return GNUNET_SYSERR; 673 return GNUNET_SYSERR;
674 } 674 }
675 gcry_sexp_release (priv_sexp); 675 gcry_sexp_release(priv_sexp);
676 GNUNET_CRYPTO_mpi_print_unsigned (pk->d, sizeof (pk->d), d); 676 GNUNET_CRYPTO_mpi_print_unsigned(pk->d, sizeof(pk->d), d);
677 gcry_mpi_release (d); 677 gcry_mpi_release(d);
678 678
679 BENCHMARK_END (ecdhe_key_create); 679 BENCHMARK_END(ecdhe_key_create);
680 680
681 return GNUNET_OK; 681 return GNUNET_OK;
682} 682}
@@ -688,7 +688,7 @@ GNUNET_CRYPTO_ecdhe_key_create2 (struct GNUNET_CRYPTO_EcdhePrivateKey *pk)
688 * @return fresh private key 688 * @return fresh private key
689 */ 689 */
690struct GNUNET_CRYPTO_EcdsaPrivateKey * 690struct GNUNET_CRYPTO_EcdsaPrivateKey *
691GNUNET_CRYPTO_ecdsa_key_create () 691GNUNET_CRYPTO_ecdsa_key_create()
692{ 692{
693 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv; 693 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
694 gcry_sexp_t priv_sexp; 694 gcry_sexp_t priv_sexp;
@@ -696,43 +696,43 @@ GNUNET_CRYPTO_ecdsa_key_create ()
696 gcry_mpi_t d; 696 gcry_mpi_t d;
697 int rc; 697 int rc;
698 698
699 BENCHMARK_START (ecdsa_key_create); 699 BENCHMARK_START(ecdsa_key_create);
700 700
701 if (0 != (rc = gcry_sexp_build (&s_keyparam, 701 if (0 != (rc = gcry_sexp_build(&s_keyparam,
702 NULL, 702 NULL,
703 "(genkey(ecc(curve \"" CURVE "\")" 703 "(genkey(ecc(curve \"" CURVE "\")"
704 "(flags)))"))) 704 "(flags)))")))
705 { 705 {
706 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 706 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
707 return NULL; 707 return NULL;
708 } 708 }
709 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam))) 709 if (0 != (rc = gcry_pk_genkey(&priv_sexp, s_keyparam)))
710 { 710 {
711 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc); 711 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
712 gcry_sexp_release (s_keyparam); 712 gcry_sexp_release(s_keyparam);
713 return NULL; 713 return NULL;
714 } 714 }
715 gcry_sexp_release (s_keyparam); 715 gcry_sexp_release(s_keyparam);
716#if EXTRA_CHECKS 716#if EXTRA_CHECKS
717 if (0 != (rc = gcry_pk_testkey (priv_sexp))) 717 if (0 != (rc = gcry_pk_testkey(priv_sexp)))
718 { 718 {
719 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 719 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
720 gcry_sexp_release (priv_sexp); 720 gcry_sexp_release(priv_sexp);
721 return NULL; 721 return NULL;
722 } 722 }
723#endif 723#endif
724 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d"))) 724 if (0 != (rc = key_from_sexp(&d, priv_sexp, "private-key", "d")))
725 { 725 {
726 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc); 726 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
727 gcry_sexp_release (priv_sexp); 727 gcry_sexp_release(priv_sexp);
728 return NULL; 728 return NULL;
729 } 729 }
730 gcry_sexp_release (priv_sexp); 730 gcry_sexp_release(priv_sexp);
731 priv = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); 731 priv = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey);
732 GNUNET_CRYPTO_mpi_print_unsigned (priv->d, sizeof (priv->d), d); 732 GNUNET_CRYPTO_mpi_print_unsigned(priv->d, sizeof(priv->d), d);
733 gcry_mpi_release (d); 733 gcry_mpi_release(d);
734 734
735 BENCHMARK_END (ecdsa_key_create); 735 BENCHMARK_END(ecdsa_key_create);
736 736
737 return priv; 737 return priv;
738} 738}
@@ -743,7 +743,7 @@ GNUNET_CRYPTO_ecdsa_key_create ()
743 * @return fresh private key 743 * @return fresh private key
744 */ 744 */
745struct GNUNET_CRYPTO_EddsaPrivateKey * 745struct GNUNET_CRYPTO_EddsaPrivateKey *
746GNUNET_CRYPTO_eddsa_key_create () 746GNUNET_CRYPTO_eddsa_key_create()
747{ 747{
748 struct GNUNET_CRYPTO_EddsaPrivateKey *priv; 748 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
749 gcry_sexp_t priv_sexp; 749 gcry_sexp_t priv_sexp;
@@ -751,55 +751,55 @@ GNUNET_CRYPTO_eddsa_key_create ()
751 gcry_mpi_t d; 751 gcry_mpi_t d;
752 int rc; 752 int rc;
753 753
754 BENCHMARK_START (eddsa_key_create); 754 BENCHMARK_START(eddsa_key_create);
755 755
756#if CRYPTO_BUG 756#if CRYPTO_BUG
757again: 757again:
758#endif 758#endif
759 if (0 != (rc = gcry_sexp_build (&s_keyparam, 759 if (0 != (rc = gcry_sexp_build(&s_keyparam,
760 NULL, 760 NULL,
761 "(genkey(ecc(curve \"" CURVE "\")" 761 "(genkey(ecc(curve \"" CURVE "\")"
762 "(flags eddsa)))"))) 762 "(flags eddsa)))")))
763 { 763 {
764 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 764 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
765 return NULL; 765 return NULL;
766 } 766 }
767 if (0 != (rc = gcry_pk_genkey (&priv_sexp, s_keyparam))) 767 if (0 != (rc = gcry_pk_genkey(&priv_sexp, s_keyparam)))
768 { 768 {
769 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc); 769 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_genkey", rc);
770 gcry_sexp_release (s_keyparam); 770 gcry_sexp_release(s_keyparam);
771 return NULL; 771 return NULL;
772 } 772 }
773 gcry_sexp_release (s_keyparam); 773 gcry_sexp_release(s_keyparam);
774#if EXTRA_CHECKS 774#if EXTRA_CHECKS
775 if (0 != (rc = gcry_pk_testkey (priv_sexp))) 775 if (0 != (rc = gcry_pk_testkey(priv_sexp)))
776 { 776 {
777 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc); 777 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_pk_testkey", rc);
778 gcry_sexp_release (priv_sexp); 778 gcry_sexp_release(priv_sexp);
779 return NULL; 779 return NULL;
780 } 780 }
781#endif 781#endif
782 if (0 != (rc = key_from_sexp (&d, priv_sexp, "private-key", "d"))) 782 if (0 != (rc = key_from_sexp(&d, priv_sexp, "private-key", "d")))
783 { 783 {
784 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc); 784 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "key_from_sexp", rc);
785 gcry_sexp_release (priv_sexp); 785 gcry_sexp_release(priv_sexp);
786 return NULL; 786 return NULL;
787 } 787 }
788 gcry_sexp_release (priv_sexp); 788 gcry_sexp_release(priv_sexp);
789 priv = GNUNET_new (struct GNUNET_CRYPTO_EddsaPrivateKey); 789 priv = GNUNET_new(struct GNUNET_CRYPTO_EddsaPrivateKey);
790 GNUNET_CRYPTO_mpi_print_unsigned (priv->d, sizeof (priv->d), d); 790 GNUNET_CRYPTO_mpi_print_unsigned(priv->d, sizeof(priv->d), d);
791 gcry_mpi_release (d); 791 gcry_mpi_release(d);
792 792
793#if CRYPTO_BUG 793#if CRYPTO_BUG
794 if (GNUNET_OK != check_eddsa_key (priv)) 794 if (GNUNET_OK != check_eddsa_key(priv))
795 { 795 {
796 GNUNET_break (0); 796 GNUNET_break(0);
797 GNUNET_free (priv); 797 GNUNET_free(priv);
798 goto again; 798 goto again;
799 } 799 }
800#endif 800#endif
801 801
802 BENCHMARK_END (eddsa_key_create); 802 BENCHMARK_END(eddsa_key_create);
803 803
804 return priv; 804 return priv;
805} 805}
@@ -811,7 +811,7 @@ again:
811 * @return "anonymous" private key 811 * @return "anonymous" private key
812 */ 812 */
813const struct GNUNET_CRYPTO_EcdsaPrivateKey * 813const struct GNUNET_CRYPTO_EcdsaPrivateKey *
814GNUNET_CRYPTO_ecdsa_key_get_anonymous () 814GNUNET_CRYPTO_ecdsa_key_get_anonymous()
815{ 815{
816 /** 816 /**
817 * 'anonymous' pseudonym (global static, d=1, public key = G 817 * 'anonymous' pseudonym (global static, d=1, public key = G
@@ -822,9 +822,9 @@ GNUNET_CRYPTO_ecdsa_key_get_anonymous ()
822 822
823 if (once) 823 if (once)
824 return &anonymous; 824 return &anonymous;
825 GNUNET_CRYPTO_mpi_print_unsigned (anonymous.d, 825 GNUNET_CRYPTO_mpi_print_unsigned(anonymous.d,
826 sizeof (anonymous.d), 826 sizeof(anonymous.d),
827 GCRYMPI_CONST_ONE); 827 GCRYMPI_CONST_ONE);
828 once = 1; 828 once = 1;
829 return &anonymous; 829 return &anonymous;
830} 830}
@@ -838,7 +838,7 @@ GNUNET_CRYPTO_ecdsa_key_get_anonymous ()
838 * @return converted s-expression 838 * @return converted s-expression
839 */ 839 */
840static gcry_sexp_t 840static gcry_sexp_t
841data_to_eddsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose) 841data_to_eddsa_value(const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
842{ 842{
843 gcry_sexp_t data; 843 gcry_sexp_t data;
844 int rc; 844 int rc;
@@ -847,29 +847,29 @@ data_to_eddsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
847#if 1 847#if 1
848 struct GNUNET_HashCode hc; 848 struct GNUNET_HashCode hc;
849 849
850 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc); 850 GNUNET_CRYPTO_hash(purpose, ntohl(purpose->size), &hc);
851 if (0 != (rc = gcry_sexp_build (&data, 851 if (0 != (rc = gcry_sexp_build(&data,
852 NULL, 852 NULL,
853 "(data(flags eddsa)(hash-algo %s)(value %b))", 853 "(data(flags eddsa)(hash-algo %s)(value %b))",
854 "sha512", 854 "sha512",
855 (int) sizeof (hc), 855 (int)sizeof(hc),
856 &hc))) 856 &hc)))
857 { 857 {
858 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 858 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
859 return NULL; 859 return NULL;
860 } 860 }
861#else 861#else
862 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc); 862 GNUNET_CRYPTO_hash(purpose, ntohl(purpose->size), &hc);
863 if (0 != (rc = gcry_sexp_build (&data, 863 if (0 != (rc = gcry_sexp_build(&data,
864 NULL, 864 NULL,
865 "(data(flags eddsa)(hash-algo %s)(value %b))", 865 "(data(flags eddsa)(hash-algo %s)(value %b))",
866 "sha512", 866 "sha512",
867 ntohl (purpose->size), 867 ntohl(purpose->size),
868 purpose))) 868 purpose)))
869 { 869 {
870 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 870 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
871 return NULL; 871 return NULL;
872 } 872 }
873#endif 873#endif
874 return data; 874 return data;
875} 875}
@@ -883,7 +883,7 @@ data_to_eddsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
883 * @return converted s-expression 883 * @return converted s-expression
884 */ 884 */
885static gcry_sexp_t 885static gcry_sexp_t
886data_to_ecdsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose) 886data_to_ecdsa_value(const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
887{ 887{
888 gcry_sexp_t data; 888 gcry_sexp_t data;
889 int rc; 889 int rc;
@@ -892,28 +892,28 @@ data_to_ecdsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
892#if 1 892#if 1
893 struct GNUNET_HashCode hc; 893 struct GNUNET_HashCode hc;
894 894
895 GNUNET_CRYPTO_hash (purpose, ntohl (purpose->size), &hc); 895 GNUNET_CRYPTO_hash(purpose, ntohl(purpose->size), &hc);
896 if (0 != (rc = gcry_sexp_build (&data, 896 if (0 != (rc = gcry_sexp_build(&data,
897 NULL, 897 NULL,
898 "(data(flags rfc6979)(hash %s %b))", 898 "(data(flags rfc6979)(hash %s %b))",
899 "sha512", 899 "sha512",
900 (int) sizeof (hc), 900 (int)sizeof(hc),
901 &hc))) 901 &hc)))
902 { 902 {
903 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 903 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
904 return NULL; 904 return NULL;
905 } 905 }
906#else 906#else
907 if (0 != (rc = gcry_sexp_build (&data, 907 if (0 != (rc = gcry_sexp_build(&data,
908 NULL, 908 NULL,
909 "(data(flags rfc6979)(hash %s %b))", 909 "(data(flags rfc6979)(hash %s %b))",
910 "sha512", 910 "sha512",
911 ntohl (purpose->size), 911 ntohl(purpose->size),
912 purpose))) 912 purpose)))
913 { 913 {
914 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 914 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
915 return NULL; 915 return NULL;
916 } 916 }
917#endif 917#endif
918 return data; 918 return data;
919} 919}
@@ -928,7 +928,7 @@ data_to_ecdsa_value (const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose)
928 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 928 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
929 */ 929 */
930int 930int
931GNUNET_CRYPTO_ecdsa_sign ( 931GNUNET_CRYPTO_ecdsa_sign(
932 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, 932 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
933 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose, 933 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
934 struct GNUNET_CRYPTO_EcdsaSignature *sig) 934 struct GNUNET_CRYPTO_EcdsaSignature *sig)
@@ -939,39 +939,39 @@ GNUNET_CRYPTO_ecdsa_sign (
939 int rc; 939 int rc;
940 gcry_mpi_t rs[2]; 940 gcry_mpi_t rs[2];
941 941
942 BENCHMARK_START (ecdsa_sign); 942 BENCHMARK_START(ecdsa_sign);
943 943
944 priv_sexp = decode_private_ecdsa_key (priv); 944 priv_sexp = decode_private_ecdsa_key(priv);
945 data = data_to_ecdsa_value (purpose); 945 data = data_to_ecdsa_value(purpose);
946 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp))) 946 if (0 != (rc = gcry_pk_sign(&sig_sexp, data, priv_sexp)))
947 { 947 {
948 LOG (GNUNET_ERROR_TYPE_WARNING, 948 LOG(GNUNET_ERROR_TYPE_WARNING,
949 _ ("ECC signing failed at %s:%d: %s\n"), 949 _("ECC signing failed at %s:%d: %s\n"),
950 __FILE__, 950 __FILE__,
951 __LINE__, 951 __LINE__,
952 gcry_strerror (rc)); 952 gcry_strerror(rc));
953 gcry_sexp_release (data); 953 gcry_sexp_release(data);
954 gcry_sexp_release (priv_sexp); 954 gcry_sexp_release(priv_sexp);
955 return GNUNET_SYSERR; 955 return GNUNET_SYSERR;
956 } 956 }
957 gcry_sexp_release (priv_sexp); 957 gcry_sexp_release(priv_sexp);
958 gcry_sexp_release (data); 958 gcry_sexp_release(data);
959 959
960 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in 960 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
961 'signature' */ 961 'signature' */
962 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs"))) 962 if (0 != (rc = key_from_sexp(rs, sig_sexp, "sig-val", "rs")))
963 { 963 {
964 GNUNET_break (0); 964 GNUNET_break(0);
965 gcry_sexp_release (sig_sexp); 965 gcry_sexp_release(sig_sexp);
966 return GNUNET_SYSERR; 966 return GNUNET_SYSERR;
967 } 967 }
968 gcry_sexp_release (sig_sexp); 968 gcry_sexp_release(sig_sexp);
969 GNUNET_CRYPTO_mpi_print_unsigned (sig->r, sizeof (sig->r), rs[0]); 969 GNUNET_CRYPTO_mpi_print_unsigned(sig->r, sizeof(sig->r), rs[0]);
970 GNUNET_CRYPTO_mpi_print_unsigned (sig->s, sizeof (sig->s), rs[1]); 970 GNUNET_CRYPTO_mpi_print_unsigned(sig->s, sizeof(sig->s), rs[1]);
971 gcry_mpi_release (rs[0]); 971 gcry_mpi_release(rs[0]);
972 gcry_mpi_release (rs[1]); 972 gcry_mpi_release(rs[1]);
973 973
974 BENCHMARK_END (ecdsa_sign); 974 BENCHMARK_END(ecdsa_sign);
975 975
976 return GNUNET_OK; 976 return GNUNET_OK;
977} 977}
@@ -986,7 +986,7 @@ GNUNET_CRYPTO_ecdsa_sign (
986 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 986 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
987 */ 987 */
988int 988int
989GNUNET_CRYPTO_eddsa_sign ( 989GNUNET_CRYPTO_eddsa_sign(
990 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, 990 const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
991 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose, 991 const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
992 struct GNUNET_CRYPTO_EddsaSignature *sig) 992 struct GNUNET_CRYPTO_EddsaSignature *sig)
@@ -997,39 +997,39 @@ GNUNET_CRYPTO_eddsa_sign (
997 int rc; 997 int rc;
998 gcry_mpi_t rs[2]; 998 gcry_mpi_t rs[2];
999 999
1000 BENCHMARK_START (eddsa_sign); 1000 BENCHMARK_START(eddsa_sign);
1001 1001
1002 priv_sexp = decode_private_eddsa_key (priv); 1002 priv_sexp = decode_private_eddsa_key(priv);
1003 data = data_to_eddsa_value (purpose); 1003 data = data_to_eddsa_value(purpose);
1004 if (0 != (rc = gcry_pk_sign (&sig_sexp, data, priv_sexp))) 1004 if (0 != (rc = gcry_pk_sign(&sig_sexp, data, priv_sexp)))
1005 { 1005 {
1006 LOG (GNUNET_ERROR_TYPE_WARNING, 1006 LOG(GNUNET_ERROR_TYPE_WARNING,
1007 _ ("EdDSA signing failed at %s:%d: %s\n"), 1007 _("EdDSA signing failed at %s:%d: %s\n"),
1008 __FILE__, 1008 __FILE__,
1009 __LINE__, 1009 __LINE__,
1010 gcry_strerror (rc)); 1010 gcry_strerror(rc));
1011 gcry_sexp_release (data); 1011 gcry_sexp_release(data);
1012 gcry_sexp_release (priv_sexp); 1012 gcry_sexp_release(priv_sexp);
1013 return GNUNET_SYSERR; 1013 return GNUNET_SYSERR;
1014 } 1014 }
1015 gcry_sexp_release (priv_sexp); 1015 gcry_sexp_release(priv_sexp);
1016 gcry_sexp_release (data); 1016 gcry_sexp_release(data);
1017 1017
1018 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in 1018 /* extract 'r' and 's' values from sexpression 'sig_sexp' and store in
1019 'signature' */ 1019 'signature' */
1020 if (0 != (rc = key_from_sexp (rs, sig_sexp, "sig-val", "rs"))) 1020 if (0 != (rc = key_from_sexp(rs, sig_sexp, "sig-val", "rs")))
1021 { 1021 {
1022 GNUNET_break (0); 1022 GNUNET_break(0);
1023 gcry_sexp_release (sig_sexp); 1023 gcry_sexp_release(sig_sexp);
1024 return GNUNET_SYSERR; 1024 return GNUNET_SYSERR;
1025 } 1025 }
1026 gcry_sexp_release (sig_sexp); 1026 gcry_sexp_release(sig_sexp);
1027 GNUNET_CRYPTO_mpi_print_unsigned (sig->r, sizeof (sig->r), rs[0]); 1027 GNUNET_CRYPTO_mpi_print_unsigned(sig->r, sizeof(sig->r), rs[0]);
1028 GNUNET_CRYPTO_mpi_print_unsigned (sig->s, sizeof (sig->s), rs[1]); 1028 GNUNET_CRYPTO_mpi_print_unsigned(sig->s, sizeof(sig->s), rs[1]);
1029 gcry_mpi_release (rs[0]); 1029 gcry_mpi_release(rs[0]);
1030 gcry_mpi_release (rs[1]); 1030 gcry_mpi_release(rs[1]);
1031 1031
1032 BENCHMARK_END (eddsa_sign); 1032 BENCHMARK_END(eddsa_sign);
1033 1033
1034 return GNUNET_OK; 1034 return GNUNET_OK;
1035} 1035}
@@ -1045,7 +1045,7 @@ GNUNET_CRYPTO_eddsa_sign (
1045 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid 1045 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1046 */ 1046 */
1047int 1047int
1048GNUNET_CRYPTO_ecdsa_verify ( 1048GNUNET_CRYPTO_ecdsa_verify(
1049 uint32_t purpose, 1049 uint32_t purpose,
1050 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate, 1050 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1051 const struct GNUNET_CRYPTO_EcdsaSignature *sig, 1051 const struct GNUNET_CRYPTO_EcdsaSignature *sig,
@@ -1056,49 +1056,49 @@ GNUNET_CRYPTO_ecdsa_verify (
1056 gcry_sexp_t pub_sexpr; 1056 gcry_sexp_t pub_sexpr;
1057 int rc; 1057 int rc;
1058 1058
1059 BENCHMARK_START (ecdsa_verify); 1059 BENCHMARK_START(ecdsa_verify);
1060 1060
1061 if (purpose != ntohl (validate->purpose)) 1061 if (purpose != ntohl(validate->purpose))
1062 return GNUNET_SYSERR; /* purpose mismatch */ 1062 return GNUNET_SYSERR; /* purpose mismatch */
1063 1063
1064 /* build s-expression for signature */ 1064 /* build s-expression for signature */
1065 if (0 != (rc = gcry_sexp_build (&sig_sexpr, 1065 if (0 != (rc = gcry_sexp_build(&sig_sexpr,
1066 NULL, 1066 NULL,
1067 "(sig-val(ecdsa(r %b)(s %b)))", 1067 "(sig-val(ecdsa(r %b)(s %b)))",
1068 (int) sizeof (sig->r), 1068 (int)sizeof(sig->r),
1069 sig->r, 1069 sig->r,
1070 (int) sizeof (sig->s), 1070 (int)sizeof(sig->s),
1071 sig->s))) 1071 sig->s)))
1072 { 1072 {
1073 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 1073 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1074 return GNUNET_SYSERR; 1074 return GNUNET_SYSERR;
1075 } 1075 }
1076 data = data_to_ecdsa_value (validate); 1076 data = data_to_ecdsa_value(validate);
1077 if (0 != (rc = gcry_sexp_build (&pub_sexpr, 1077 if (0 != (rc = gcry_sexp_build(&pub_sexpr,
1078 NULL, 1078 NULL,
1079 "(public-key(ecc(curve " CURVE ")(q %b)))", 1079 "(public-key(ecc(curve " CURVE ")(q %b)))",
1080 (int) sizeof (pub->q_y), 1080 (int)sizeof(pub->q_y),
1081 pub->q_y))) 1081 pub->q_y)))
1082 { 1082 {
1083 gcry_sexp_release (data); 1083 gcry_sexp_release(data);
1084 gcry_sexp_release (sig_sexpr); 1084 gcry_sexp_release(sig_sexpr);
1085 return GNUNET_SYSERR; 1085 return GNUNET_SYSERR;
1086 } 1086 }
1087 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr); 1087 rc = gcry_pk_verify(sig_sexpr, data, pub_sexpr);
1088 gcry_sexp_release (pub_sexpr); 1088 gcry_sexp_release(pub_sexpr);
1089 gcry_sexp_release (data); 1089 gcry_sexp_release(data);
1090 gcry_sexp_release (sig_sexpr); 1090 gcry_sexp_release(sig_sexpr);
1091 if (0 != rc) 1091 if (0 != rc)
1092 { 1092 {
1093 LOG (GNUNET_ERROR_TYPE_INFO, 1093 LOG(GNUNET_ERROR_TYPE_INFO,
1094 _ ("ECDSA signature verification failed at %s:%d: %s\n"), 1094 _("ECDSA signature verification failed at %s:%d: %s\n"),
1095 __FILE__, 1095 __FILE__,
1096 __LINE__, 1096 __LINE__,
1097 gcry_strerror (rc)); 1097 gcry_strerror(rc));
1098 BENCHMARK_END (ecdsa_verify); 1098 BENCHMARK_END(ecdsa_verify);
1099 return GNUNET_SYSERR; 1099 return GNUNET_SYSERR;
1100 } 1100 }
1101 BENCHMARK_END (ecdsa_verify); 1101 BENCHMARK_END(ecdsa_verify);
1102 return GNUNET_OK; 1102 return GNUNET_OK;
1103} 1103}
1104 1104
@@ -1113,7 +1113,7 @@ GNUNET_CRYPTO_ecdsa_verify (
1113 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid 1113 * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1114 */ 1114 */
1115int 1115int
1116GNUNET_CRYPTO_eddsa_verify ( 1116GNUNET_CRYPTO_eddsa_verify(
1117 uint32_t purpose, 1117 uint32_t purpose,
1118 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate, 1118 const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1119 const struct GNUNET_CRYPTO_EddsaSignature *sig, 1119 const struct GNUNET_CRYPTO_EddsaSignature *sig,
@@ -1124,51 +1124,51 @@ GNUNET_CRYPTO_eddsa_verify (
1124 gcry_sexp_t pub_sexpr; 1124 gcry_sexp_t pub_sexpr;
1125 int rc; 1125 int rc;
1126 1126
1127 BENCHMARK_START (eddsa_verify); 1127 BENCHMARK_START(eddsa_verify);
1128 1128
1129 if (purpose != ntohl (validate->purpose)) 1129 if (purpose != ntohl(validate->purpose))
1130 return GNUNET_SYSERR; /* purpose mismatch */ 1130 return GNUNET_SYSERR; /* purpose mismatch */
1131 1131
1132 /* build s-expression for signature */ 1132 /* build s-expression for signature */
1133 if (0 != (rc = gcry_sexp_build (&sig_sexpr, 1133 if (0 != (rc = gcry_sexp_build(&sig_sexpr,
1134 NULL, 1134 NULL,
1135 "(sig-val(eddsa(r %b)(s %b)))", 1135 "(sig-val(eddsa(r %b)(s %b)))",
1136 (int) sizeof (sig->r), 1136 (int)sizeof(sig->r),
1137 sig->r, 1137 sig->r,
1138 (int) sizeof (sig->s), 1138 (int)sizeof(sig->s),
1139 sig->s))) 1139 sig->s)))
1140 { 1140 {
1141 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc); 1141 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "gcry_sexp_build", rc);
1142 return GNUNET_SYSERR; 1142 return GNUNET_SYSERR;
1143 } 1143 }
1144 data = data_to_eddsa_value (validate); 1144 data = data_to_eddsa_value(validate);
1145 if (0 != (rc = gcry_sexp_build (&pub_sexpr, 1145 if (0 != (rc = gcry_sexp_build(&pub_sexpr,
1146 NULL, 1146 NULL,
1147 "(public-key(ecc(curve " CURVE 1147 "(public-key(ecc(curve " CURVE
1148 ")(flags eddsa)(q %b)))", 1148 ")(flags eddsa)(q %b)))",
1149 (int) sizeof (pub->q_y), 1149 (int)sizeof(pub->q_y),
1150 pub->q_y))) 1150 pub->q_y)))
1151 { 1151 {
1152 gcry_sexp_release (data); 1152 gcry_sexp_release(data);
1153 gcry_sexp_release (sig_sexpr); 1153 gcry_sexp_release(sig_sexpr);
1154 return GNUNET_SYSERR; 1154 return GNUNET_SYSERR;
1155 } 1155 }
1156 rc = gcry_pk_verify (sig_sexpr, data, pub_sexpr); 1156 rc = gcry_pk_verify(sig_sexpr, data, pub_sexpr);
1157 gcry_sexp_release (pub_sexpr); 1157 gcry_sexp_release(pub_sexpr);
1158 gcry_sexp_release (data); 1158 gcry_sexp_release(data);
1159 gcry_sexp_release (sig_sexpr); 1159 gcry_sexp_release(sig_sexpr);
1160 if (0 != rc) 1160 if (0 != rc)
1161 { 1161 {
1162 LOG (GNUNET_ERROR_TYPE_INFO, 1162 LOG(GNUNET_ERROR_TYPE_INFO,
1163 _ ("EdDSA signature verification of type %u failed at %s:%d: %s\n"), 1163 _("EdDSA signature verification of type %u failed at %s:%d: %s\n"),
1164 (unsigned int) purpose, 1164 (unsigned int)purpose,
1165 __FILE__, 1165 __FILE__,
1166 __LINE__, 1166 __LINE__,
1167 gcry_strerror (rc)); 1167 gcry_strerror(rc));
1168 BENCHMARK_END (eddsa_verify); 1168 BENCHMARK_END(eddsa_verify);
1169 return GNUNET_SYSERR; 1169 return GNUNET_SYSERR;
1170 } 1170 }
1171 BENCHMARK_END (eddsa_verify); 1171 BENCHMARK_END(eddsa_verify);
1172 return GNUNET_OK; 1172 return GNUNET_OK;
1173} 1173}
1174 1174
@@ -1182,9 +1182,9 @@ GNUNET_CRYPTO_eddsa_verify (
1182 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 1182 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1183 */ 1183 */
1184int 1184int
1185GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, 1185GNUNET_CRYPTO_ecc_ecdh(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1186 const struct GNUNET_CRYPTO_EcdhePublicKey *pub, 1186 const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1187 struct GNUNET_HashCode *key_material) 1187 struct GNUNET_HashCode *key_material)
1188{ 1188{
1189 gcry_mpi_point_t result; 1189 gcry_mpi_point_t result;
1190 gcry_mpi_point_t q; 1190 gcry_mpi_point_t q;
@@ -1195,51 +1195,51 @@ GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1195 unsigned char xbuf[256 / 8]; 1195 unsigned char xbuf[256 / 8];
1196 size_t rsize; 1196 size_t rsize;
1197 1197
1198 BENCHMARK_START (ecc_ecdh); 1198 BENCHMARK_START(ecc_ecdh);
1199 1199
1200 /* first, extract the q = dP value from the public key */ 1200 /* first, extract the q = dP value from the public key */
1201 if (0 != gcry_sexp_build (&pub_sexpr, 1201 if (0 != gcry_sexp_build(&pub_sexpr,
1202 NULL, 1202 NULL,
1203 "(public-key(ecc(curve " CURVE ")(q %b)))", 1203 "(public-key(ecc(curve " CURVE ")(q %b)))",
1204 (int) sizeof (pub->q_y), 1204 (int)sizeof(pub->q_y),
1205 pub->q_y)) 1205 pub->q_y))
1206 return GNUNET_SYSERR; 1206 return GNUNET_SYSERR;
1207 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)); 1207 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, pub_sexpr, NULL));
1208 gcry_sexp_release (pub_sexpr); 1208 gcry_sexp_release(pub_sexpr);
1209 q = gcry_mpi_ec_get_point ("q", ctx, 0); 1209 q = gcry_mpi_ec_get_point("q", ctx, 0);
1210 1210
1211 /* second, extract the d value from our private key */ 1211 /* second, extract the d value from our private key */
1212 GNUNET_CRYPTO_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d)); 1212 GNUNET_CRYPTO_mpi_scan_unsigned(&d, priv->d, sizeof(priv->d));
1213 1213
1214 /* then call the 'multiply' function, to compute the product */ 1214 /* then call the 'multiply' function, to compute the product */
1215 result = gcry_mpi_point_new (0); 1215 result = gcry_mpi_point_new(0);
1216 gcry_mpi_ec_mul (result, d, q, ctx); 1216 gcry_mpi_ec_mul(result, d, q, ctx);
1217 gcry_mpi_point_release (q); 1217 gcry_mpi_point_release(q);
1218 gcry_mpi_release (d); 1218 gcry_mpi_release(d);
1219 1219
1220 /* finally, convert point to string for hashing */ 1220 /* finally, convert point to string for hashing */
1221 result_x = gcry_mpi_new (256); 1221 result_x = gcry_mpi_new(256);
1222 if (gcry_mpi_ec_get_affine (result_x, NULL, result, ctx)) 1222 if (gcry_mpi_ec_get_affine(result_x, NULL, result, ctx))
1223 { 1223 {
1224 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0); 1224 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
1225 gcry_mpi_point_release (result); 1225 gcry_mpi_point_release(result);
1226 gcry_ctx_release (ctx); 1226 gcry_ctx_release(ctx);
1227 return GNUNET_SYSERR; 1227 return GNUNET_SYSERR;
1228 } 1228 }
1229 gcry_mpi_point_release (result); 1229 gcry_mpi_point_release(result);
1230 gcry_ctx_release (ctx); 1230 gcry_ctx_release(ctx);
1231 1231
1232 rsize = sizeof (xbuf); 1232 rsize = sizeof(xbuf);
1233 GNUNET_assert (! gcry_mpi_get_flag (result_x, GCRYMPI_FLAG_OPAQUE)); 1233 GNUNET_assert(!gcry_mpi_get_flag(result_x, GCRYMPI_FLAG_OPAQUE));
1234 /* result_x can be negative here, so we do not use 'GNUNET_CRYPTO_mpi_print_unsigned' 1234 /* result_x can be negative here, so we do not use 'GNUNET_CRYPTO_mpi_print_unsigned'
1235 as that does not include the sign bit; x should be a 255-bit 1235 as that does not include the sign bit; x should be a 255-bit
1236 value, so with the sign it should fit snugly into the 256-bit 1236 value, so with the sign it should fit snugly into the 256-bit
1237 xbuf */ 1237 xbuf */
1238 GNUNET_assert ( 1238 GNUNET_assert(
1239 0 == gcry_mpi_print (GCRYMPI_FMT_STD, xbuf, rsize, &rsize, result_x)); 1239 0 == gcry_mpi_print(GCRYMPI_FMT_STD, xbuf, rsize, &rsize, result_x));
1240 GNUNET_CRYPTO_hash (xbuf, rsize, key_material); 1240 GNUNET_CRYPTO_hash(xbuf, rsize, key_material);
1241 gcry_mpi_release (result_x); 1241 gcry_mpi_release(result_x);
1242 BENCHMARK_END (ecc_ecdh); 1242 BENCHMARK_END(ecc_ecdh);
1243 return GNUNET_OK; 1243 return GNUNET_OK;
1244} 1244}
1245 1245
@@ -1255,27 +1255,27 @@ GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1255 * @return h value 1255 * @return h value
1256 */ 1256 */
1257static gcry_mpi_t 1257static gcry_mpi_t
1258derive_h (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, 1258derive_h(const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1259 const char *label, 1259 const char *label,
1260 const char *context) 1260 const char *context)
1261{ 1261{
1262 gcry_mpi_t h; 1262 gcry_mpi_t h;
1263 struct GNUNET_HashCode hc; 1263 struct GNUNET_HashCode hc;
1264 static const char *const salt = "key-derivation"; 1264 static const char *const salt = "key-derivation";
1265 1265
1266 GNUNET_CRYPTO_kdf (&hc, 1266 GNUNET_CRYPTO_kdf(&hc,
1267 sizeof (hc), 1267 sizeof(hc),
1268 salt, 1268 salt,
1269 strlen (salt), 1269 strlen(salt),
1270 pub, 1270 pub,
1271 sizeof (*pub), 1271 sizeof(*pub),
1272 label, 1272 label,
1273 strlen (label), 1273 strlen(label),
1274 context, 1274 context,
1275 strlen (context), 1275 strlen(context),
1276 NULL, 1276 NULL,
1277 0); 1277 0);
1278 GNUNET_CRYPTO_mpi_scan_unsigned (&h, (unsigned char *) &hc, sizeof (hc)); 1278 GNUNET_CRYPTO_mpi_scan_unsigned(&h, (unsigned char *)&hc, sizeof(hc));
1279 return h; 1279 return h;
1280} 1280}
1281 1281
@@ -1293,7 +1293,7 @@ derive_h (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1293 * @return derived private key 1293 * @return derived private key
1294 */ 1294 */
1295struct GNUNET_CRYPTO_EcdsaPrivateKey * 1295struct GNUNET_CRYPTO_EcdsaPrivateKey *
1296GNUNET_CRYPTO_ecdsa_private_key_derive ( 1296GNUNET_CRYPTO_ecdsa_private_key_derive(
1297 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, 1297 const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1298 const char *label, 1298 const char *label,
1299 const char *context) 1299 const char *context)
@@ -1306,22 +1306,22 @@ GNUNET_CRYPTO_ecdsa_private_key_derive (
1306 gcry_mpi_t n; 1306 gcry_mpi_t n;
1307 gcry_ctx_t ctx; 1307 gcry_ctx_t ctx;
1308 1308
1309 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE)); 1309 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, NULL, CURVE));
1310 1310
1311 n = gcry_mpi_ec_get_mpi ("n", ctx, 1); 1311 n = gcry_mpi_ec_get_mpi("n", ctx, 1);
1312 GNUNET_CRYPTO_ecdsa_key_get_public (priv, &pub); 1312 GNUNET_CRYPTO_ecdsa_key_get_public(priv, &pub);
1313 1313
1314 h = derive_h (&pub, label, context); 1314 h = derive_h(&pub, label, context);
1315 GNUNET_CRYPTO_mpi_scan_unsigned (&x, priv->d, sizeof (priv->d)); 1315 GNUNET_CRYPTO_mpi_scan_unsigned(&x, priv->d, sizeof(priv->d));
1316 d = gcry_mpi_new (256); 1316 d = gcry_mpi_new(256);
1317 gcry_mpi_mulm (d, h, x, n); 1317 gcry_mpi_mulm(d, h, x, n);
1318 gcry_mpi_release (h); 1318 gcry_mpi_release(h);
1319 gcry_mpi_release (x); 1319 gcry_mpi_release(x);
1320 gcry_mpi_release (n); 1320 gcry_mpi_release(n);
1321 gcry_ctx_release (ctx); 1321 gcry_ctx_release(ctx);
1322 ret = GNUNET_new (struct GNUNET_CRYPTO_EcdsaPrivateKey); 1322 ret = GNUNET_new(struct GNUNET_CRYPTO_EcdsaPrivateKey);
1323 GNUNET_CRYPTO_mpi_print_unsigned (ret->d, sizeof (ret->d), d); 1323 GNUNET_CRYPTO_mpi_print_unsigned(ret->d, sizeof(ret->d), d);
1324 gcry_mpi_release (d); 1324 gcry_mpi_release(d);
1325 return ret; 1325 return ret;
1326} 1326}
1327 1327
@@ -1337,7 +1337,7 @@ GNUNET_CRYPTO_ecdsa_private_key_derive (
1337 * @param result where to write the derived public key 1337 * @param result where to write the derived public key
1338 */ 1338 */
1339void 1339void
1340GNUNET_CRYPTO_ecdsa_public_key_derive ( 1340GNUNET_CRYPTO_ecdsa_public_key_derive(
1341 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, 1341 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1342 const char *label, 1342 const char *label,
1343 const char *context, 1343 const char *context,
@@ -1351,39 +1351,39 @@ GNUNET_CRYPTO_ecdsa_public_key_derive (
1351 gcry_mpi_point_t q; 1351 gcry_mpi_point_t q;
1352 gcry_mpi_point_t v; 1352 gcry_mpi_point_t v;
1353 1353
1354 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE)); 1354 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, NULL, CURVE));
1355 1355
1356 /* obtain point 'q' from original public key. The provided 'q' is 1356 /* obtain point 'q' from original public key. The provided 'q' is
1357 compressed thus we first store it in the context and then get it 1357 compressed thus we first store it in the context and then get it
1358 back as a (decompresssed) point. */ 1358 back as a (decompresssed) point. */
1359 q_y = gcry_mpi_set_opaque_copy (NULL, pub->q_y, 8 * sizeof (pub->q_y)); 1359 q_y = gcry_mpi_set_opaque_copy(NULL, pub->q_y, 8 * sizeof(pub->q_y));
1360 GNUNET_assert (NULL != q_y); 1360 GNUNET_assert(NULL != q_y);
1361 GNUNET_assert (0 == gcry_mpi_ec_set_mpi ("q", q_y, ctx)); 1361 GNUNET_assert(0 == gcry_mpi_ec_set_mpi("q", q_y, ctx));
1362 gcry_mpi_release (q_y); 1362 gcry_mpi_release(q_y);
1363 q = gcry_mpi_ec_get_point ("q", ctx, 0); 1363 q = gcry_mpi_ec_get_point("q", ctx, 0);
1364 GNUNET_assert (q); 1364 GNUNET_assert(q);
1365 1365
1366 /* calculate h_mod_n = h % n */ 1366 /* calculate h_mod_n = h % n */
1367 h = derive_h (pub, label, context); 1367 h = derive_h(pub, label, context);
1368 n = gcry_mpi_ec_get_mpi ("n", ctx, 1); 1368 n = gcry_mpi_ec_get_mpi("n", ctx, 1);
1369 h_mod_n = gcry_mpi_new (256); 1369 h_mod_n = gcry_mpi_new(256);
1370 gcry_mpi_mod (h_mod_n, h, n); 1370 gcry_mpi_mod(h_mod_n, h, n);
1371 /* calculate v = h_mod_n * q */ 1371 /* calculate v = h_mod_n * q */
1372 v = gcry_mpi_point_new (0); 1372 v = gcry_mpi_point_new(0);
1373 gcry_mpi_ec_mul (v, h_mod_n, q, ctx); 1373 gcry_mpi_ec_mul(v, h_mod_n, q, ctx);
1374 gcry_mpi_release (h_mod_n); 1374 gcry_mpi_release(h_mod_n);
1375 gcry_mpi_release (h); 1375 gcry_mpi_release(h);
1376 gcry_mpi_release (n); 1376 gcry_mpi_release(n);
1377 gcry_mpi_point_release (q); 1377 gcry_mpi_point_release(q);
1378 1378
1379 /* convert point 'v' to public key that we return */ 1379 /* convert point 'v' to public key that we return */
1380 GNUNET_assert (0 == gcry_mpi_ec_set_point ("q", v, ctx)); 1380 GNUNET_assert(0 == gcry_mpi_ec_set_point("q", v, ctx));
1381 gcry_mpi_point_release (v); 1381 gcry_mpi_point_release(v);
1382 q_y = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0); 1382 q_y = gcry_mpi_ec_get_mpi("q@eddsa", ctx, 0);
1383 GNUNET_assert (q_y); 1383 GNUNET_assert(q_y);
1384 GNUNET_CRYPTO_mpi_print_unsigned (result->q_y, sizeof (result->q_y), q_y); 1384 GNUNET_CRYPTO_mpi_print_unsigned(result->q_y, sizeof(result->q_y), q_y);
1385 gcry_mpi_release (q_y); 1385 gcry_mpi_release(q_y);
1386 gcry_ctx_release (ctx); 1386 gcry_ctx_release(ctx);
1387} 1387}
1388 1388
1389 1389
@@ -1394,17 +1394,17 @@ GNUNET_CRYPTO_ecdsa_public_key_derive (
1394 * @param length number of bytes in @a buffer 1394 * @param length number of bytes in @a buffer
1395 */ 1395 */
1396static void 1396static void
1397reverse_buffer (unsigned char *buffer, size_t length) 1397reverse_buffer(unsigned char *buffer, size_t length)
1398{ 1398{
1399 unsigned char tmp; 1399 unsigned char tmp;
1400 size_t i; 1400 size_t i;
1401 1401
1402 for (i = 0; i < length / 2; i++) 1402 for (i = 0; i < length / 2; i++)
1403 { 1403 {
1404 tmp = buffer[i]; 1404 tmp = buffer[i];
1405 buffer[i] = buffer[length - 1 - i]; 1405 buffer[i] = buffer[length - 1 - i];
1406 buffer[length - 1 - i] = tmp; 1406 buffer[length - 1 - i] = tmp;
1407 } 1407 }
1408} 1408}
1409 1409
1410 1410
@@ -1416,7 +1416,7 @@ reverse_buffer (unsigned char *buffer, size_t length)
1416 * @return value used for the calculation in EdDSA 1416 * @return value used for the calculation in EdDSA
1417 */ 1417 */
1418static gcry_mpi_t 1418static gcry_mpi_t
1419eddsa_d_to_a (gcry_mpi_t d) 1419eddsa_d_to_a(gcry_mpi_t d)
1420{ 1420{
1421 unsigned char rawmpi[32]; /* 256-bit value */ 1421 unsigned char rawmpi[32]; /* 256-bit value */
1422 size_t rawmpilen; 1422 size_t rawmpilen;
@@ -1429,25 +1429,25 @@ eddsa_d_to_a (gcry_mpi_t d)
1429 1429
1430 /* Note that we clear DIGEST so we can use it as input to left pad 1430 /* Note that we clear DIGEST so we can use it as input to left pad
1431 the key with zeroes for hashing. */ 1431 the key with zeroes for hashing. */
1432 memset (digest, 0, sizeof digest); 1432 memset(digest, 0, sizeof digest);
1433 memset (hvec, 0, sizeof hvec); 1433 memset(hvec, 0, sizeof hvec);
1434 rawmpilen = sizeof (rawmpi); 1434 rawmpilen = sizeof(rawmpi);
1435 GNUNET_assert ( 1435 GNUNET_assert(
1436 0 == gcry_mpi_print (GCRYMPI_FMT_USG, rawmpi, rawmpilen, &rawmpilen, d)); 1436 0 == gcry_mpi_print(GCRYMPI_FMT_USG, rawmpi, rawmpilen, &rawmpilen, d));
1437 hvec[0].data = digest; 1437 hvec[0].data = digest;
1438 hvec[0].off = 0; 1438 hvec[0].off = 0;
1439 hvec[0].len = b > rawmpilen ? (b - rawmpilen) : 0; 1439 hvec[0].len = b > rawmpilen ? (b - rawmpilen) : 0;
1440 hvec[1].data = rawmpi; 1440 hvec[1].data = rawmpi;
1441 hvec[1].off = 0; 1441 hvec[1].off = 0;
1442 hvec[1].len = rawmpilen; 1442 hvec[1].len = rawmpilen;
1443 GNUNET_assert ( 1443 GNUNET_assert(
1444 0 == gcry_md_hash_buffers (GCRY_MD_SHA512, 0 /* flags */, digest, hvec, 2)); 1444 0 == gcry_md_hash_buffers(GCRY_MD_SHA512, 0 /* flags */, digest, hvec, 2));
1445 /* Compute the A value. */ 1445 /* Compute the A value. */
1446 reverse_buffer (digest, 32); /* Only the first half of the hash. */ 1446 reverse_buffer(digest, 32); /* Only the first half of the hash. */
1447 digest[0] = (digest[0] & 0x7f) | 0x40; 1447 digest[0] = (digest[0] & 0x7f) | 0x40;
1448 digest[31] &= 0xf8; 1448 digest[31] &= 0xf8;
1449 1449
1450 GNUNET_CRYPTO_mpi_scan_unsigned (&a, digest, 32); 1450 GNUNET_CRYPTO_mpi_scan_unsigned(&a, digest, 32);
1451 return a; 1451 return a;
1452} 1452}
1453 1453
@@ -1461,32 +1461,32 @@ eddsa_d_to_a (gcry_mpi_t d)
1461 * @return #GNUNET_OK on success 1461 * @return #GNUNET_OK on success
1462 */ 1462 */
1463static int 1463static int
1464point_to_hash (gcry_mpi_point_t result, 1464point_to_hash(gcry_mpi_point_t result,
1465 gcry_ctx_t ctx, 1465 gcry_ctx_t ctx,
1466 struct GNUNET_HashCode *key_material) 1466 struct GNUNET_HashCode *key_material)
1467{ 1467{
1468 gcry_mpi_t result_x; 1468 gcry_mpi_t result_x;
1469 unsigned char xbuf[256 / 8]; 1469 unsigned char xbuf[256 / 8];
1470 size_t rsize; 1470 size_t rsize;
1471 1471
1472 /* finally, convert point to string for hashing */ 1472 /* finally, convert point to string for hashing */
1473 result_x = gcry_mpi_new (256); 1473 result_x = gcry_mpi_new(256);
1474 if (gcry_mpi_ec_get_affine (result_x, NULL, result, ctx)) 1474 if (gcry_mpi_ec_get_affine(result_x, NULL, result, ctx))
1475 { 1475 {
1476 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0); 1476 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR, "get_affine failed", 0);
1477 return GNUNET_SYSERR; 1477 return GNUNET_SYSERR;
1478 } 1478 }
1479 1479
1480 rsize = sizeof (xbuf); 1480 rsize = sizeof(xbuf);
1481 GNUNET_assert (! gcry_mpi_get_flag (result_x, GCRYMPI_FLAG_OPAQUE)); 1481 GNUNET_assert(!gcry_mpi_get_flag(result_x, GCRYMPI_FLAG_OPAQUE));
1482 /* result_x can be negative here, so we do not use 'GNUNET_CRYPTO_mpi_print_unsigned' 1482 /* result_x can be negative here, so we do not use 'GNUNET_CRYPTO_mpi_print_unsigned'
1483 as that does not include the sign bit; x should be a 255-bit 1483 as that does not include the sign bit; x should be a 255-bit
1484 value, so with the sign it should fit snugly into the 256-bit 1484 value, so with the sign it should fit snugly into the 256-bit
1485 xbuf */ 1485 xbuf */
1486 GNUNET_assert ( 1486 GNUNET_assert(
1487 0 == gcry_mpi_print (GCRYMPI_FMT_STD, xbuf, rsize, &rsize, result_x)); 1487 0 == gcry_mpi_print(GCRYMPI_FMT_STD, xbuf, rsize, &rsize, result_x));
1488 GNUNET_CRYPTO_hash (xbuf, rsize, key_material); 1488 GNUNET_CRYPTO_hash(xbuf, rsize, key_material);
1489 gcry_mpi_release (result_x); 1489 gcry_mpi_release(result_x);
1490 return GNUNET_OK; 1490 return GNUNET_OK;
1491} 1491}
1492 1492
@@ -1502,9 +1502,9 @@ point_to_hash (gcry_mpi_point_t result,
1502 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 1502 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1503 */ 1503 */
1504int 1504int
1505GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv, 1505GNUNET_CRYPTO_eddsa_ecdh(const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1506 const struct GNUNET_CRYPTO_EcdhePublicKey *pub, 1506 const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1507 struct GNUNET_HashCode *key_material) 1507 struct GNUNET_HashCode *key_material)
1508{ 1508{
1509 gcry_mpi_point_t result; 1509 gcry_mpi_point_t result;
1510 gcry_mpi_point_t q; 1510 gcry_mpi_point_t q;
@@ -1514,36 +1514,36 @@ GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1514 gcry_sexp_t pub_sexpr; 1514 gcry_sexp_t pub_sexpr;
1515 int ret; 1515 int ret;
1516 1516
1517 BENCHMARK_START (eddsa_ecdh); 1517 BENCHMARK_START(eddsa_ecdh);
1518 1518
1519 /* first, extract the q = dP value from the public key */ 1519 /* first, extract the q = dP value from the public key */
1520 if (0 != gcry_sexp_build (&pub_sexpr, 1520 if (0 != gcry_sexp_build(&pub_sexpr,
1521 NULL, 1521 NULL,
1522 "(public-key(ecc(curve " CURVE ")(q %b)))", 1522 "(public-key(ecc(curve " CURVE ")(q %b)))",
1523 (int) sizeof (pub->q_y), 1523 (int)sizeof(pub->q_y),
1524 pub->q_y)) 1524 pub->q_y))
1525 return GNUNET_SYSERR; 1525 return GNUNET_SYSERR;
1526 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)); 1526 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, pub_sexpr, NULL));
1527 gcry_sexp_release (pub_sexpr); 1527 gcry_sexp_release(pub_sexpr);
1528 q = gcry_mpi_ec_get_point ("q", ctx, 0); 1528 q = gcry_mpi_ec_get_point("q", ctx, 0);
1529 1529
1530 /* second, extract the d value from our private key */ 1530 /* second, extract the d value from our private key */
1531 GNUNET_CRYPTO_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d)); 1531 GNUNET_CRYPTO_mpi_scan_unsigned(&d, priv->d, sizeof(priv->d));
1532 1532
1533 /* NOW, because this is EdDSA, HASH 'd' first! */ 1533 /* NOW, because this is EdDSA, HASH 'd' first! */
1534 a = eddsa_d_to_a (d); 1534 a = eddsa_d_to_a(d);
1535 gcry_mpi_release (d); 1535 gcry_mpi_release(d);
1536 1536
1537 /* then call the 'multiply' function, to compute the product */ 1537 /* then call the 'multiply' function, to compute the product */
1538 result = gcry_mpi_point_new (0); 1538 result = gcry_mpi_point_new(0);
1539 gcry_mpi_ec_mul (result, a, q, ctx); 1539 gcry_mpi_ec_mul(result, a, q, ctx);
1540 gcry_mpi_point_release (q); 1540 gcry_mpi_point_release(q);
1541 gcry_mpi_release (a); 1541 gcry_mpi_release(a);
1542 1542
1543 ret = point_to_hash (result, ctx, key_material); 1543 ret = point_to_hash(result, ctx, key_material);
1544 gcry_mpi_point_release (result); 1544 gcry_mpi_point_release(result);
1545 gcry_ctx_release (ctx); 1545 gcry_ctx_release(ctx);
1546 BENCHMARK_END (eddsa_ecdh); 1546 BENCHMARK_END(eddsa_ecdh);
1547 return ret; 1547 return ret;
1548} 1548}
1549 1549
@@ -1559,9 +1559,9 @@ GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1559 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 1559 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1560 */ 1560 */
1561int 1561int
1562GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv, 1562GNUNET_CRYPTO_ecdsa_ecdh(const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1563 const struct GNUNET_CRYPTO_EcdhePublicKey *pub, 1563 const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1564 struct GNUNET_HashCode *key_material) 1564 struct GNUNET_HashCode *key_material)
1565{ 1565{
1566 gcry_mpi_point_t result; 1566 gcry_mpi_point_t result;
1567 gcry_mpi_point_t q; 1567 gcry_mpi_point_t q;
@@ -1570,33 +1570,33 @@ GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1570 gcry_sexp_t pub_sexpr; 1570 gcry_sexp_t pub_sexpr;
1571 int ret; 1571 int ret;
1572 1572
1573 BENCHMARK_START (ecdsa_ecdh); 1573 BENCHMARK_START(ecdsa_ecdh);
1574 1574
1575 /* first, extract the q = dP value from the public key */ 1575 /* first, extract the q = dP value from the public key */
1576 if (0 != gcry_sexp_build (&pub_sexpr, 1576 if (0 != gcry_sexp_build(&pub_sexpr,
1577 NULL, 1577 NULL,
1578 "(public-key(ecc(curve " CURVE ")(q %b)))", 1578 "(public-key(ecc(curve " CURVE ")(q %b)))",
1579 (int) sizeof (pub->q_y), 1579 (int)sizeof(pub->q_y),
1580 pub->q_y)) 1580 pub->q_y))
1581 return GNUNET_SYSERR; 1581 return GNUNET_SYSERR;
1582 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)); 1582 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, pub_sexpr, NULL));
1583 gcry_sexp_release (pub_sexpr); 1583 gcry_sexp_release(pub_sexpr);
1584 q = gcry_mpi_ec_get_point ("q", ctx, 0); 1584 q = gcry_mpi_ec_get_point("q", ctx, 0);
1585 1585
1586 /* second, extract the d value from our private key */ 1586 /* second, extract the d value from our private key */
1587 GNUNET_CRYPTO_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d)); 1587 GNUNET_CRYPTO_mpi_scan_unsigned(&d, priv->d, sizeof(priv->d));
1588 1588
1589 /* then call the 'multiply' function, to compute the product */ 1589 /* then call the 'multiply' function, to compute the product */
1590 result = gcry_mpi_point_new (0); 1590 result = gcry_mpi_point_new(0);
1591 gcry_mpi_ec_mul (result, d, q, ctx); 1591 gcry_mpi_ec_mul(result, d, q, ctx);
1592 gcry_mpi_point_release (q); 1592 gcry_mpi_point_release(q);
1593 gcry_mpi_release (d); 1593 gcry_mpi_release(d);
1594 1594
1595 /* finally, convert point to string for hashing */ 1595 /* finally, convert point to string for hashing */
1596 ret = point_to_hash (result, ctx, key_material); 1596 ret = point_to_hash(result, ctx, key_material);
1597 gcry_mpi_point_release (result); 1597 gcry_mpi_point_release(result);
1598 gcry_ctx_release (ctx); 1598 gcry_ctx_release(ctx);
1599 BENCHMARK_END (ecdsa_ecdh); 1599 BENCHMARK_END(ecdsa_ecdh);
1600 return ret; 1600 return ret;
1601} 1601}
1602 1602
@@ -1612,9 +1612,9 @@ GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1612 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 1612 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1613 */ 1613 */
1614int 1614int
1615GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, 1615GNUNET_CRYPTO_ecdh_eddsa(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1616 const struct GNUNET_CRYPTO_EddsaPublicKey *pub, 1616 const struct GNUNET_CRYPTO_EddsaPublicKey *pub,
1617 struct GNUNET_HashCode *key_material) 1617 struct GNUNET_HashCode *key_material)
1618{ 1618{
1619 gcry_mpi_point_t result; 1619 gcry_mpi_point_t result;
1620 gcry_mpi_point_t q; 1620 gcry_mpi_point_t q;
@@ -1623,33 +1623,33 @@ GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1623 gcry_sexp_t pub_sexpr; 1623 gcry_sexp_t pub_sexpr;
1624 int ret; 1624 int ret;
1625 1625
1626 BENCHMARK_START (ecdh_eddsa); 1626 BENCHMARK_START(ecdh_eddsa);
1627 1627
1628 /* first, extract the q = dP value from the public key */ 1628 /* first, extract the q = dP value from the public key */
1629 if (0 != gcry_sexp_build (&pub_sexpr, 1629 if (0 != gcry_sexp_build(&pub_sexpr,
1630 NULL, 1630 NULL,
1631 "(public-key(ecc(curve " CURVE ")(q %b)))", 1631 "(public-key(ecc(curve " CURVE ")(q %b)))",
1632 (int) sizeof (pub->q_y), 1632 (int)sizeof(pub->q_y),
1633 pub->q_y)) 1633 pub->q_y))
1634 return GNUNET_SYSERR; 1634 return GNUNET_SYSERR;
1635 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)); 1635 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, pub_sexpr, NULL));
1636 gcry_sexp_release (pub_sexpr); 1636 gcry_sexp_release(pub_sexpr);
1637 q = gcry_mpi_ec_get_point ("q", ctx, 0); 1637 q = gcry_mpi_ec_get_point("q", ctx, 0);
1638 1638
1639 /* second, extract the d value from our private key */ 1639 /* second, extract the d value from our private key */
1640 GNUNET_CRYPTO_mpi_scan_unsigned (&d, priv->d, sizeof (priv->d)); 1640 GNUNET_CRYPTO_mpi_scan_unsigned(&d, priv->d, sizeof(priv->d));
1641 1641
1642 /* then call the 'multiply' function, to compute the product */ 1642 /* then call the 'multiply' function, to compute the product */
1643 result = gcry_mpi_point_new (0); 1643 result = gcry_mpi_point_new(0);
1644 gcry_mpi_ec_mul (result, d, q, ctx); 1644 gcry_mpi_ec_mul(result, d, q, ctx);
1645 gcry_mpi_point_release (q); 1645 gcry_mpi_point_release(q);
1646 gcry_mpi_release (d); 1646 gcry_mpi_release(d);
1647 1647
1648 /* finally, convert point to string for hashing */ 1648 /* finally, convert point to string for hashing */
1649 ret = point_to_hash (result, ctx, key_material); 1649 ret = point_to_hash(result, ctx, key_material);
1650 gcry_mpi_point_release (result); 1650 gcry_mpi_point_release(result);
1651 gcry_ctx_release (ctx); 1651 gcry_ctx_release(ctx);
1652 BENCHMARK_END (ecdh_eddsa); 1652 BENCHMARK_END(ecdh_eddsa);
1653 return ret; 1653 return ret;
1654} 1654}
1655 1655
@@ -1664,14 +1664,14 @@ GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1664 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 1664 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1665 */ 1665 */
1666int 1666int
1667GNUNET_CRYPTO_ecdh_ecdsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv, 1667GNUNET_CRYPTO_ecdh_ecdsa(const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1668 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub, 1668 const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1669 struct GNUNET_HashCode *key_material) 1669 struct GNUNET_HashCode *key_material)
1670{ 1670{
1671 return GNUNET_CRYPTO_ecdh_eddsa (priv, 1671 return GNUNET_CRYPTO_ecdh_eddsa(priv,
1672 (const struct GNUNET_CRYPTO_EddsaPublicKey *) 1672 (const struct GNUNET_CRYPTO_EddsaPublicKey *)
1673 pub, 1673 pub,
1674 key_material); 1674 key_material);
1675} 1675}
1676 1676
1677/* end of crypto_ecc.c */ 1677/* end of crypto_ecc.c */
diff --git a/src/util/crypto_ecc_dlog.c b/src/util/crypto_ecc_dlog.c
index 07777e377..8b4344b25 100644
--- a/src/util/crypto_ecc_dlog.c
+++ b/src/util/crypto_ecc_dlog.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_ecc_dlog.c 22 * @file util/crypto_ecc_dlog.c
@@ -44,27 +44,26 @@
44 * 44 *
45 */ 45 */
46static void 46static void
47extract_pk (gcry_mpi_point_t pt, 47extract_pk(gcry_mpi_point_t pt,
48 gcry_ctx_t ctx, 48 gcry_ctx_t ctx,
49 struct GNUNET_PeerIdentity *pid) 49 struct GNUNET_PeerIdentity *pid)
50{ 50{
51 gcry_mpi_t q_y; 51 gcry_mpi_t q_y;
52 52
53 GNUNET_assert (0 == gcry_mpi_ec_set_point ("q", pt, ctx)); 53 GNUNET_assert(0 == gcry_mpi_ec_set_point("q", pt, ctx));
54 q_y = gcry_mpi_ec_get_mpi ("q@eddsa", ctx, 0); 54 q_y = gcry_mpi_ec_get_mpi("q@eddsa", ctx, 0);
55 GNUNET_assert (q_y); 55 GNUNET_assert(q_y);
56 GNUNET_CRYPTO_mpi_print_unsigned (pid->public_key.q_y, 56 GNUNET_CRYPTO_mpi_print_unsigned(pid->public_key.q_y,
57 sizeof (pid->public_key.q_y), 57 sizeof(pid->public_key.q_y),
58 q_y); 58 q_y);
59 gcry_mpi_release (q_y); 59 gcry_mpi_release(q_y);
60} 60}
61 61
62 62
63/** 63/**
64 * Internal structure used to cache pre-calculated values for DLOG calculation. 64 * Internal structure used to cache pre-calculated values for DLOG calculation.
65 */ 65 */
66struct GNUNET_CRYPTO_EccDlogContext 66struct GNUNET_CRYPTO_EccDlogContext {
67{
68 /** 67 /**
69 * Maximum absolute value the calculation supports. 68 * Maximum absolute value the calculation supports.
70 */ 69 */
@@ -87,7 +86,6 @@ struct GNUNET_CRYPTO_EccDlogContext
87 * Context to use for operations on the elliptic curve. 86 * Context to use for operations on the elliptic curve.
88 */ 87 */
89 gcry_ctx_t ctx; 88 gcry_ctx_t ctx;
90
91}; 89};
92 90
93 91
@@ -99,19 +97,19 @@ struct GNUNET_CRYPTO_EccDlogContext
99 * @param[out] bin binary point representation 97 * @param[out] bin binary point representation
100 */ 98 */
101void 99void
102GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc, 100GNUNET_CRYPTO_ecc_point_to_bin(struct GNUNET_CRYPTO_EccDlogContext *edc,
103 gcry_mpi_point_t point, 101 gcry_mpi_point_t point,
104 struct GNUNET_CRYPTO_EccPoint *bin) 102 struct GNUNET_CRYPTO_EccPoint *bin)
105{ 103{
106 gcry_mpi_t q_y; 104 gcry_mpi_t q_y;
107 105
108 GNUNET_assert (0 == gcry_mpi_ec_set_point ("q", point, edc->ctx)); 106 GNUNET_assert(0 == gcry_mpi_ec_set_point("q", point, edc->ctx));
109 q_y = gcry_mpi_ec_get_mpi ("q@eddsa", edc->ctx, 0); 107 q_y = gcry_mpi_ec_get_mpi("q@eddsa", edc->ctx, 0);
110 GNUNET_assert (q_y); 108 GNUNET_assert(q_y);
111 GNUNET_CRYPTO_mpi_print_unsigned (bin->q_y, 109 GNUNET_CRYPTO_mpi_print_unsigned(bin->q_y,
112 sizeof (bin->q_y), 110 sizeof(bin->q_y),
113 q_y); 111 q_y);
114 gcry_mpi_release (q_y); 112 gcry_mpi_release(q_y);
115} 113}
116 114
117 115
@@ -123,26 +121,26 @@ GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc,
123 * @return computational representation 121 * @return computational representation
124 */ 122 */
125gcry_mpi_point_t 123gcry_mpi_point_t
126GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc, 124GNUNET_CRYPTO_ecc_bin_to_point(struct GNUNET_CRYPTO_EccDlogContext *edc,
127 const struct GNUNET_CRYPTO_EccPoint *bin) 125 const struct GNUNET_CRYPTO_EccPoint *bin)
128{ 126{
129 gcry_sexp_t pub_sexpr; 127 gcry_sexp_t pub_sexpr;
130 gcry_ctx_t ctx; 128 gcry_ctx_t ctx;
131 gcry_mpi_point_t q; 129 gcry_mpi_point_t q;
132 130
133 (void) edc; 131 (void)edc;
134 if (0 != gcry_sexp_build (&pub_sexpr, NULL, 132 if (0 != gcry_sexp_build(&pub_sexpr, NULL,
135 "(public-key(ecc(curve " CURVE ")(q %b)))", 133 "(public-key(ecc(curve " CURVE ")(q %b)))",
136 (int) sizeof (bin->q_y), 134 (int)sizeof(bin->q_y),
137 bin->q_y)) 135 bin->q_y))
138 { 136 {
139 GNUNET_break (0); 137 GNUNET_break(0);
140 return NULL; 138 return NULL;
141 } 139 }
142 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, pub_sexpr, NULL)); 140 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, pub_sexpr, NULL));
143 gcry_sexp_release (pub_sexpr); 141 gcry_sexp_release(pub_sexpr);
144 q = gcry_mpi_ec_get_point ("q", ctx, 0); 142 q = gcry_mpi_ec_get_point("q", ctx, 0);
145 gcry_ctx_release (ctx); 143 gcry_ctx_release(ctx);
146 return q; 144 return q;
147} 145}
148 146
@@ -155,11 +153,11 @@ GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc,
155 * @return NULL on error 153 * @return NULL on error
156 */ 154 */
157struct GNUNET_CRYPTO_EccDlogContext * 155struct GNUNET_CRYPTO_EccDlogContext *
158GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max, 156GNUNET_CRYPTO_ecc_dlog_prepare(unsigned int max,
159 unsigned int mem) 157 unsigned int mem)
160{ 158{
161 struct GNUNET_CRYPTO_EccDlogContext *edc; 159 struct GNUNET_CRYPTO_EccDlogContext *edc;
162 unsigned int K = ((max + (mem-1)) / mem); 160 unsigned int K = ((max + (mem - 1)) / mem);
163 gcry_mpi_point_t g; 161 gcry_mpi_point_t g;
164 struct GNUNET_PeerIdentity key; 162 struct GNUNET_PeerIdentity key;
165 gcry_mpi_point_t gKi; 163 gcry_mpi_point_t gKi;
@@ -167,50 +165,50 @@ GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max,
167 gcry_mpi_t n; 165 gcry_mpi_t n;
168 unsigned int i; 166 unsigned int i;
169 167
170 GNUNET_assert (max < INT32_MAX); 168 GNUNET_assert(max < INT32_MAX);
171 edc = GNUNET_new (struct GNUNET_CRYPTO_EccDlogContext); 169 edc = GNUNET_new(struct GNUNET_CRYPTO_EccDlogContext);
172 edc->max = max; 170 edc->max = max;
173 edc->mem = mem; 171 edc->mem = mem;
174 172
175 edc->map = GNUNET_CONTAINER_multipeermap_create (mem * 2, 173 edc->map = GNUNET_CONTAINER_multipeermap_create(mem * 2,
176 GNUNET_NO); 174 GNUNET_NO);
177 175
178 GNUNET_assert (0 == gcry_mpi_ec_new (&edc->ctx, 176 GNUNET_assert(0 == gcry_mpi_ec_new(&edc->ctx,
179 NULL, 177 NULL,
180 CURVE)); 178 CURVE));
181 g = gcry_mpi_ec_get_point ("g", edc->ctx, 0); 179 g = gcry_mpi_ec_get_point("g", edc->ctx, 0);
182 GNUNET_assert (NULL != g); 180 GNUNET_assert(NULL != g);
183 fact = gcry_mpi_new (0); 181 fact = gcry_mpi_new(0);
184 gKi = gcry_mpi_point_new (0); 182 gKi = gcry_mpi_point_new(0);
185 for (i=0;i<=mem;i++) 183 for (i = 0; i <= mem; i++)
186 { 184 {
187 gcry_mpi_set_ui (fact, i * K); 185 gcry_mpi_set_ui(fact, i * K);
188 gcry_mpi_ec_mul (gKi, fact, g, edc->ctx); 186 gcry_mpi_ec_mul(gKi, fact, g, edc->ctx);
189 extract_pk (gKi, edc->ctx, &key); 187 extract_pk(gKi, edc->ctx, &key);
190 GNUNET_assert (GNUNET_OK == 188 GNUNET_assert(GNUNET_OK ==
191 GNUNET_CONTAINER_multipeermap_put (edc->map, 189 GNUNET_CONTAINER_multipeermap_put(edc->map,
192 &key, 190 &key,
193 (void*) (long) i + max, 191 (void*)(long)i + max,
194 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); 192 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
195 } 193 }
196 /* negative values */ 194 /* negative values */
197 n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1); 195 n = gcry_mpi_ec_get_mpi("n", edc->ctx, 1);
198 for (i=1;i<mem;i++) 196 for (i = 1; i < mem; i++)
199 { 197 {
200 gcry_mpi_set_ui (fact, i * K); 198 gcry_mpi_set_ui(fact, i * K);
201 gcry_mpi_sub (fact, n, fact); 199 gcry_mpi_sub(fact, n, fact);
202 gcry_mpi_ec_mul (gKi, fact, g, edc->ctx); 200 gcry_mpi_ec_mul(gKi, fact, g, edc->ctx);
203 extract_pk (gKi, edc->ctx, &key); 201 extract_pk(gKi, edc->ctx, &key);
204 GNUNET_assert (GNUNET_OK == 202 GNUNET_assert(GNUNET_OK ==
205 GNUNET_CONTAINER_multipeermap_put (edc->map, 203 GNUNET_CONTAINER_multipeermap_put(edc->map,
206 &key, 204 &key,
207 (void*) (long) max - i, 205 (void*)(long)max - i,
208 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); 206 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
209 } 207 }
210 gcry_mpi_release (fact); 208 gcry_mpi_release(fact);
211 gcry_mpi_release (n); 209 gcry_mpi_release(n);
212 gcry_mpi_point_release (gKi); 210 gcry_mpi_point_release(gKi);
213 gcry_mpi_point_release (g); 211 gcry_mpi_point_release(g);
214 return edc; 212 return edc;
215} 213}
216 214
@@ -223,10 +221,10 @@ GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max,
223 * @return INT_MAX if dlog failed, otherwise the factor 221 * @return INT_MAX if dlog failed, otherwise the factor
224 */ 222 */
225int 223int
226GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc, 224GNUNET_CRYPTO_ecc_dlog(struct GNUNET_CRYPTO_EccDlogContext *edc,
227 gcry_mpi_point_t input) 225 gcry_mpi_point_t input)
228{ 226{
229 unsigned int K = ((edc->max + (edc->mem-1)) / edc->mem); 227 unsigned int K = ((edc->max + (edc->mem - 1)) / edc->mem);
230 gcry_mpi_point_t g; 228 gcry_mpi_point_t g;
231 struct GNUNET_PeerIdentity key; 229 struct GNUNET_PeerIdentity key;
232 gcry_mpi_point_t q; 230 gcry_mpi_point_t q;
@@ -234,36 +232,36 @@ GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc,
234 int res; 232 int res;
235 void *retp; 233 void *retp;
236 234
237 g = gcry_mpi_ec_get_point ("g", edc->ctx, 0); 235 g = gcry_mpi_ec_get_point("g", edc->ctx, 0);
238 GNUNET_assert (NULL != g); 236 GNUNET_assert(NULL != g);
239 q = gcry_mpi_point_new (0); 237 q = gcry_mpi_point_new(0);
240 238
241 res = INT_MAX; 239 res = INT_MAX;
242 for (i=0;i<=edc->max/edc->mem;i++) 240 for (i = 0; i <= edc->max / edc->mem; i++)
243 {
244 if (0 == i)
245 extract_pk (input, edc->ctx, &key);
246 else
247 extract_pk (q, edc->ctx, &key);
248 retp = GNUNET_CONTAINER_multipeermap_get (edc->map,
249 &key);
250 if (NULL != retp)
251 { 241 {
252 res = (((long) retp) - edc->max) * K - i; 242 if (0 == i)
253 /* we continue the loop here to make the implementation 243 extract_pk(input, edc->ctx, &key);
254 "constant-time". If we do not care about this, we could just 244 else
255 'break' here and do fewer operations... */ 245 extract_pk(q, edc->ctx, &key);
246 retp = GNUNET_CONTAINER_multipeermap_get(edc->map,
247 &key);
248 if (NULL != retp)
249 {
250 res = (((long)retp) - edc->max) * K - i;
251 /* we continue the loop here to make the implementation
252 "constant-time". If we do not care about this, we could just
253 'break' here and do fewer operations... */
254 }
255 if (i == edc->max / edc->mem)
256 break;
257 /* q = q + g */
258 if (0 == i)
259 gcry_mpi_ec_add(q, input, g, edc->ctx);
260 else
261 gcry_mpi_ec_add(q, q, g, edc->ctx);
256 } 262 }
257 if (i == edc->max/edc->mem) 263 gcry_mpi_point_release(g);
258 break; 264 gcry_mpi_point_release(q);
259 /* q = q + g */
260 if (0 == i)
261 gcry_mpi_ec_add (q, input, g, edc->ctx);
262 else
263 gcry_mpi_ec_add (q, q, g, edc->ctx);
264 }
265 gcry_mpi_point_release (g);
266 gcry_mpi_point_release (q);
267 265
268 return res; 266 return res;
269} 267}
@@ -276,29 +274,30 @@ GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc,
276 * @return random value mod n. 274 * @return random value mod n.
277 */ 275 */
278gcry_mpi_t 276gcry_mpi_t
279GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc) 277GNUNET_CRYPTO_ecc_random_mod_n(struct GNUNET_CRYPTO_EccDlogContext *edc)
280{ 278{
281 gcry_mpi_t n; 279 gcry_mpi_t n;
282 unsigned int highbit; 280 unsigned int highbit;
283 gcry_mpi_t r; 281 gcry_mpi_t r;
284 282
285 n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1); 283 n = gcry_mpi_ec_get_mpi("n", edc->ctx, 1);
286 284
287 /* check public key for number of bits, bail out if key is all zeros */ 285 /* check public key for number of bits, bail out if key is all zeros */
288 highbit = 256; /* Curve25519 */ 286 highbit = 256; /* Curve25519 */
289 while ( (! gcry_mpi_test_bit (n, highbit)) && 287 while ((!gcry_mpi_test_bit(n, highbit)) &&
290 (0 != highbit) ) 288 (0 != highbit))
291 highbit--; 289 highbit--;
292 GNUNET_assert (0 != highbit); 290 GNUNET_assert(0 != highbit);
293 /* generate fact < n (without bias) */ 291 /* generate fact < n (without bias) */
294 GNUNET_assert (NULL != (r = gcry_mpi_new (0))); 292 GNUNET_assert(NULL != (r = gcry_mpi_new(0)));
295 do { 293 do
296 gcry_mpi_randomize (r, 294 {
297 highbit + 1, 295 gcry_mpi_randomize(r,
298 GCRY_STRONG_RANDOM); 296 highbit + 1,
299 } 297 GCRY_STRONG_RANDOM);
300 while (gcry_mpi_cmp (r, n) >= 0); 298 }
301 gcry_mpi_release (n); 299 while (gcry_mpi_cmp(r, n) >= 0);
300 gcry_mpi_release(n);
302 return r; 301 return r;
303} 302}
304 303
@@ -309,11 +308,11 @@ GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc)
309 * @param edc dlog context 308 * @param edc dlog context
310 */ 309 */
311void 310void
312GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *edc) 311GNUNET_CRYPTO_ecc_dlog_release(struct GNUNET_CRYPTO_EccDlogContext *edc)
313{ 312{
314 gcry_ctx_release (edc->ctx); 313 gcry_ctx_release(edc->ctx);
315 GNUNET_CONTAINER_multipeermap_destroy (edc->map); 314 GNUNET_CONTAINER_multipeermap_destroy(edc->map);
316 GNUNET_free (edc); 315 GNUNET_free(edc);
317} 316}
318 317
319 318
@@ -331,32 +330,32 @@ GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *edc)
331 * must be freed using #GNUNET_CRYPTO_ecc_free() 330 * must be freed using #GNUNET_CRYPTO_ecc_free()
332 */ 331 */
333gcry_mpi_point_t 332gcry_mpi_point_t
334GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc, 333GNUNET_CRYPTO_ecc_dexp(struct GNUNET_CRYPTO_EccDlogContext *edc,
335 int val) 334 int val)
336{ 335{
337 gcry_mpi_t fact; 336 gcry_mpi_t fact;
338 gcry_mpi_t n; 337 gcry_mpi_t n;
339 gcry_mpi_point_t g; 338 gcry_mpi_point_t g;
340 gcry_mpi_point_t r; 339 gcry_mpi_point_t r;
341 340
342 g = gcry_mpi_ec_get_point ("g", edc->ctx, 0); 341 g = gcry_mpi_ec_get_point("g", edc->ctx, 0);
343 GNUNET_assert (NULL != g); 342 GNUNET_assert(NULL != g);
344 fact = gcry_mpi_new (0); 343 fact = gcry_mpi_new(0);
345 if (val < 0) 344 if (val < 0)
346 { 345 {
347 n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1); 346 n = gcry_mpi_ec_get_mpi("n", edc->ctx, 1);
348 gcry_mpi_set_ui (fact, - val); 347 gcry_mpi_set_ui(fact, -val);
349 gcry_mpi_sub (fact, n, fact); 348 gcry_mpi_sub(fact, n, fact);
350 gcry_mpi_release (n); 349 gcry_mpi_release(n);
351 } 350 }
352 else 351 else
353 { 352 {
354 gcry_mpi_set_ui (fact, val); 353 gcry_mpi_set_ui(fact, val);
355 } 354 }
356 r = gcry_mpi_point_new (0); 355 r = gcry_mpi_point_new(0);
357 gcry_mpi_ec_mul (r, fact, g, edc->ctx); 356 gcry_mpi_ec_mul(r, fact, g, edc->ctx);
358 gcry_mpi_release (fact); 357 gcry_mpi_release(fact);
359 gcry_mpi_point_release (g); 358 gcry_mpi_point_release(g);
360 return r; 359 return r;
361} 360}
362 361
@@ -371,17 +370,17 @@ GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc,
371 * must be freed using #GNUNET_CRYPTO_ecc_free() 370 * must be freed using #GNUNET_CRYPTO_ecc_free()
372 */ 371 */
373gcry_mpi_point_t 372gcry_mpi_point_t
374GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, 373GNUNET_CRYPTO_ecc_dexp_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc,
375 gcry_mpi_t val) 374 gcry_mpi_t val)
376{ 375{
377 gcry_mpi_point_t g; 376 gcry_mpi_point_t g;
378 gcry_mpi_point_t r; 377 gcry_mpi_point_t r;
379 378
380 g = gcry_mpi_ec_get_point ("g", edc->ctx, 0); 379 g = gcry_mpi_ec_get_point("g", edc->ctx, 0);
381 GNUNET_assert (NULL != g); 380 GNUNET_assert(NULL != g);
382 r = gcry_mpi_point_new (0); 381 r = gcry_mpi_point_new(0);
383 gcry_mpi_ec_mul (r, val, g, edc->ctx); 382 gcry_mpi_ec_mul(r, val, g, edc->ctx);
384 gcry_mpi_point_release (g); 383 gcry_mpi_point_release(g);
385 return r; 384 return r;
386} 385}
387 386
@@ -395,14 +394,14 @@ GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
395 * @return @a a + @a b, must be freed using #GNUNET_CRYPTO_ecc_free() 394 * @return @a a + @a b, must be freed using #GNUNET_CRYPTO_ecc_free()
396 */ 395 */
397gcry_mpi_point_t 396gcry_mpi_point_t
398GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc, 397GNUNET_CRYPTO_ecc_add(struct GNUNET_CRYPTO_EccDlogContext *edc,
399 gcry_mpi_point_t a, 398 gcry_mpi_point_t a,
400 gcry_mpi_point_t b) 399 gcry_mpi_point_t b)
401{ 400{
402 gcry_mpi_point_t r; 401 gcry_mpi_point_t r;
403 402
404 r = gcry_mpi_point_new (0); 403 r = gcry_mpi_point_new(0);
405 gcry_mpi_ec_add (r, a, b, edc->ctx); 404 gcry_mpi_ec_add(r, a, b, edc->ctx);
406 return r; 405 return r;
407} 406}
408 407
@@ -417,14 +416,14 @@ GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc,
417 * must be freed using #GNUNET_CRYPTO_ecc_free() 416 * must be freed using #GNUNET_CRYPTO_ecc_free()
418 */ 417 */
419gcry_mpi_point_t 418gcry_mpi_point_t
420GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, 419GNUNET_CRYPTO_ecc_pmul_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc,
421 gcry_mpi_point_t p, 420 gcry_mpi_point_t p,
422 gcry_mpi_t val) 421 gcry_mpi_t val)
423{ 422{
424 gcry_mpi_point_t r; 423 gcry_mpi_point_t r;
425 424
426 r = gcry_mpi_point_new (0); 425 r = gcry_mpi_point_new(0);
427 gcry_mpi_ec_mul (r, val, p, edc->ctx); 426 gcry_mpi_ec_mul(r, val, p, edc->ctx);
428 return r; 427 return r;
429} 428}
430 429
@@ -439,31 +438,31 @@ GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
439 * @param[out] r_inv set to the additive inverse of @a r 438 * @param[out] r_inv set to the additive inverse of @a r
440 */ 439 */
441void 440void
442GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc, 441GNUNET_CRYPTO_ecc_rnd(struct GNUNET_CRYPTO_EccDlogContext *edc,
443 gcry_mpi_point_t *r, 442 gcry_mpi_point_t *r,
444 gcry_mpi_point_t *r_inv) 443 gcry_mpi_point_t *r_inv)
445{ 444{
446 gcry_mpi_t fact; 445 gcry_mpi_t fact;
447 gcry_mpi_t n; 446 gcry_mpi_t n;
448 gcry_mpi_point_t g; 447 gcry_mpi_point_t g;
449 448
450 fact = GNUNET_CRYPTO_ecc_random_mod_n (edc); 449 fact = GNUNET_CRYPTO_ecc_random_mod_n(edc);
451 450
452 /* calculate 'r' */ 451 /* calculate 'r' */
453 g = gcry_mpi_ec_get_point ("g", edc->ctx, 0); 452 g = gcry_mpi_ec_get_point("g", edc->ctx, 0);
454 GNUNET_assert (NULL != g); 453 GNUNET_assert(NULL != g);
455 *r = gcry_mpi_point_new (0); 454 *r = gcry_mpi_point_new(0);
456 gcry_mpi_ec_mul (*r, fact, g, edc->ctx); 455 gcry_mpi_ec_mul(*r, fact, g, edc->ctx);
457 456
458 /* calculate 'r_inv' */ 457 /* calculate 'r_inv' */
459 n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1); 458 n = gcry_mpi_ec_get_mpi("n", edc->ctx, 1);
460 gcry_mpi_sub (fact, n, fact); /* fact = n - fact = - fact */ 459 gcry_mpi_sub(fact, n, fact); /* fact = n - fact = - fact */
461 *r_inv = gcry_mpi_point_new (0); 460 *r_inv = gcry_mpi_point_new(0);
462 gcry_mpi_ec_mul (*r_inv, fact, g, edc->ctx); 461 gcry_mpi_ec_mul(*r_inv, fact, g, edc->ctx);
463 462
464 gcry_mpi_release (n); 463 gcry_mpi_release(n);
465 gcry_mpi_release (fact); 464 gcry_mpi_release(fact);
466 gcry_mpi_point_release (g); 465 gcry_mpi_point_release(g);
467} 466}
468 467
469 468
@@ -476,17 +475,17 @@ GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc,
476 * @param[out] r_inv set to the multiplicative inverse of @a r 475 * @param[out] r_inv set to the multiplicative inverse of @a r
477 */ 476 */
478void 477void
479GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc, 478GNUNET_CRYPTO_ecc_rnd_mpi(struct GNUNET_CRYPTO_EccDlogContext *edc,
480 gcry_mpi_t *r, 479 gcry_mpi_t *r,
481 gcry_mpi_t *r_inv) 480 gcry_mpi_t *r_inv)
482{ 481{
483 gcry_mpi_t n; 482 gcry_mpi_t n;
484 483
485 *r = GNUNET_CRYPTO_ecc_random_mod_n (edc); 484 *r = GNUNET_CRYPTO_ecc_random_mod_n(edc);
486 /* r_inv = n - r = - r */ 485 /* r_inv = n - r = - r */
487 *r_inv = gcry_mpi_new (0); 486 *r_inv = gcry_mpi_new(0);
488 n = gcry_mpi_ec_get_mpi ("n", edc->ctx, 1); 487 n = gcry_mpi_ec_get_mpi("n", edc->ctx, 1);
489 gcry_mpi_sub (*r_inv, n, *r); 488 gcry_mpi_sub(*r_inv, n, *r);
490} 489}
491 490
492 491
@@ -496,9 +495,9 @@ GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
496 * @param p point to free 495 * @param p point to free
497 */ 496 */
498void 497void
499GNUNET_CRYPTO_ecc_free (gcry_mpi_point_t p) 498GNUNET_CRYPTO_ecc_free(gcry_mpi_point_t p)
500{ 499{
501 gcry_mpi_point_release (p); 500 gcry_mpi_point_release(p);
502} 501}
503 502
504 503
diff --git a/src/util/crypto_ecc_setup.c b/src/util/crypto_ecc_setup.c
index c556d805d..af42df613 100644
--- a/src/util/crypto_ecc_setup.c
+++ b/src/util/crypto_ecc_setup.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_ecc_setup.c 22 * @file util/crypto_ecc_setup.c
@@ -27,13 +27,13 @@
27#include <gcrypt.h> 27#include <gcrypt.h>
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define LOG(kind, ...) GNUNET_log_from (kind, "util-crypto-ecc", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-ecc", __VA_ARGS__)
31 31
32#define LOG_STRERROR(kind, syscall) \ 32#define LOG_STRERROR(kind, syscall) \
33 GNUNET_log_from_strerror (kind, "util-crypto-ecc", syscall) 33 GNUNET_log_from_strerror(kind, "util-crypto-ecc", syscall)
34 34
35#define LOG_STRERROR_FILE(kind, syscall, filename) \ 35#define LOG_STRERROR_FILE(kind, syscall, filename) \
36 GNUNET_log_from_strerror_file (kind, "util-crypto-ecc", syscall, filename) 36 GNUNET_log_from_strerror_file(kind, "util-crypto-ecc", syscall, filename)
37 37
38/** 38/**
39 * Log an error message at log-level 'level' that indicates 39 * Log an error message at log-level 'level' that indicates
@@ -42,14 +42,14 @@
42 */ 42 */
43#define LOG_GCRY(level, cmd, rc) \ 43#define LOG_GCRY(level, cmd, rc) \
44 do \ 44 do \
45 { \ 45 { \
46 LOG (level, \ 46 LOG(level, \
47 _ ("`%s' failed at %s:%d with error: %s\n"), \ 47 _("`%s' failed at %s:%d with error: %s\n"), \
48 cmd, \ 48 cmd, \
49 __FILE__, \ 49 __FILE__, \
50 __LINE__, \ 50 __LINE__, \
51 gcry_strerror (rc)); \ 51 gcry_strerror(rc)); \
52 } while (0) 52 } while (0)
53 53
54 54
55/** 55/**
@@ -60,12 +60,12 @@
60 * some 'real' work). 60 * some 'real' work).
61 */ 61 */
62static void 62static void
63short_wait () 63short_wait()
64{ 64{
65 struct GNUNET_TIME_Relative timeout; 65 struct GNUNET_TIME_Relative timeout;
66 66
67 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 100); 67 timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 100);
68 (void) GNUNET_NETWORK_socket_select (NULL, NULL, NULL, timeout); 68 (void)GNUNET_NETWORK_socket_select(NULL, NULL, NULL, timeout);
69} 69}
70 70
71 71
@@ -84,7 +84,7 @@ short_wait ()
84 * permission denied) 84 * permission denied)
85 */ 85 */
86struct GNUNET_CRYPTO_EddsaPrivateKey * 86struct GNUNET_CRYPTO_EddsaPrivateKey *
87GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename) 87GNUNET_CRYPTO_eddsa_key_create_from_file(const char *filename)
88{ 88{
89 struct GNUNET_CRYPTO_EddsaPrivateKey *priv; 89 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
90 struct GNUNET_DISK_FileHandle *fd; 90 struct GNUNET_DISK_FileHandle *fd;
@@ -93,159 +93,159 @@ GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename)
93 uint64_t fs; 93 uint64_t fs;
94 ssize_t sret; 94 ssize_t sret;
95 95
96 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename)) 96 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file(filename))
97 return NULL; 97 return NULL;
98 while (GNUNET_YES != GNUNET_DISK_file_test (filename)) 98 while (GNUNET_YES != GNUNET_DISK_file_test(filename))
99 {
100 fd =
101 GNUNET_DISK_file_open (filename,
102 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
103 GNUNET_DISK_OPEN_FAILIFEXISTS,
104 GNUNET_DISK_PERM_USER_READ |
105 GNUNET_DISK_PERM_USER_WRITE);
106 if (NULL == fd)
107 { 99 {
108 if (EEXIST == errno) 100 fd =
109 { 101 GNUNET_DISK_file_open(filename,
110 if (GNUNET_YES != GNUNET_DISK_file_test (filename)) 102 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
103 GNUNET_DISK_OPEN_FAILIFEXISTS,
104 GNUNET_DISK_PERM_USER_READ |
105 GNUNET_DISK_PERM_USER_WRITE);
106 if (NULL == fd)
111 { 107 {
112 /* must exist but not be accessible, fail for good! */ 108 if (EEXIST == errno)
113 if (0 != access (filename, R_OK)) 109 {
114 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename); 110 if (GNUNET_YES != GNUNET_DISK_file_test(filename))
115 else 111 {
116 GNUNET_break (0); /* what is going on!? */ 112 /* must exist but not be accessible, fail for good! */
113 if (0 != access(filename, R_OK))
114 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "access", filename);
115 else
116 GNUNET_break(0); /* what is going on!? */
117 return NULL;
118 }
119 continue;
120 }
121 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "open", filename);
117 return NULL; 122 return NULL;
118 } 123 }
119 continue; 124 cnt = 0;
120 } 125 while (GNUNET_YES !=
121 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename); 126 GNUNET_DISK_file_lock(fd,
122 return NULL; 127 0,
123 } 128 sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey),
124 cnt = 0; 129 GNUNET_YES))
125 while (GNUNET_YES != 130 {
126 GNUNET_DISK_file_lock (fd, 131 short_wait();
132 if (0 == ++cnt % 10)
133 {
134 ec = errno;
135 LOG(GNUNET_ERROR_TYPE_ERROR,
136 _("Could not acquire lock on file `%s': %s...\n"),
137 filename,
138 strerror(ec));
139 }
140 }
141 LOG(GNUNET_ERROR_TYPE_INFO,
142 _("Creating a new private key. This may take a while.\n"));
143 priv = GNUNET_CRYPTO_eddsa_key_create();
144 GNUNET_assert(NULL != priv);
145 GNUNET_assert(sizeof(*priv) ==
146 GNUNET_DISK_file_write(fd, priv, sizeof(*priv)));
147 GNUNET_DISK_file_sync(fd);
148 if (GNUNET_YES !=
149 GNUNET_DISK_file_unlock(fd,
127 0, 150 0,
128 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey), 151 sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey)))
129 GNUNET_YES)) 152 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
130 { 153 GNUNET_assert(GNUNET_YES == GNUNET_DISK_file_close(fd));
131 short_wait (); 154 return priv;
132 if (0 == ++cnt % 10)
133 {
134 ec = errno;
135 LOG (GNUNET_ERROR_TYPE_ERROR,
136 _ ("Could not acquire lock on file `%s': %s...\n"),
137 filename,
138 strerror (ec));
139 }
140 } 155 }
141 LOG (GNUNET_ERROR_TYPE_INFO,
142 _ ("Creating a new private key. This may take a while.\n"));
143 priv = GNUNET_CRYPTO_eddsa_key_create ();
144 GNUNET_assert (NULL != priv);
145 GNUNET_assert (sizeof (*priv) ==
146 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
147 GNUNET_DISK_file_sync (fd);
148 if (GNUNET_YES !=
149 GNUNET_DISK_file_unlock (fd,
150 0,
151 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)))
152 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
153 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
154 return priv;
155 }
156 /* key file exists already, read it! */ 156 /* key file exists already, read it! */
157 fd = GNUNET_DISK_file_open (filename, 157 fd = GNUNET_DISK_file_open(filename,
158 GNUNET_DISK_OPEN_READ, 158 GNUNET_DISK_OPEN_READ,
159 GNUNET_DISK_PERM_NONE); 159 GNUNET_DISK_PERM_NONE);
160 if (NULL == fd) 160 if (NULL == fd)
161 {
162 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
163 return NULL;
164 }
165 cnt = 0;
166 while (1)
167 {
168 if (GNUNET_YES !=
169 GNUNET_DISK_file_lock (fd,
170 0,
171 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey),
172 GNUNET_NO))
173 { 161 {
174 if (0 == ++cnt % 60) 162 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "open", filename);
175 {
176 ec = errno;
177 LOG (GNUNET_ERROR_TYPE_ERROR,
178 _ ("Could not acquire lock on file `%s': %s...\n"),
179 filename,
180 strerror (ec));
181 LOG (
182 GNUNET_ERROR_TYPE_ERROR,
183 _ (
184 "This may be ok if someone is currently generating a private key.\n"));
185 }
186 short_wait ();
187 continue;
188 }
189 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
190 {
191 /* eh, what!? File we opened is now gone!? */
192 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
193 if (GNUNET_YES !=
194 GNUNET_DISK_file_unlock (fd,
195 0,
196 sizeof (
197 struct GNUNET_CRYPTO_EddsaPrivateKey)))
198 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
199 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
200
201 return NULL; 163 return NULL;
202 } 164 }
203 if (GNUNET_OK != 165 cnt = 0;
204 GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES)) 166 while (1)
205 fs = 0;
206 if (fs < sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey))
207 { 167 {
208 /* maybe we got the read lock before the key generating
209 * process had a chance to get the write lock; give it up! */
210 if (GNUNET_YES != 168 if (GNUNET_YES !=
211 GNUNET_DISK_file_unlock (fd, 169 GNUNET_DISK_file_lock(fd,
212 0, 170 0,
213 sizeof ( 171 sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey),
214 struct GNUNET_CRYPTO_EddsaPrivateKey))) 172 GNUNET_NO))
215 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename); 173 {
216 if (0 == ++cnt % 10) 174 if (0 == ++cnt % 60)
217 { 175 {
218 LOG (GNUNET_ERROR_TYPE_ERROR, 176 ec = errno;
219 _ ( 177 LOG(GNUNET_ERROR_TYPE_ERROR,
220 "When trying to read key file `%s' I found %u bytes but I need at least %u.\n"), 178 _("Could not acquire lock on file `%s': %s...\n"),
221 filename, 179 filename,
222 (unsigned int) fs, 180 strerror(ec));
223 (unsigned int) sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey)); 181 LOG(
224 LOG (GNUNET_ERROR_TYPE_ERROR, 182 GNUNET_ERROR_TYPE_ERROR,
225 _ ("This may be ok if someone is currently generating a key.\n")); 183 _(
226 } 184 "This may be ok if someone is currently generating a private key.\n"));
227 short_wait (); /* wait a bit longer! */ 185 }
228 continue; 186 short_wait();
187 continue;
188 }
189 if (GNUNET_YES != GNUNET_DISK_file_test(filename))
190 {
191 /* eh, what!? File we opened is now gone!? */
192 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", filename);
193 if (GNUNET_YES !=
194 GNUNET_DISK_file_unlock(fd,
195 0,
196 sizeof(
197 struct GNUNET_CRYPTO_EddsaPrivateKey)))
198 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
199 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fd));
200
201 return NULL;
202 }
203 if (GNUNET_OK !=
204 GNUNET_DISK_file_size(filename, &fs, GNUNET_YES, GNUNET_YES))
205 fs = 0;
206 if (fs < sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey))
207 {
208 /* maybe we got the read lock before the key generating
209 * process had a chance to get the write lock; give it up! */
210 if (GNUNET_YES !=
211 GNUNET_DISK_file_unlock(fd,
212 0,
213 sizeof(
214 struct GNUNET_CRYPTO_EddsaPrivateKey)))
215 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
216 if (0 == ++cnt % 10)
217 {
218 LOG(GNUNET_ERROR_TYPE_ERROR,
219 _(
220 "When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
221 filename,
222 (unsigned int)fs,
223 (unsigned int)sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey));
224 LOG(GNUNET_ERROR_TYPE_ERROR,
225 _("This may be ok if someone is currently generating a key.\n"));
226 }
227 short_wait(); /* wait a bit longer! */
228 continue;
229 }
230 break;
229 } 231 }
230 break; 232 fs = sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey);
231 } 233 priv = GNUNET_malloc(fs);
232 fs = sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey); 234 sret = GNUNET_DISK_file_read(fd, priv, fs);
233 priv = GNUNET_malloc (fs); 235 GNUNET_assert((sret >= 0) && (fs == (size_t)sret));
234 sret = GNUNET_DISK_file_read (fd, priv, fs);
235 GNUNET_assert ((sret >= 0) && (fs == (size_t) sret));
236 if (GNUNET_YES != 236 if (GNUNET_YES !=
237 GNUNET_DISK_file_unlock (fd, 237 GNUNET_DISK_file_unlock(fd,
238 0, 238 0,
239 sizeof (struct GNUNET_CRYPTO_EddsaPrivateKey))) 239 sizeof(struct GNUNET_CRYPTO_EddsaPrivateKey)))
240 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename); 240 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
241 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd)); 241 GNUNET_assert(GNUNET_YES == GNUNET_DISK_file_close(fd));
242#if CRYPTO_BUG 242#if CRYPTO_BUG
243 if (GNUNET_OK != check_eddsa_key (priv)) 243 if (GNUNET_OK != check_eddsa_key(priv))
244 { 244 {
245 GNUNET_break (0); 245 GNUNET_break(0);
246 GNUNET_free (priv); 246 GNUNET_free(priv);
247 return NULL; 247 return NULL;
248 } 248 }
249#endif 249#endif
250 return priv; 250 return priv;
251} 251}
@@ -266,7 +266,7 @@ GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename)
266 * permission denied) 266 * permission denied)
267 */ 267 */
268struct GNUNET_CRYPTO_EcdsaPrivateKey * 268struct GNUNET_CRYPTO_EcdsaPrivateKey *
269GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename) 269GNUNET_CRYPTO_ecdsa_key_create_from_file(const char *filename)
270{ 270{
271 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv; 271 struct GNUNET_CRYPTO_EcdsaPrivateKey *priv;
272 struct GNUNET_DISK_FileHandle *fd; 272 struct GNUNET_DISK_FileHandle *fd;
@@ -275,152 +275,152 @@ GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename)
275 uint64_t fs; 275 uint64_t fs;
276 ssize_t sret; 276 ssize_t sret;
277 277
278 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file (filename)) 278 if (GNUNET_SYSERR == GNUNET_DISK_directory_create_for_file(filename))
279 return NULL; 279 return NULL;
280 while (GNUNET_YES != GNUNET_DISK_file_test (filename)) 280 while (GNUNET_YES != GNUNET_DISK_file_test(filename))
281 {
282 fd =
283 GNUNET_DISK_file_open (filename,
284 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
285 GNUNET_DISK_OPEN_FAILIFEXISTS,
286 GNUNET_DISK_PERM_USER_READ |
287 GNUNET_DISK_PERM_USER_WRITE);
288 if (NULL == fd)
289 { 281 {
290 if (EEXIST == errno) 282 fd =
291 { 283 GNUNET_DISK_file_open(filename,
292 if (GNUNET_YES != GNUNET_DISK_file_test (filename)) 284 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
285 GNUNET_DISK_OPEN_FAILIFEXISTS,
286 GNUNET_DISK_PERM_USER_READ |
287 GNUNET_DISK_PERM_USER_WRITE);
288 if (NULL == fd)
293 { 289 {
294 /* must exist but not be accessible, fail for good! */ 290 if (EEXIST == errno)
295 if (0 != access (filename, R_OK)) 291 {
296 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "access", filename); 292 if (GNUNET_YES != GNUNET_DISK_file_test(filename))
297 else 293 {
298 GNUNET_break (0); /* what is going on!? */ 294 /* must exist but not be accessible, fail for good! */
295 if (0 != access(filename, R_OK))
296 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "access", filename);
297 else
298 GNUNET_break(0); /* what is going on!? */
299 return NULL;
300 }
301 continue;
302 }
303 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "open", filename);
299 return NULL; 304 return NULL;
300 } 305 }
301 continue; 306 cnt = 0;
302 } 307 while (GNUNET_YES !=
303 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename); 308 GNUNET_DISK_file_lock(fd,
304 return NULL; 309 0,
305 } 310 sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey),
306 cnt = 0; 311 GNUNET_YES))
307 while (GNUNET_YES != 312 {
308 GNUNET_DISK_file_lock (fd, 313 short_wait();
314 if (0 == ++cnt % 10)
315 {
316 ec = errno;
317 LOG(GNUNET_ERROR_TYPE_ERROR,
318 _("Could not acquire lock on file `%s': %s...\n"),
319 filename,
320 strerror(ec));
321 }
322 }
323 LOG(GNUNET_ERROR_TYPE_INFO,
324 _("Creating a new private key. This may take a while.\n"));
325 priv = GNUNET_CRYPTO_ecdsa_key_create();
326 GNUNET_assert(NULL != priv);
327 GNUNET_assert(sizeof(*priv) ==
328 GNUNET_DISK_file_write(fd, priv, sizeof(*priv)));
329 GNUNET_DISK_file_sync(fd);
330 if (GNUNET_YES !=
331 GNUNET_DISK_file_unlock(fd,
309 0, 332 0,
310 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey), 333 sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey)))
311 GNUNET_YES)) 334 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
312 { 335 GNUNET_assert(GNUNET_YES == GNUNET_DISK_file_close(fd));
313 short_wait (); 336 return priv;
314 if (0 == ++cnt % 10)
315 {
316 ec = errno;
317 LOG (GNUNET_ERROR_TYPE_ERROR,
318 _ ("Could not acquire lock on file `%s': %s...\n"),
319 filename,
320 strerror (ec));
321 }
322 } 337 }
323 LOG (GNUNET_ERROR_TYPE_INFO,
324 _ ("Creating a new private key. This may take a while.\n"));
325 priv = GNUNET_CRYPTO_ecdsa_key_create ();
326 GNUNET_assert (NULL != priv);
327 GNUNET_assert (sizeof (*priv) ==
328 GNUNET_DISK_file_write (fd, priv, sizeof (*priv)));
329 GNUNET_DISK_file_sync (fd);
330 if (GNUNET_YES !=
331 GNUNET_DISK_file_unlock (fd,
332 0,
333 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)))
334 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
335 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd));
336 return priv;
337 }
338 /* key file exists already, read it! */ 338 /* key file exists already, read it! */
339 fd = GNUNET_DISK_file_open (filename, 339 fd = GNUNET_DISK_file_open(filename,
340 GNUNET_DISK_OPEN_READ, 340 GNUNET_DISK_OPEN_READ,
341 GNUNET_DISK_PERM_NONE); 341 GNUNET_DISK_PERM_NONE);
342 if (NULL == fd) 342 if (NULL == fd)
343 {
344 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "open", filename);
345 return NULL;
346 }
347 cnt = 0;
348 while (1)
349 {
350 if (GNUNET_YES !=
351 GNUNET_DISK_file_lock (fd,
352 0,
353 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey),
354 GNUNET_NO))
355 { 343 {
356 if (0 == ++cnt % 60) 344 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "open", filename);
357 {
358 ec = errno;
359 LOG (GNUNET_ERROR_TYPE_ERROR,
360 _ ("Could not acquire lock on file `%s': %s...\n"),
361 filename,
362 strerror (ec));
363 LOG (
364 GNUNET_ERROR_TYPE_ERROR,
365 _ (
366 "This may be ok if someone is currently generating a private key.\n"));
367 }
368 short_wait ();
369 continue;
370 }
371 if (GNUNET_YES != GNUNET_DISK_file_test (filename))
372 {
373 /* eh, what!? File we opened is now gone!? */
374 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", filename);
375 if (GNUNET_YES !=
376 GNUNET_DISK_file_unlock (fd,
377 0,
378 sizeof (
379 struct GNUNET_CRYPTO_EcdsaPrivateKey)))
380 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
381 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fd));
382
383 return NULL; 345 return NULL;
384 } 346 }
385 if (GNUNET_OK != 347 cnt = 0;
386 GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES)) 348 while (1)
387 fs = 0;
388 if (fs < sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))
389 { 349 {
390 /* maybe we got the read lock before the key generating
391 * process had a chance to get the write lock; give it up! */
392 if (GNUNET_YES != 350 if (GNUNET_YES !=
393 GNUNET_DISK_file_unlock (fd, 351 GNUNET_DISK_file_lock(fd,
394 0, 352 0,
395 sizeof ( 353 sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey),
396 struct GNUNET_CRYPTO_EcdsaPrivateKey))) 354 GNUNET_NO))
397 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename); 355 {
398 if (0 == ++cnt % 10) 356 if (0 == ++cnt % 60)
399 { 357 {
400 LOG (GNUNET_ERROR_TYPE_ERROR, 358 ec = errno;
401 _ ( 359 LOG(GNUNET_ERROR_TYPE_ERROR,
402 "When trying to read key file `%s' I found %u bytes but I need at least %u.\n"), 360 _("Could not acquire lock on file `%s': %s...\n"),
403 filename, 361 filename,
404 (unsigned int) fs, 362 strerror(ec));
405 (unsigned int) sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey)); 363 LOG(
406 LOG (GNUNET_ERROR_TYPE_ERROR, 364 GNUNET_ERROR_TYPE_ERROR,
407 _ ("This may be ok if someone is currently generating a key.\n")); 365 _(
408 } 366 "This may be ok if someone is currently generating a private key.\n"));
409 short_wait (); /* wait a bit longer! */ 367 }
410 continue; 368 short_wait();
369 continue;
370 }
371 if (GNUNET_YES != GNUNET_DISK_file_test(filename))
372 {
373 /* eh, what!? File we opened is now gone!? */
374 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", filename);
375 if (GNUNET_YES !=
376 GNUNET_DISK_file_unlock(fd,
377 0,
378 sizeof(
379 struct GNUNET_CRYPTO_EcdsaPrivateKey)))
380 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
381 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fd));
382
383 return NULL;
384 }
385 if (GNUNET_OK !=
386 GNUNET_DISK_file_size(filename, &fs, GNUNET_YES, GNUNET_YES))
387 fs = 0;
388 if (fs < sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey))
389 {
390 /* maybe we got the read lock before the key generating
391 * process had a chance to get the write lock; give it up! */
392 if (GNUNET_YES !=
393 GNUNET_DISK_file_unlock(fd,
394 0,
395 sizeof(
396 struct GNUNET_CRYPTO_EcdsaPrivateKey)))
397 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
398 if (0 == ++cnt % 10)
399 {
400 LOG(GNUNET_ERROR_TYPE_ERROR,
401 _(
402 "When trying to read key file `%s' I found %u bytes but I need at least %u.\n"),
403 filename,
404 (unsigned int)fs,
405 (unsigned int)sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey));
406 LOG(GNUNET_ERROR_TYPE_ERROR,
407 _("This may be ok if someone is currently generating a key.\n"));
408 }
409 short_wait(); /* wait a bit longer! */
410 continue;
411 }
412 break;
411 } 413 }
412 break; 414 fs = sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey);
413 } 415 priv = GNUNET_malloc(fs);
414 fs = sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey); 416 sret = GNUNET_DISK_file_read(fd, priv, fs);
415 priv = GNUNET_malloc (fs); 417 GNUNET_assert((sret >= 0) && (fs == (size_t)sret));
416 sret = GNUNET_DISK_file_read (fd, priv, fs);
417 GNUNET_assert ((sret >= 0) && (fs == (size_t) sret));
418 if (GNUNET_YES != 418 if (GNUNET_YES !=
419 GNUNET_DISK_file_unlock (fd, 419 GNUNET_DISK_file_unlock(fd,
420 0, 420 0,
421 sizeof (struct GNUNET_CRYPTO_EcdsaPrivateKey))) 421 sizeof(struct GNUNET_CRYPTO_EcdsaPrivateKey)))
422 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "fcntl", filename); 422 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "fcntl", filename);
423 GNUNET_assert (GNUNET_YES == GNUNET_DISK_file_close (fd)); 423 GNUNET_assert(GNUNET_YES == GNUNET_DISK_file_close(fd));
424 return priv; 424 return priv;
425} 425}
426 426
@@ -434,17 +434,17 @@ GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename)
434 * permission denied) 434 * permission denied)
435 */ 435 */
436struct GNUNET_CRYPTO_EddsaPrivateKey * 436struct GNUNET_CRYPTO_EddsaPrivateKey *
437GNUNET_CRYPTO_eddsa_key_create_from_configuration ( 437GNUNET_CRYPTO_eddsa_key_create_from_configuration(
438 const struct GNUNET_CONFIGURATION_Handle *cfg) 438 const struct GNUNET_CONFIGURATION_Handle *cfg)
439{ 439{
440 struct GNUNET_CRYPTO_EddsaPrivateKey *priv; 440 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
441 char *fn; 441 char *fn;
442 442
443 if (GNUNET_OK != 443 if (GNUNET_OK !=
444 GNUNET_CONFIGURATION_get_value_filename (cfg, "PEER", "PRIVATE_KEY", &fn)) 444 GNUNET_CONFIGURATION_get_value_filename(cfg, "PEER", "PRIVATE_KEY", &fn))
445 return NULL; 445 return NULL;
446 priv = GNUNET_CRYPTO_eddsa_key_create_from_file (fn); 446 priv = GNUNET_CRYPTO_eddsa_key_create_from_file(fn);
447 GNUNET_free (fn); 447 GNUNET_free(fn);
448 return priv; 448 return priv;
449} 449}
450 450
@@ -458,19 +458,19 @@ GNUNET_CRYPTO_eddsa_key_create_from_configuration (
458 * could not be retrieved 458 * could not be retrieved
459 */ 459 */
460int 460int
461GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg, 461GNUNET_CRYPTO_get_peer_identity(const struct GNUNET_CONFIGURATION_Handle *cfg,
462 struct GNUNET_PeerIdentity *dst) 462 struct GNUNET_PeerIdentity *dst)
463{ 463{
464 struct GNUNET_CRYPTO_EddsaPrivateKey *priv; 464 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
465 465
466 if (NULL == (priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg))) 466 if (NULL == (priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg)))
467 { 467 {
468 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 468 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
469 _ ("Could not load peer's private key\n")); 469 _("Could not load peer's private key\n"));
470 return GNUNET_SYSERR; 470 return GNUNET_SYSERR;
471 } 471 }
472 GNUNET_CRYPTO_eddsa_key_get_public (priv, &dst->public_key); 472 GNUNET_CRYPTO_eddsa_key_get_public(priv, &dst->public_key);
473 GNUNET_free (priv); 473 GNUNET_free(priv);
474 return GNUNET_OK; 474 return GNUNET_OK;
475} 475}
476 476
@@ -484,17 +484,17 @@ GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
484 * @param cfg_name name of the configuration file to use 484 * @param cfg_name name of the configuration file to use
485 */ 485 */
486void 486void
487GNUNET_CRYPTO_eddsa_setup_key (const char *cfg_name) 487GNUNET_CRYPTO_eddsa_setup_key(const char *cfg_name)
488{ 488{
489 struct GNUNET_CONFIGURATION_Handle *cfg; 489 struct GNUNET_CONFIGURATION_Handle *cfg;
490 struct GNUNET_CRYPTO_EddsaPrivateKey *priv; 490 struct GNUNET_CRYPTO_EddsaPrivateKey *priv;
491 491
492 cfg = GNUNET_CONFIGURATION_create (); 492 cfg = GNUNET_CONFIGURATION_create();
493 (void) GNUNET_CONFIGURATION_load (cfg, cfg_name); 493 (void)GNUNET_CONFIGURATION_load(cfg, cfg_name);
494 priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration (cfg); 494 priv = GNUNET_CRYPTO_eddsa_key_create_from_configuration(cfg);
495 if (NULL != priv) 495 if (NULL != priv)
496 GNUNET_free (priv); 496 GNUNET_free(priv);
497 GNUNET_CONFIGURATION_destroy (cfg); 497 GNUNET_CONFIGURATION_destroy(cfg);
498} 498}
499 499
500/* end of crypto_ecc_setup.c */ 500/* end of crypto_ecc_setup.c */
diff --git a/src/util/crypto_hash.c b/src/util/crypto_hash.c
index 925d6b94d..ebb1266b2 100644
--- a/src/util/crypto_hash.c
+++ b/src/util/crypto_hash.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/crypto_hash.c 22 * @file util/crypto_hash.c
23 * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions 23 * @brief SHA-512 #GNUNET_CRYPTO_hash() related functions
@@ -29,9 +29,9 @@
29#include "benchmark.h" 29#include "benchmark.h"
30#include <gcrypt.h> 30#include <gcrypt.h>
31 31
32#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-hash", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-hash", __VA_ARGS__)
33 33
34#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-crypto-hash", syscall, filename) 34#define LOG_STRERROR_FILE(kind, syscall, filename) GNUNET_log_from_strerror_file(kind, "util-crypto-hash", syscall, filename)
35 35
36/** 36/**
37 * Hash block of given size. 37 * Hash block of given size.
@@ -41,13 +41,13 @@
41 * @param ret pointer to where to write the hashcode 41 * @param ret pointer to where to write the hashcode
42 */ 42 */
43void 43void
44GNUNET_CRYPTO_hash (const void *block, 44GNUNET_CRYPTO_hash(const void *block,
45 size_t size, 45 size_t size,
46 struct GNUNET_HashCode *ret) 46 struct GNUNET_HashCode *ret)
47{ 47{
48 BENCHMARK_START (hash); 48 BENCHMARK_START(hash);
49 gcry_md_hash_buffer (GCRY_MD_SHA512, ret, block, size); 49 gcry_md_hash_buffer(GCRY_MD_SHA512, ret, block, size);
50 BENCHMARK_END (hash); 50 BENCHMARK_END(hash);
51} 51}
52 52
53 53
@@ -66,16 +66,16 @@ GNUNET_CRYPTO_hash (const void *block,
66 * safely cast to char*, a '\\0' termination is set). 66 * safely cast to char*, a '\\0' termination is set).
67 */ 67 */
68void 68void
69GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block, 69GNUNET_CRYPTO_hash_to_enc(const struct GNUNET_HashCode *block,
70 struct GNUNET_CRYPTO_HashAsciiEncoded *result) 70 struct GNUNET_CRYPTO_HashAsciiEncoded *result)
71{ 71{
72 char *np; 72 char *np;
73 73
74 np = GNUNET_STRINGS_data_to_string ((const unsigned char *) block, 74 np = GNUNET_STRINGS_data_to_string((const unsigned char *)block,
75 sizeof (struct GNUNET_HashCode), 75 sizeof(struct GNUNET_HashCode),
76 (char *) result, 76 (char *)result,
77 sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1); 77 sizeof(struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
78 GNUNET_assert (NULL != np); 78 GNUNET_assert(NULL != np);
79 *np = '\0'; 79 *np = '\0';
80} 80}
81 81
@@ -89,18 +89,18 @@ GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
89 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding 89 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
90 */ 90 */
91int 91int
92GNUNET_CRYPTO_hash_from_string2 (const char *enc, 92GNUNET_CRYPTO_hash_from_string2(const char *enc,
93 size_t enclen, 93 size_t enclen,
94 struct GNUNET_HashCode *result) 94 struct GNUNET_HashCode *result)
95{ 95{
96 char upper_enc[enclen]; 96 char upper_enc[enclen];
97 char *up_ptr = upper_enc; 97 char *up_ptr = upper_enc;
98 98
99 GNUNET_STRINGS_utf8_toupper (enc, up_ptr); 99 GNUNET_STRINGS_utf8_toupper(enc, up_ptr);
100 100
101 return GNUNET_STRINGS_string_to_data (upper_enc, enclen, 101 return GNUNET_STRINGS_string_to_data(upper_enc, enclen,
102 (unsigned char*) result, 102 (unsigned char*)result,
103 sizeof (struct GNUNET_HashCode)); 103 sizeof(struct GNUNET_HashCode));
104} 104}
105 105
106 106
@@ -118,13 +118,13 @@ GNUNET_CRYPTO_hash_from_string2 (const char *enc,
118 * hashcode proximity. 118 * hashcode proximity.
119 */ 119 */
120unsigned int 120unsigned int
121GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a, 121GNUNET_CRYPTO_hash_distance_u32(const struct GNUNET_HashCode *a,
122 const struct GNUNET_HashCode *b) 122 const struct GNUNET_HashCode *b)
123{ 123{
124 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16; 124 unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
125 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16; 125 unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
126 126
127 return (x1 * x2); 127 return(x1 * x2);
128} 128}
129 129
130 130
@@ -135,13 +135,13 @@ GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
135 * @param result hash code that is randomized 135 * @param result hash code that is randomized
136 */ 136 */
137void 137void
138GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode, 138GNUNET_CRYPTO_hash_create_random(enum GNUNET_CRYPTO_Quality mode,
139 struct GNUNET_HashCode *result) 139 struct GNUNET_HashCode *result)
140{ 140{
141 int i; 141 int i;
142 142
143 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (uint32_t)) - 1; i >= 0; i--) 143 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(uint32_t)) - 1; i >= 0; i--)
144 result->bits[i] = GNUNET_CRYPTO_random_u32 (mode, UINT32_MAX); 144 result->bits[i] = GNUNET_CRYPTO_random_u32(mode, UINT32_MAX);
145} 145}
146 146
147 147
@@ -153,13 +153,13 @@ GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
153 * @param result set to b - a 153 * @param result set to b - a
154 */ 154 */
155void 155void
156GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a, 156GNUNET_CRYPTO_hash_difference(const struct GNUNET_HashCode *a,
157 const struct GNUNET_HashCode *b, 157 const struct GNUNET_HashCode *b,
158 struct GNUNET_HashCode *result) 158 struct GNUNET_HashCode *result)
159{ 159{
160 int i; 160 int i;
161 161
162 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--) 162 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
163 result->bits[i] = b->bits[i] - a->bits[i]; 163 result->bits[i] = b->bits[i] - a->bits[i];
164} 164}
165 165
@@ -172,12 +172,12 @@ GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
172 * @param result set to a + delta 172 * @param result set to a + delta
173 */ 173 */
174void 174void
175GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a, 175GNUNET_CRYPTO_hash_sum(const struct GNUNET_HashCode * a,
176 const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result) 176 const struct GNUNET_HashCode * delta, struct GNUNET_HashCode * result)
177{ 177{
178 int i; 178 int i;
179 179
180 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--) 180 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
181 result->bits[i] = delta->bits[i] + a->bits[i]; 181 result->bits[i] = delta->bits[i] + a->bits[i];
182} 182}
183 183
@@ -190,13 +190,13 @@ GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
190 * @param result set to a ^ b 190 * @param result set to a ^ b
191 */ 191 */
192void 192void
193GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a, 193GNUNET_CRYPTO_hash_xor(const struct GNUNET_HashCode *a,
194 const struct GNUNET_HashCode *b, 194 const struct GNUNET_HashCode *b,
195 struct GNUNET_HashCode *result) 195 struct GNUNET_HashCode *result)
196{ 196{
197 int i; 197 int i;
198 198
199 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--) 199 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
200 result->bits[i] = a->bits[i] ^ b->bits[i]; 200 result->bits[i] = a->bits[i] ^ b->bits[i];
201} 201}
202 202
@@ -209,20 +209,20 @@ GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
209 * @param iv set to a valid initialization vector 209 * @param iv set to a valid initialization vector
210 */ 210 */
211void 211void
212GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc, 212GNUNET_CRYPTO_hash_to_aes_key(const struct GNUNET_HashCode *hc,
213 struct GNUNET_CRYPTO_SymmetricSessionKey *skey, 213 struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
214 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv) 214 struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
215{ 215{
216 GNUNET_assert (GNUNET_YES == 216 GNUNET_assert(GNUNET_YES ==
217 GNUNET_CRYPTO_kdf (skey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey), 217 GNUNET_CRYPTO_kdf(skey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
218 "Hash key derivation", strlen ("Hash key derivation"), 218 "Hash key derivation", strlen("Hash key derivation"),
219 hc, sizeof (struct GNUNET_HashCode), 219 hc, sizeof(struct GNUNET_HashCode),
220 NULL, 0)); 220 NULL, 0));
221 GNUNET_assert (GNUNET_YES == 221 GNUNET_assert(GNUNET_YES ==
222 GNUNET_CRYPTO_kdf (iv, sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector), 222 GNUNET_CRYPTO_kdf(iv, sizeof(struct GNUNET_CRYPTO_SymmetricInitializationVector),
223 "Initialization vector derivation", strlen ("Initialization vector derivation"), 223 "Initialization vector derivation", strlen("Initialization vector derivation"),
224 hc, sizeof (struct GNUNET_HashCode), 224 hc, sizeof(struct GNUNET_HashCode),
225 NULL, 0)); 225 NULL, 0));
226} 226}
227 227
228 228
@@ -233,10 +233,10 @@ GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode *hc,
233 * @return Bit \a bit from hashcode \a code, -1 for invalid index 233 * @return Bit \a bit from hashcode \a code, -1 for invalid index
234 */ 234 */
235int 235int
236GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit) 236GNUNET_CRYPTO_hash_get_bit(const struct GNUNET_HashCode * code, unsigned int bit)
237{ 237{
238 GNUNET_assert (bit < 8 * sizeof (struct GNUNET_HashCode)); 238 GNUNET_assert(bit < 8 * sizeof(struct GNUNET_HashCode));
239 return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0; 239 return (((unsigned char *)code)[bit >> 3] & (1 << (bit & 7))) > 0;
240} 240}
241 241
242 242
@@ -253,16 +253,16 @@ GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bi
253 * @return the number of bits that match 253 * @return the number of bits that match
254 */ 254 */
255unsigned int 255unsigned int
256GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first, 256GNUNET_CRYPTO_hash_matching_bits(const struct GNUNET_HashCode * first,
257 const struct GNUNET_HashCode * second) 257 const struct GNUNET_HashCode * second)
258{ 258{
259 unsigned int i; 259 unsigned int i;
260 260
261 for (i = 0; i < sizeof (struct GNUNET_HashCode) * 8; i++) 261 for (i = 0; i < sizeof(struct GNUNET_HashCode) * 8; i++)
262 if (GNUNET_CRYPTO_hash_get_bit (first, i) != 262 if (GNUNET_CRYPTO_hash_get_bit(first, i) !=
263 GNUNET_CRYPTO_hash_get_bit (second, i)) 263 GNUNET_CRYPTO_hash_get_bit(second, i))
264 return i; 264 return i;
265 return sizeof (struct GNUNET_HashCode) * 8; 265 return sizeof(struct GNUNET_HashCode) * 8;
266} 266}
267 267
268 268
@@ -275,22 +275,22 @@ GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
275 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2. 275 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
276 */ 276 */
277int 277int
278GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1, 278GNUNET_CRYPTO_hash_cmp(const struct GNUNET_HashCode *h1,
279 const struct GNUNET_HashCode *h2) 279 const struct GNUNET_HashCode *h2)
280{ 280{
281 unsigned int *i1; 281 unsigned int *i1;
282 unsigned int *i2; 282 unsigned int *i2;
283 int i; 283 int i;
284 284
285 i1 = (unsigned int *) h1; 285 i1 = (unsigned int *)h1;
286 i2 = (unsigned int *) h2; 286 i2 = (unsigned int *)h2;
287 for (i = (sizeof (struct GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0; i--) 287 for (i = (sizeof(struct GNUNET_HashCode) / sizeof(unsigned int)) - 1; i >= 0; i--)
288 { 288 {
289 if (i1[i] > i2[i]) 289 if (i1[i] > i2[i])
290 return 1; 290 return 1;
291 if (i1[i] < i2[i]) 291 if (i1[i] < i2[i])
292 return -1; 292 return -1;
293 } 293 }
294 return 0; 294 return 0;
295} 295}
296 296
@@ -305,23 +305,23 @@ GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
305 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2. 305 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
306 */ 306 */
307int 307int
308GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1, 308GNUNET_CRYPTO_hash_xorcmp(const struct GNUNET_HashCode *h1,
309 const struct GNUNET_HashCode *h2, 309 const struct GNUNET_HashCode *h2,
310 const struct GNUNET_HashCode *target) 310 const struct GNUNET_HashCode *target)
311{ 311{
312 int i; 312 int i;
313 unsigned int d1; 313 unsigned int d1;
314 unsigned int d2; 314 unsigned int d2;
315 315
316 for (i = sizeof (struct GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--) 316 for (i = sizeof(struct GNUNET_HashCode) / sizeof(unsigned int) - 1; i >= 0; i--)
317 { 317 {
318 d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i]; 318 d1 = ((unsigned int *)h1)[i] ^ ((unsigned int *)target)[i];
319 d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i]; 319 d2 = ((unsigned int *)h2)[i] ^ ((unsigned int *)target)[i];
320 if (d1 > d2) 320 if (d1 > d2)
321 return 1; 321 return 1;
322 else if (d1 < d2) 322 else if (d1 < d2)
323 return -1; 323 return -1;
324 } 324 }
325 return 0; 325 return 0;
326} 326}
327 327
@@ -335,15 +335,15 @@ GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
335 * @param ... pair of void * & size_t for context chunks, terminated by NULL 335 * @param ... pair of void * & size_t for context chunks, terminated by NULL
336 */ 336 */
337void 337void
338GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key, 338GNUNET_CRYPTO_hmac_derive_key(struct GNUNET_CRYPTO_AuthKey *key,
339 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey, 339 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
340 const void *salt, size_t salt_len, ...) 340 const void *salt, size_t salt_len, ...)
341{ 341{
342 va_list argp; 342 va_list argp;
343 343
344 va_start (argp, salt_len); 344 va_start(argp, salt_len);
345 GNUNET_CRYPTO_hmac_derive_key_v (key, rkey, salt, salt_len, argp); 345 GNUNET_CRYPTO_hmac_derive_key_v(key, rkey, salt, salt_len, argp);
346 va_end (argp); 346 va_end(argp);
347} 347}
348 348
349 349
@@ -356,15 +356,15 @@ GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
356 * @param argp pair of void * & size_t for context chunks, terminated by NULL 356 * @param argp pair of void * & size_t for context chunks, terminated by NULL
357 */ 357 */
358void 358void
359GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key, 359GNUNET_CRYPTO_hmac_derive_key_v(struct GNUNET_CRYPTO_AuthKey *key,
360 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey, 360 const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
361 const void *salt, size_t salt_len, 361 const void *salt, size_t salt_len,
362 va_list argp) 362 va_list argp)
363{ 363{
364 GNUNET_CRYPTO_kdf_v (key->key, sizeof (key->key), 364 GNUNET_CRYPTO_kdf_v(key->key, sizeof(key->key),
365 salt, salt_len, 365 salt, salt_len,
366 rkey, sizeof (struct GNUNET_CRYPTO_SymmetricSessionKey), 366 rkey, sizeof(struct GNUNET_CRYPTO_SymmetricSessionKey),
367 argp); 367 argp);
368} 368}
369 369
370 370
@@ -380,29 +380,29 @@ GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
380 * @param hmac where to store the hmac 380 * @param hmac where to store the hmac
381 */ 381 */
382void 382void
383GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len, 383GNUNET_CRYPTO_hmac_raw(const void *key, size_t key_len,
384 const void *plaintext, size_t plaintext_len, 384 const void *plaintext, size_t plaintext_len,
385 struct GNUNET_HashCode *hmac) 385 struct GNUNET_HashCode *hmac)
386{ 386{
387 static int once; 387 static int once;
388 static gcry_md_hd_t md; 388 static gcry_md_hd_t md;
389 const unsigned char *mc; 389 const unsigned char *mc;
390 390
391 if (! once) 391 if (!once)
392 { 392 {
393 once = 1; 393 once = 1;
394 GNUNET_assert (GPG_ERR_NO_ERROR == 394 GNUNET_assert(GPG_ERR_NO_ERROR ==
395 gcry_md_open (&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC)); 395 gcry_md_open(&md, GCRY_MD_SHA512, GCRY_MD_FLAG_HMAC));
396 } 396 }
397 else 397 else
398 { 398 {
399 gcry_md_reset (md); 399 gcry_md_reset(md);
400 } 400 }
401 gcry_md_setkey (md, key, key_len); 401 gcry_md_setkey(md, key, key_len);
402 gcry_md_write (md, plaintext, plaintext_len); 402 gcry_md_write(md, plaintext, plaintext_len);
403 mc = gcry_md_read (md, GCRY_MD_SHA512); 403 mc = gcry_md_read(md, GCRY_MD_SHA512);
404 GNUNET_assert (NULL != mc); 404 GNUNET_assert(NULL != mc);
405 GNUNET_memcpy (hmac->bits, mc, sizeof (hmac->bits)); 405 GNUNET_memcpy(hmac->bits, mc, sizeof(hmac->bits));
406} 406}
407 407
408 408
@@ -415,21 +415,20 @@ GNUNET_CRYPTO_hmac_raw (const void *key, size_t key_len,
415 * @param hmac where to store the hmac 415 * @param hmac where to store the hmac
416 */ 416 */
417void 417void
418GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key, 418GNUNET_CRYPTO_hmac(const struct GNUNET_CRYPTO_AuthKey *key,
419 const void *plaintext, size_t plaintext_len, 419 const void *plaintext, size_t plaintext_len,
420 struct GNUNET_HashCode *hmac) 420 struct GNUNET_HashCode *hmac)
421{ 421{
422 GNUNET_CRYPTO_hmac_raw ((void*) key->key, sizeof (key->key), 422 GNUNET_CRYPTO_hmac_raw((void*)key->key, sizeof(key->key),
423 plaintext, plaintext_len, 423 plaintext, plaintext_len,
424 hmac); 424 hmac);
425} 425}
426 426
427 427
428/** 428/**
429 * Context for cummulative hashing. 429 * Context for cummulative hashing.
430 */ 430 */
431struct GNUNET_HashContext 431struct GNUNET_HashContext {
432{
433 /** 432 /**
434 * Internal state of the hash function. 433 * Internal state of the hash function.
435 */ 434 */
@@ -443,19 +442,19 @@ struct GNUNET_HashContext
443 * @return context for incremental hash computation 442 * @return context for incremental hash computation
444 */ 443 */
445struct GNUNET_HashContext * 444struct GNUNET_HashContext *
446GNUNET_CRYPTO_hash_context_start () 445GNUNET_CRYPTO_hash_context_start()
447{ 446{
448 struct GNUNET_HashContext *hc; 447 struct GNUNET_HashContext *hc;
449 448
450 BENCHMARK_START (hash_context_start); 449 BENCHMARK_START(hash_context_start);
451 450
452 hc = GNUNET_new (struct GNUNET_HashContext); 451 hc = GNUNET_new(struct GNUNET_HashContext);
453 GNUNET_assert (0 == 452 GNUNET_assert(0 ==
454 gcry_md_open (&hc->hd, 453 gcry_md_open(&hc->hd,
455 GCRY_MD_SHA512, 454 GCRY_MD_SHA512,
456 0)); 455 0));
457 456
458 BENCHMARK_END (hash_context_start); 457 BENCHMARK_END(hash_context_start);
459 458
460 return hc; 459 return hc;
461} 460}
@@ -469,13 +468,13 @@ GNUNET_CRYPTO_hash_context_start ()
469 * @param size number of bytes in @a buf 468 * @param size number of bytes in @a buf
470 */ 469 */
471void 470void
472GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc, 471GNUNET_CRYPTO_hash_context_read(struct GNUNET_HashContext *hc,
473 const void *buf, 472 const void *buf,
474 size_t size) 473 size_t size)
475{ 474{
476 BENCHMARK_START (hash_context_read); 475 BENCHMARK_START(hash_context_read);
477 gcry_md_write (hc->hd, buf, size); 476 gcry_md_write(hc->hd, buf, size);
478 BENCHMARK_END (hash_context_read); 477 BENCHMARK_END(hash_context_read);
479} 478}
480 479
481 480
@@ -486,20 +485,20 @@ GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
486 * @param r_hash where to write the latest / final hash code 485 * @param r_hash where to write the latest / final hash code
487 */ 486 */
488void 487void
489GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc, 488GNUNET_CRYPTO_hash_context_finish(struct GNUNET_HashContext *hc,
490 struct GNUNET_HashCode *r_hash) 489 struct GNUNET_HashCode *r_hash)
491{ 490{
492 const void *res = gcry_md_read (hc->hd, 0); 491 const void *res = gcry_md_read(hc->hd, 0);
493 492
494 BENCHMARK_START (hash_context_finish); 493 BENCHMARK_START(hash_context_finish);
495 494
496 GNUNET_assert (NULL != res); 495 GNUNET_assert(NULL != res);
497 if (NULL != r_hash) 496 if (NULL != r_hash)
498 GNUNET_memcpy (r_hash, 497 GNUNET_memcpy(r_hash,
499 res, 498 res,
500 sizeof (struct GNUNET_HashCode)); 499 sizeof(struct GNUNET_HashCode));
501 GNUNET_CRYPTO_hash_context_abort (hc); 500 GNUNET_CRYPTO_hash_context_abort(hc);
502 BENCHMARK_END (hash_context_finish); 501 BENCHMARK_END(hash_context_finish);
503} 502}
504 503
505 504
@@ -509,10 +508,10 @@ GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
509 * @param hc hash context to destroy 508 * @param hc hash context to destroy
510 */ 509 */
511void 510void
512GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc) 511GNUNET_CRYPTO_hash_context_abort(struct GNUNET_HashContext *hc)
513{ 512{
514 gcry_md_close (hc->hd); 513 gcry_md_close(hc->hd);
515 GNUNET_free (hc); 514 GNUNET_free(hc);
516} 515}
517 516
518 517
diff --git a/src/util/crypto_hash_file.c b/src/util/crypto_hash_file.c
index 83afe5e91..78d0d0a0d 100644
--- a/src/util/crypto_hash_file.c
+++ b/src/util/crypto_hash_file.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/crypto_hash_file.c 22 * @file util/crypto_hash_file.c
23 * @brief incremental hashing of files 23 * @brief incremental hashing of files
@@ -27,17 +27,15 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28#include <gcrypt.h> 28#include <gcrypt.h>
29 29
30#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-hash-file", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-hash-file", __VA_ARGS__)
31 31
32#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-crypto-hash-file", syscall, filename) 32#define LOG_STRERROR_FILE(kind, syscall, filename) GNUNET_log_from_strerror_file(kind, "util-crypto-hash-file", syscall, filename)
33 33
34 34
35/** 35/**
36 * Context used when hashing a file. 36 * Context used when hashing a file.
37 */ 37 */
38struct GNUNET_CRYPTO_FileHashContext 38struct GNUNET_CRYPTO_FileHashContext {
39{
40
41 /** 39 /**
42 * Function to call upon completion. 40 * Function to call upon completion.
43 */ 41 */
@@ -92,7 +90,6 @@ struct GNUNET_CRYPTO_FileHashContext
92 * Blocksize. 90 * Blocksize.
93 */ 91 */
94 size_t bsize; 92 size_t bsize;
95
96}; 93};
97 94
98 95
@@ -101,15 +98,15 @@ struct GNUNET_CRYPTO_FileHashContext
101 * and free associated resources. 98 * and free associated resources.
102 */ 99 */
103static void 100static void
104file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc, 101file_hash_finish(struct GNUNET_CRYPTO_FileHashContext *fhc,
105 const struct GNUNET_HashCode * res) 102 const struct GNUNET_HashCode * res)
106{ 103{
107 fhc->callback (fhc->callback_cls, res); 104 fhc->callback(fhc->callback_cls, res);
108 GNUNET_free (fhc->filename); 105 GNUNET_free(fhc->filename);
109 if (!GNUNET_DISK_handle_invalid (fhc->fh)) 106 if (!GNUNET_DISK_handle_invalid(fhc->fh))
110 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_close (fhc->fh)); 107 GNUNET_break(GNUNET_OK == GNUNET_DISK_file_close(fhc->fh));
111 gcry_md_close (fhc->md); 108 gcry_md_close(fhc->md);
112 GNUNET_free (fhc); /* also frees fhc->buffer */ 109 GNUNET_free(fhc); /* also frees fhc->buffer */
113} 110}
114 111
115 112
@@ -119,7 +116,7 @@ file_hash_finish (struct GNUNET_CRYPTO_FileHashContext *fhc,
119 * @param cls closure 116 * @param cls closure
120 */ 117 */
121static void 118static void
122file_hash_task (void *cls) 119file_hash_task(void *cls)
123{ 120{
124 struct GNUNET_CRYPTO_FileHashContext *fhc = cls; 121 struct GNUNET_CRYPTO_FileHashContext *fhc = cls;
125 struct GNUNET_HashCode *res; 122 struct GNUNET_HashCode *res;
@@ -127,37 +124,37 @@ file_hash_task (void *cls)
127 ssize_t sret; 124 ssize_t sret;
128 125
129 fhc->task = NULL; 126 fhc->task = NULL;
130 GNUNET_assert (fhc->offset <= fhc->fsize); 127 GNUNET_assert(fhc->offset <= fhc->fsize);
131 delta = fhc->bsize; 128 delta = fhc->bsize;
132 if (fhc->fsize - fhc->offset < delta) 129 if (fhc->fsize - fhc->offset < delta)
133 delta = fhc->fsize - fhc->offset; 130 delta = fhc->fsize - fhc->offset;
134 sret = GNUNET_DISK_file_read (fhc->fh, 131 sret = GNUNET_DISK_file_read(fhc->fh,
135 fhc->buffer, 132 fhc->buffer,
136 delta); 133 delta);
137 if ( (sret < 0) || 134 if ((sret < 0) ||
138 (delta != (size_t) sret) ) 135 (delta != (size_t)sret))
139 { 136 {
140 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, 137 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING,
141 "read", 138 "read",
142 fhc->filename); 139 fhc->filename);
143 file_hash_finish (fhc, 140 file_hash_finish(fhc,
144 NULL); 141 NULL);
145 return; 142 return;
146 } 143 }
147 gcry_md_write (fhc->md, 144 gcry_md_write(fhc->md,
148 fhc->buffer, 145 fhc->buffer,
149 delta); 146 delta);
150 fhc->offset += delta; 147 fhc->offset += delta;
151 if (fhc->offset == fhc->fsize) 148 if (fhc->offset == fhc->fsize)
152 { 149 {
153 res = (struct GNUNET_HashCode *) gcry_md_read (fhc->md, 150 res = (struct GNUNET_HashCode *)gcry_md_read(fhc->md,
154 GCRY_MD_SHA512); 151 GCRY_MD_SHA512);
155 file_hash_finish (fhc, res); 152 file_hash_finish(fhc, res);
156 return; 153 return;
157 } 154 }
158 fhc->task = GNUNET_SCHEDULER_add_with_priority (fhc->priority, 155 fhc->task = GNUNET_SCHEDULER_add_with_priority(fhc->priority,
159 &file_hash_task, 156 &file_hash_task,
160 fhc); 157 fhc);
161} 158}
162 159
163 160
@@ -172,51 +169,51 @@ file_hash_task (void *cls)
172 * @return NULL on (immediate) errror 169 * @return NULL on (immediate) errror
173 */ 170 */
174struct GNUNET_CRYPTO_FileHashContext * 171struct GNUNET_CRYPTO_FileHashContext *
175GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority, 172GNUNET_CRYPTO_hash_file(enum GNUNET_SCHEDULER_Priority priority,
176 const char *filename, 173 const char *filename,
177 size_t blocksize, 174 size_t blocksize,
178 GNUNET_CRYPTO_HashCompletedCallback callback, 175 GNUNET_CRYPTO_HashCompletedCallback callback,
179 void *callback_cls) 176 void *callback_cls)
180{ 177{
181 struct GNUNET_CRYPTO_FileHashContext *fhc; 178 struct GNUNET_CRYPTO_FileHashContext *fhc;
182 179
183 GNUNET_assert (blocksize > 0); 180 GNUNET_assert(blocksize > 0);
184 fhc = 181 fhc =
185 GNUNET_malloc (sizeof (struct GNUNET_CRYPTO_FileHashContext) + blocksize); 182 GNUNET_malloc(sizeof(struct GNUNET_CRYPTO_FileHashContext) + blocksize);
186 fhc->callback = callback; 183 fhc->callback = callback;
187 fhc->callback_cls = callback_cls; 184 fhc->callback_cls = callback_cls;
188 fhc->buffer = (unsigned char *) &fhc[1]; 185 fhc->buffer = (unsigned char *)&fhc[1];
189 fhc->filename = GNUNET_strdup (filename); 186 fhc->filename = GNUNET_strdup(filename);
190 if (GPG_ERR_NO_ERROR != gcry_md_open (&fhc->md, GCRY_MD_SHA512, 0)) 187 if (GPG_ERR_NO_ERROR != gcry_md_open(&fhc->md, GCRY_MD_SHA512, 0))
191 { 188 {
192 GNUNET_break (0); 189 GNUNET_break(0);
193 GNUNET_free (fhc); 190 GNUNET_free(fhc);
194 return NULL; 191 return NULL;
195 } 192 }
196 fhc->bsize = blocksize; 193 fhc->bsize = blocksize;
197 if (GNUNET_OK != 194 if (GNUNET_OK !=
198 GNUNET_DISK_file_size (filename, 195 GNUNET_DISK_file_size(filename,
199 &fhc->fsize, 196 &fhc->fsize,
200 GNUNET_NO, 197 GNUNET_NO,
201 GNUNET_YES)) 198 GNUNET_YES))
202 { 199 {
203 GNUNET_free (fhc->filename); 200 GNUNET_free(fhc->filename);
204 GNUNET_free (fhc); 201 GNUNET_free(fhc);
205 return NULL; 202 return NULL;
206 } 203 }
207 fhc->fh = GNUNET_DISK_file_open (filename, 204 fhc->fh = GNUNET_DISK_file_open(filename,
208 GNUNET_DISK_OPEN_READ, 205 GNUNET_DISK_OPEN_READ,
209 GNUNET_DISK_PERM_NONE); 206 GNUNET_DISK_PERM_NONE);
210 if (! fhc->fh) 207 if (!fhc->fh)
211 { 208 {
212 GNUNET_free (fhc->filename); 209 GNUNET_free(fhc->filename);
213 GNUNET_free (fhc); 210 GNUNET_free(fhc);
214 return NULL; 211 return NULL;
215 } 212 }
216 fhc->priority = priority; 213 fhc->priority = priority;
217 fhc->task = GNUNET_SCHEDULER_add_with_priority (priority, 214 fhc->task = GNUNET_SCHEDULER_add_with_priority(priority,
218 &file_hash_task, 215 &file_hash_task,
219 fhc); 216 fhc);
220 return fhc; 217 return fhc;
221} 218}
222 219
@@ -227,13 +224,13 @@ GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
227 * @param fhc operation to cancel (callback must not yet have been invoked) 224 * @param fhc operation to cancel (callback must not yet have been invoked)
228 */ 225 */
229void 226void
230GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc) 227GNUNET_CRYPTO_hash_file_cancel(struct GNUNET_CRYPTO_FileHashContext *fhc)
231{ 228{
232 GNUNET_SCHEDULER_cancel (fhc->task); 229 GNUNET_SCHEDULER_cancel(fhc->task);
233 GNUNET_free (fhc->filename); 230 GNUNET_free(fhc->filename);
234 GNUNET_break (GNUNET_OK == 231 GNUNET_break(GNUNET_OK ==
235 GNUNET_DISK_file_close (fhc->fh)); 232 GNUNET_DISK_file_close(fhc->fh));
236 GNUNET_free (fhc); 233 GNUNET_free(fhc);
237} 234}
238 235
239/* end of crypto_hash_file.c */ 236/* end of crypto_hash_file.c */
diff --git a/src/util/crypto_hkdf.c b/src/util/crypto_hkdf.c
index 5ed22269f..58ae6c8ad 100644
--- a/src/util/crypto_hkdf.c
+++ b/src/util/crypto_hkdf.c
@@ -18,7 +18,7 @@
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE. 20 THE SOFTWARE.
21*/ 21 */
22 22
23/** 23/**
24 * @file src/util/crypto_hkdf.c 24 * @file src/util/crypto_hkdf.c
@@ -36,7 +36,7 @@
36 * - Matthias Wachs (08.10.2010) 36 * - Matthias Wachs (08.10.2010)
37 */ 37 */
38 38
39#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-hkdf", __VA_ARGS__) 39#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-hkdf", __VA_ARGS__)
40 40
41/** 41/**
42 * Set this to 0 if you compile this code outside of GNUnet. 42 * Set this to 0 if you compile this code outside of GNUnet.
@@ -75,13 +75,13 @@
75 * @return HMAC, freed by caller via gcry_md_close/_reset 75 * @return HMAC, freed by caller via gcry_md_close/_reset
76 */ 76 */
77static const void * 77static const void *
78doHMAC (gcry_md_hd_t mac, const void *key, size_t key_len, const void *buf, 78doHMAC(gcry_md_hd_t mac, const void *key, size_t key_len, const void *buf,
79 size_t buf_len) 79 size_t buf_len)
80{ 80{
81 gcry_md_setkey (mac, key, key_len); 81 gcry_md_setkey(mac, key, key_len);
82 gcry_md_write (mac, buf, buf_len); 82 gcry_md_write(mac, buf, buf_len);
83 83
84 return (const void *) gcry_md_read (mac, 0); 84 return (const void *)gcry_md_read(mac, 0);
85} 85}
86 86
87/** 87/**
@@ -95,15 +95,15 @@ doHMAC (gcry_md_hd_t mac, const void *key, size_t key_len, const void *buf,
95 * @return #GNUNET_YES on success 95 * @return #GNUNET_YES on success
96 */ 96 */
97static int 97static int
98getPRK (gcry_md_hd_t mac, const void *xts, size_t xts_len, const void *skm, 98getPRK(gcry_md_hd_t mac, const void *xts, size_t xts_len, const void *skm,
99 size_t skm_len, void *prk) 99 size_t skm_len, void *prk)
100{ 100{
101 const void *ret; 101 const void *ret;
102 102
103 ret = doHMAC (mac, xts, xts_len, skm, skm_len); 103 ret = doHMAC(mac, xts, xts_len, skm, skm_len);
104 if (ret == NULL) 104 if (ret == NULL)
105 return GNUNET_SYSERR; 105 return GNUNET_SYSERR;
106 GNUNET_memcpy (prk, ret, gcry_md_get_algo_dlen (gcry_md_get_algo (mac))); 106 GNUNET_memcpy(prk, ret, gcry_md_get_algo_dlen(gcry_md_get_algo(mac)));
107 107
108 return GNUNET_YES; 108 return GNUNET_YES;
109} 109}
@@ -111,16 +111,16 @@ getPRK (gcry_md_hd_t mac, const void *xts, size_t xts_len, const void *skm,
111 111
112#if DEBUG_HKDF 112#if DEBUG_HKDF
113static void 113static void
114dump (const char *src, const void *p, unsigned int l) 114dump(const char *src, const void *p, unsigned int l)
115{ 115{
116 unsigned int i; 116 unsigned int i;
117 117
118 printf ("\n%s: ", src); 118 printf("\n%s: ", src);
119 for (i = 0; i < l; i++) 119 for (i = 0; i < l; i++)
120 { 120 {
121 printf ("%2x", (int) ((const unsigned char *) p)[i]); 121 printf("%2x", (int)((const unsigned char *)p)[i]);
122 } 122 }
123 printf ("\n"); 123 printf("\n");
124} 124}
125#endif 125#endif
126 126
@@ -139,9 +139,9 @@ dump (const char *src, const void *p, unsigned int l)
139 * @return #GNUNET_YES on success 139 * @return #GNUNET_YES on success
140 */ 140 */
141int 141int
142GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo, 142GNUNET_CRYPTO_hkdf_v(void *result, size_t out_len, int xtr_algo, int prf_algo,
143 const void *xts, size_t xts_len, const void *skm, 143 const void *xts, size_t xts_len, const void *skm,
144 size_t skm_len, va_list argp) 144 size_t skm_len, va_list argp)
145{ 145{
146 gcry_md_hd_t xtr; 146 gcry_md_hd_t xtr;
147 gcry_md_hd_t prf; 147 gcry_md_hd_t prf;
@@ -149,39 +149,39 @@ GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
149 unsigned long i; 149 unsigned long i;
150 unsigned long t; 150 unsigned long t;
151 unsigned long d; 151 unsigned long d;
152 unsigned int k = gcry_md_get_algo_dlen (prf_algo); 152 unsigned int k = gcry_md_get_algo_dlen(prf_algo);
153 unsigned int xtr_len = gcry_md_get_algo_dlen (xtr_algo); 153 unsigned int xtr_len = gcry_md_get_algo_dlen(xtr_algo);
154 char prk[xtr_len]; 154 char prk[xtr_len];
155 int ret; 155 int ret;
156 size_t ctx_len; 156 size_t ctx_len;
157 va_list args; 157 va_list args;
158 158
159 BENCHMARK_START (hkdf); 159 BENCHMARK_START(hkdf);
160 160
161 if (0 == k) 161 if (0 == k)
162 return GNUNET_SYSERR; 162 return GNUNET_SYSERR;
163 if (GPG_ERR_NO_ERROR != 163 if (GPG_ERR_NO_ERROR !=
164 gcry_md_open (&xtr, xtr_algo, GCRY_MD_FLAG_HMAC)) 164 gcry_md_open(&xtr, xtr_algo, GCRY_MD_FLAG_HMAC))
165 return GNUNET_SYSERR; 165 return GNUNET_SYSERR;
166 if (GPG_ERR_NO_ERROR != 166 if (GPG_ERR_NO_ERROR !=
167 gcry_md_open (&prf, prf_algo, GCRY_MD_FLAG_HMAC)) 167 gcry_md_open(&prf, prf_algo, GCRY_MD_FLAG_HMAC))
168 { 168 {
169 gcry_md_close (xtr); 169 gcry_md_close(xtr);
170 return GNUNET_SYSERR; 170 return GNUNET_SYSERR;
171 } 171 }
172 va_copy (args, argp); 172 va_copy(args, argp);
173 173
174 ctx_len = 0; 174 ctx_len = 0;
175 while (NULL != va_arg (args, void *)) 175 while (NULL != va_arg(args, void *))
176 ctx_len += va_arg (args, size_t); 176 ctx_len += va_arg(args, size_t);
177 177
178 va_end (args); 178 va_end(args);
179 179
180 memset (result, 0, out_len); 180 memset(result, 0, out_len);
181 if (getPRK (xtr, xts, xts_len, skm, skm_len, prk) != GNUNET_YES) 181 if (getPRK(xtr, xts, xts_len, skm, skm_len, prk) != GNUNET_YES)
182 goto hkdf_error; 182 goto hkdf_error;
183#if DEBUG_HKDF 183#if DEBUG_HKDF
184 dump ("PRK", prk, xtr_len); 184 dump("PRK", prk, xtr_len);
185#endif 185#endif
186 186
187 t = out_len / k; 187 t = out_len / k;
@@ -195,69 +195,69 @@ GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
195 char *dst; 195 char *dst;
196 196
197 dst = plain + k; 197 dst = plain + k;
198 va_copy (args, argp); 198 va_copy(args, argp);
199 while ((ctx = va_arg (args, void *))) 199 while ((ctx = va_arg(args, void *)))
200 { 200 {
201 size_t len; 201 size_t len;
202 202
203 len = va_arg (args, size_t); 203 len = va_arg(args, size_t);
204 GNUNET_memcpy (dst, ctx, len); 204 GNUNET_memcpy(dst, ctx, len);
205 dst += len; 205 dst += len;
206 } 206 }
207 va_end (args); 207 va_end(args);
208 208
209 if (t > 0) 209 if (t > 0)
210 { 210 {
211 memset (plain + k + ctx_len, 1, 1); 211 memset(plain + k + ctx_len, 1, 1);
212#if DEBUG_HKDF 212#if DEBUG_HKDF
213 dump ("K(1)", plain, plain_len); 213 dump("K(1)", plain, plain_len);
214#endif 214#endif
215 hc = doHMAC (prf, prk, xtr_len, &plain[k], ctx_len + 1); 215 hc = doHMAC(prf, prk, xtr_len, &plain[k], ctx_len + 1);
216 if (hc == NULL) 216 if (hc == NULL)
217 goto hkdf_error; 217 goto hkdf_error;
218 GNUNET_memcpy (result, hc, k); 218 GNUNET_memcpy(result, hc, k);
219 result += k; 219 result += k;
220 } 220 }
221 221
222 /* K(i+1) */ 222 /* K(i+1) */
223 for (i = 1; i < t; i++) 223 for (i = 1; i < t; i++)
224 { 224 {
225 GNUNET_memcpy (plain, result - k, k); 225 GNUNET_memcpy(plain, result - k, k);
226 memset (plain + k + ctx_len, i + 1, 1); 226 memset(plain + k + ctx_len, i + 1, 1);
227 gcry_md_reset (prf); 227 gcry_md_reset(prf);
228#if DEBUG_HKDF 228#if DEBUG_HKDF
229 dump ("K(i+1)", plain, plain_len); 229 dump("K(i+1)", plain, plain_len);
230#endif 230#endif
231 hc = doHMAC (prf, prk, xtr_len, plain, plain_len); 231 hc = doHMAC(prf, prk, xtr_len, plain, plain_len);
232 if (hc == NULL) 232 if (hc == NULL)
233 goto hkdf_error; 233 goto hkdf_error;
234 GNUNET_memcpy (result, hc, k); 234 GNUNET_memcpy(result, hc, k);
235 result += k; 235 result += k;
236 } 236 }
237 237
238 /* K(t):d */ 238 /* K(t):d */
239 if (d > 0) 239 if (d > 0)
240 {
241 if (t > 0)
242 { 240 {
243 GNUNET_memcpy (plain, result - k, k); 241 if (t > 0)
244 i++; 242 {
245 } 243 GNUNET_memcpy(plain, result - k, k);
246 memset (plain + k + ctx_len, i, 1); 244 i++;
247 gcry_md_reset (prf); 245 }
246 memset(plain + k + ctx_len, i, 1);
247 gcry_md_reset(prf);
248#if DEBUG_HKDF 248#if DEBUG_HKDF
249 dump ("K(t):d", plain, plain_len); 249 dump("K(t):d", plain, plain_len);
250#endif 250#endif
251 if (t > 0) 251 if (t > 0)
252 hc = doHMAC (prf, prk, xtr_len, plain, plain_len); 252 hc = doHMAC(prf, prk, xtr_len, plain, plain_len);
253 else 253 else
254 hc = doHMAC (prf, prk, xtr_len, plain + k, plain_len - k); 254 hc = doHMAC(prf, prk, xtr_len, plain + k, plain_len - k);
255 if (hc == NULL) 255 if (hc == NULL)
256 goto hkdf_error; 256 goto hkdf_error;
257 GNUNET_memcpy (result, hc, d); 257 GNUNET_memcpy(result, hc, d);
258 } 258 }
259#if DEBUG_HKDF 259#if DEBUG_HKDF
260 dump ("result", result - k, out_len); 260 dump("result", result - k, out_len);
261#endif 261#endif
262 262
263 ret = GNUNET_YES; 263 ret = GNUNET_YES;
@@ -266,9 +266,9 @@ GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
266hkdf_error: 266hkdf_error:
267 ret = GNUNET_SYSERR; 267 ret = GNUNET_SYSERR;
268hkdf_ok: 268hkdf_ok:
269 gcry_md_close (xtr); 269 gcry_md_close(xtr);
270 gcry_md_close (prf); 270 gcry_md_close(prf);
271 BENCHMARK_END (hkdf); 271 BENCHMARK_END(hkdf);
272 return ret; 272 return ret;
273} 273}
274 274
@@ -286,18 +286,18 @@ hkdf_ok:
286 * @return #GNUNET_YES on success 286 * @return #GNUNET_YES on success
287 */ 287 */
288int 288int
289GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo, 289GNUNET_CRYPTO_hkdf(void *result, size_t out_len, int xtr_algo, int prf_algo,
290 const void *xts, size_t xts_len, const void *skm, 290 const void *xts, size_t xts_len, const void *skm,
291 size_t skm_len, ...) 291 size_t skm_len, ...)
292{ 292{
293 va_list argp; 293 va_list argp;
294 int ret; 294 int ret;
295 295
296 va_start (argp, skm_len); 296 va_start(argp, skm_len);
297 ret = 297 ret =
298 GNUNET_CRYPTO_hkdf_v (result, out_len, xtr_algo, prf_algo, xts, xts_len, 298 GNUNET_CRYPTO_hkdf_v(result, out_len, xtr_algo, prf_algo, xts, xts_len,
299 skm, skm_len, argp); 299 skm, skm_len, argp);
300 va_end (argp); 300 va_end(argp);
301 301
302 return ret; 302 return ret;
303} 303}
diff --git a/src/util/crypto_kdf.c b/src/util/crypto_kdf.c
index ac68ed7f1..ef96889b2 100644
--- a/src/util/crypto_kdf.c
+++ b/src/util/crypto_kdf.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/crypto_kdf.c 22 * @file src/util/crypto_kdf.c
@@ -30,7 +30,7 @@
30#include "platform.h" 30#include "platform.h"
31#include "gnunet_crypto_lib.h" 31#include "gnunet_crypto_lib.h"
32 32
33#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-kdf", __VA_ARGS__) 33#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-kdf", __VA_ARGS__)
34 34
35/** 35/**
36 * @brief Derive key 36 * @brief Derive key
@@ -44,13 +44,13 @@
44 * @return #GNUNET_YES on success 44 * @return #GNUNET_YES on success
45 */ 45 */
46int 46int
47GNUNET_CRYPTO_kdf_v (void *result, 47GNUNET_CRYPTO_kdf_v(void *result,
48 size_t out_len, 48 size_t out_len,
49 const void *xts, 49 const void *xts,
50 size_t xts_len, 50 size_t xts_len,
51 const void *skm, 51 const void *skm,
52 size_t skm_len, 52 size_t skm_len,
53 va_list argp) 53 va_list argp)
54{ 54{
55 /* 55 /*
56 * "Finally, we point out to a particularly advantageous instantiation using 56 * "Finally, we point out to a particularly advantageous instantiation using
@@ -64,15 +64,15 @@ GNUNET_CRYPTO_kdf_v (void *result,
64 * http://eprint.iacr.org/2010/264 64 * http://eprint.iacr.org/2010/264
65 */ 65 */
66 66
67 return GNUNET_CRYPTO_hkdf_v (result, 67 return GNUNET_CRYPTO_hkdf_v(result,
68 out_len, 68 out_len,
69 GCRY_MD_SHA512, 69 GCRY_MD_SHA512,
70 GCRY_MD_SHA256, 70 GCRY_MD_SHA256,
71 xts, 71 xts,
72 xts_len, 72 xts_len,
73 skm, 73 skm,
74 skm_len, 74 skm_len,
75 argp); 75 argp);
76} 76}
77 77
78 78
@@ -88,25 +88,25 @@ GNUNET_CRYPTO_kdf_v (void *result,
88 * @return #GNUNET_YES on success 88 * @return #GNUNET_YES on success
89 */ 89 */
90int 90int
91GNUNET_CRYPTO_kdf (void *result, 91GNUNET_CRYPTO_kdf(void *result,
92 size_t out_len, 92 size_t out_len,
93 const void *xts, 93 const void *xts,
94 size_t xts_len, 94 size_t xts_len,
95 const void *skm, 95 const void *skm,
96 size_t skm_len, ...) 96 size_t skm_len, ...)
97{ 97{
98 va_list argp; 98 va_list argp;
99 int ret; 99 int ret;
100 100
101 va_start (argp, skm_len); 101 va_start(argp, skm_len);
102 ret = GNUNET_CRYPTO_kdf_v (result, 102 ret = GNUNET_CRYPTO_kdf_v(result,
103 out_len, 103 out_len,
104 xts, 104 xts,
105 xts_len, 105 xts_len,
106 skm, 106 skm,
107 skm_len, 107 skm_len,
108 argp); 108 argp);
109 va_end (argp); 109 va_end(argp);
110 110
111 return ret; 111 return ret;
112} 112}
@@ -125,50 +125,50 @@ GNUNET_CRYPTO_kdf (void *result,
125 * @param ctx context string 125 * @param ctx context string
126 */ 126 */
127void 127void
128GNUNET_CRYPTO_kdf_mod_mpi (gcry_mpi_t *r, 128GNUNET_CRYPTO_kdf_mod_mpi(gcry_mpi_t *r,
129 gcry_mpi_t n, 129 gcry_mpi_t n,
130 const void *xts, size_t xts_len, 130 const void *xts, size_t xts_len,
131 const void *skm, size_t skm_len, 131 const void *skm, size_t skm_len,
132 const char *ctx) 132 const char *ctx)
133{ 133{
134 gcry_error_t rc; 134 gcry_error_t rc;
135 unsigned int nbits; 135 unsigned int nbits;
136 size_t rsize; 136 size_t rsize;
137 unsigned int ctr; 137 unsigned int ctr;
138 138
139 nbits = gcry_mpi_get_nbits (n); 139 nbits = gcry_mpi_get_nbits(n);
140 /* GNUNET_assert (nbits > 512); */ 140 /* GNUNET_assert (nbits > 512); */
141 141
142 ctr = 0; 142 ctr = 0;
143 while (1) 143 while (1)
144 { 144 {
145 /* Ain't clear if n is always divisible by 8 */ 145 /* Ain't clear if n is always divisible by 8 */
146 uint8_t buf[ (nbits-1)/8 + 1 ]; 146 uint8_t buf[ (nbits - 1) / 8 + 1 ];
147 147
148 rc = GNUNET_CRYPTO_kdf (buf, 148 rc = GNUNET_CRYPTO_kdf(buf,
149 sizeof (buf), 149 sizeof(buf),
150 xts, xts_len, 150 xts, xts_len,
151 skm, skm_len, 151 skm, skm_len,
152 ctx, strlen(ctx), 152 ctx, strlen(ctx),
153 &ctr, sizeof(ctr), 153 &ctr, sizeof(ctr),
154 NULL, 0); 154 NULL, 0);
155 GNUNET_assert (GNUNET_YES == rc); 155 GNUNET_assert(GNUNET_YES == rc);
156 156
157 rc = gcry_mpi_scan (r, 157 rc = gcry_mpi_scan(r,
158 GCRYMPI_FMT_USG, 158 GCRYMPI_FMT_USG,
159 (const unsigned char *) buf, 159 (const unsigned char *)buf,
160 sizeof (buf), 160 sizeof(buf),
161 &rsize); 161 &rsize);
162 GNUNET_assert (0 == rc); /* Allocation erro? */ 162 GNUNET_assert(0 == rc); /* Allocation erro? */
163 163
164 gcry_mpi_clear_highbit (*r, nbits); 164 gcry_mpi_clear_highbit(*r, nbits);
165 GNUNET_assert( 0 == gcry_mpi_test_bit (*r, nbits) ); 165 GNUNET_assert(0 == gcry_mpi_test_bit(*r, nbits));
166 ++ctr; 166 ++ctr;
167 /* We reject this FDH if either *r > n and retry with another ctr */ 167 /* We reject this FDH if either *r > n and retry with another ctr */
168 if (0 > gcry_mpi_cmp(*r, n)) 168 if (0 > gcry_mpi_cmp(*r, n))
169 break; 169 break;
170 gcry_mpi_release (*r); 170 gcry_mpi_release(*r);
171 } 171 }
172} 172}
173 173
174/* end of crypto_kdf.c */ 174/* end of crypto_kdf.c */
diff --git a/src/util/crypto_mpi.c b/src/util/crypto_mpi.c
index 14c672383..2c402e95a 100644
--- a/src/util/crypto_mpi.c
+++ b/src/util/crypto_mpi.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_mpi.c 22 * @file util/crypto_mpi.c
@@ -29,14 +29,14 @@
29#include "gnunet_crypto_lib.h" 29#include "gnunet_crypto_lib.h"
30 30
31 31
32#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-mpi", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-mpi", __VA_ARGS__)
33 33
34/** 34/**
35 * Log an error message at log-level 'level' that indicates 35 * Log an error message at log-level 'level' that indicates
36 * a failure of the command 'cmd' with the message given 36 * a failure of the command 'cmd' with the message given
37 * by gcry_strerror(rc). 37 * by gcry_strerror(rc).
38 */ 38 */
39#define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while(0) 39#define LOG_GCRY(level, cmd, rc) do { LOG(level, _("`%s' failed at %s:%d with error: %s\n"), cmd, __FILE__, __LINE__, gcry_strerror(rc)); } while (0)
40 40
41 41
42/** 42/**
@@ -48,17 +48,17 @@
48 * @param target target size of the buffer 48 * @param target target size of the buffer
49 */ 49 */
50static void 50static void
51adjust (void *buf, 51adjust(void *buf,
52 size_t size, 52 size_t size,
53 size_t target) 53 size_t target)
54{ 54{
55 char *p = buf; 55 char *p = buf;
56 56
57 if (size < target) 57 if (size < target)
58 { 58 {
59 memmove (&p[target - size], buf, size); 59 memmove(&p[target - size], buf, size);
60 memset (buf, 0, target - size); 60 memset(buf, 0, target - size);
61 } 61 }
62} 62}
63 63
64 64
@@ -72,46 +72,46 @@ adjust (void *buf,
72 * @param val value to write to @a buf 72 * @param val value to write to @a buf
73 */ 73 */
74void 74void
75GNUNET_CRYPTO_mpi_print_unsigned (void *buf, 75GNUNET_CRYPTO_mpi_print_unsigned(void *buf,
76 size_t size, 76 size_t size,
77 gcry_mpi_t val) 77 gcry_mpi_t val)
78{ 78{
79 size_t rsize; 79 size_t rsize;
80 int rc; 80 int rc;
81 81
82 if (gcry_mpi_get_flag (val, GCRYMPI_FLAG_OPAQUE)) 82 if (gcry_mpi_get_flag(val, GCRYMPI_FLAG_OPAQUE))
83 { 83 {
84 /* Store opaque MPIs left aligned into the buffer. */ 84 /* Store opaque MPIs left aligned into the buffer. */
85 unsigned int nbits; 85 unsigned int nbits;
86 const void *p; 86 const void *p;
87 87
88 p = gcry_mpi_get_opaque (val, &nbits); 88 p = gcry_mpi_get_opaque(val, &nbits);
89 GNUNET_assert (p); 89 GNUNET_assert(p);
90 rsize = (nbits+7)/8; 90 rsize = (nbits + 7) / 8;
91 if (rsize > size) 91 if (rsize > size)
92 rsize = size; 92 rsize = size;
93 GNUNET_memcpy (buf, p, rsize); 93 GNUNET_memcpy(buf, p, rsize);
94 if (rsize < size) 94 if (rsize < size)
95 memset (buf+rsize, 0, size - rsize); 95 memset(buf + rsize, 0, size - rsize);
96 } 96 }
97 else 97 else
98 {
99 /* Store regular MPIs as unsigned integers right aligned into
100 the buffer. */
101 rsize = size;
102 if (0 !=
103 (rc = gcry_mpi_print (GCRYMPI_FMT_USG,
104 buf,
105 rsize, &rsize,
106 val)))
107 { 98 {
108 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, 99 /* Store regular MPIs as unsigned integers right aligned into
109 "gcry_mpi_print", 100 the buffer. */
110 rc); 101 rsize = size;
111 GNUNET_assert (0); 102 if (0 !=
103 (rc = gcry_mpi_print(GCRYMPI_FMT_USG,
104 buf,
105 rsize, &rsize,
106 val)))
107 {
108 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR,
109 "gcry_mpi_print",
110 rc);
111 GNUNET_assert(0);
112 }
113 adjust(buf, rsize, size);
112 } 114 }
113 adjust (buf, rsize, size);
114 }
115} 115}
116 116
117 117
@@ -125,21 +125,21 @@ GNUNET_CRYPTO_mpi_print_unsigned (void *buf,
125 * @param size number of bytes in @a data 125 * @param size number of bytes in @a data
126 */ 126 */
127void 127void
128GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result, 128GNUNET_CRYPTO_mpi_scan_unsigned(gcry_mpi_t *result,
129 const void *data, 129 const void *data,
130 size_t size) 130 size_t size)
131{ 131{
132 int rc; 132 int rc;
133 133
134 if (0 != (rc = gcry_mpi_scan (result, 134 if (0 != (rc = gcry_mpi_scan(result,
135 GCRYMPI_FMT_USG, 135 GCRYMPI_FMT_USG,
136 data, size, &size))) 136 data, size, &size)))
137 { 137 {
138 LOG_GCRY (GNUNET_ERROR_TYPE_ERROR, 138 LOG_GCRY(GNUNET_ERROR_TYPE_ERROR,
139 "gcry_mpi_scan", 139 "gcry_mpi_scan",
140 rc); 140 rc);
141 GNUNET_assert (0); 141 GNUNET_assert(0);
142 } 142 }
143} 143}
144 144
145/* end of crypto_mpi.c */ 145/* end of crypto_mpi.c */
diff --git a/src/util/crypto_paillier.c b/src/util/crypto_paillier.c
index 622ce81fa..27a9af5de 100644
--- a/src/util/crypto_paillier.c
+++ b/src/util/crypto_paillier.c
@@ -11,7 +11,7 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
@@ -36,8 +36,8 @@
36 * @param[out] private_key Where to store the private key? 36 * @param[out] private_key Where to store the private key?
37 */ 37 */
38void 38void
39GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_key, 39GNUNET_CRYPTO_paillier_create(struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
40 struct GNUNET_CRYPTO_PaillierPrivateKey *private_key) 40 struct GNUNET_CRYPTO_PaillierPrivateKey *private_key)
41{ 41{
42 gcry_mpi_t p; 42 gcry_mpi_t p;
43 gcry_mpi_t q; 43 gcry_mpi_t q;
@@ -49,55 +49,56 @@ GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_ke
49 is executed more than once is very very low... */ 49 is executed more than once is very very low... */
50 p = NULL; 50 p = NULL;
51 q = NULL; 51 q = NULL;
52 do { 52 do
53 if (NULL != p) 53 {
54 gcry_mpi_release (p); 54 if (NULL != p)
55 if (NULL != q) 55 gcry_mpi_release(p);
56 gcry_mpi_release (q); 56 if (NULL != q)
57 GNUNET_assert (0 == 57 gcry_mpi_release(q);
58 gcry_prime_generate (&p, 58 GNUNET_assert(0 ==
59 gcry_prime_generate(&p,
59 GNUNET_CRYPTO_PAILLIER_BITS / 2, 60 GNUNET_CRYPTO_PAILLIER_BITS / 2,
60 0, NULL, NULL, NULL, 61 0, NULL, NULL, NULL,
61 GCRY_STRONG_RANDOM, 0)); 62 GCRY_STRONG_RANDOM, 0));
62 GNUNET_assert (0 == 63 GNUNET_assert(0 ==
63 gcry_prime_generate (&q, 64 gcry_prime_generate(&q,
64 GNUNET_CRYPTO_PAILLIER_BITS / 2, 65 GNUNET_CRYPTO_PAILLIER_BITS / 2,
65 0, NULL, NULL, NULL, 66 0, NULL, NULL, NULL,
66 GCRY_STRONG_RANDOM, 0)); 67 GCRY_STRONG_RANDOM, 0));
67 } 68 }
68 while (0 == gcry_mpi_cmp (p, q)); 69 while (0 == gcry_mpi_cmp(p, q));
69 /* n = p * q */ 70 /* n = p * q */
70 GNUNET_assert (NULL != (n = gcry_mpi_new (0))); 71 GNUNET_assert(NULL != (n = gcry_mpi_new(0)));
71 gcry_mpi_mul (n, 72 gcry_mpi_mul(n,
72 p, 73 p,
73 q); 74 q);
74 GNUNET_CRYPTO_mpi_print_unsigned (public_key, 75 GNUNET_CRYPTO_mpi_print_unsigned(public_key,
75 sizeof (struct GNUNET_CRYPTO_PaillierPublicKey), 76 sizeof(struct GNUNET_CRYPTO_PaillierPublicKey),
76 n); 77 n);
77 78
78 /* compute phi(n) = (p-1)(q-1) */ 79 /* compute phi(n) = (p-1)(q-1) */
79 GNUNET_assert (NULL != (phi = gcry_mpi_new (0))); 80 GNUNET_assert(NULL != (phi = gcry_mpi_new(0)));
80 gcry_mpi_sub_ui (p, p, 1); 81 gcry_mpi_sub_ui(p, p, 1);
81 gcry_mpi_sub_ui (q, q, 1); 82 gcry_mpi_sub_ui(q, q, 1);
82 gcry_mpi_mul (phi, p, q); 83 gcry_mpi_mul(phi, p, q);
83 gcry_mpi_release (p); 84 gcry_mpi_release(p);
84 gcry_mpi_release (q); 85 gcry_mpi_release(q);
85 86
86 /* lambda equals phi(n) in the simplified key generation */ 87 /* lambda equals phi(n) in the simplified key generation */
87 GNUNET_CRYPTO_mpi_print_unsigned (private_key->lambda, 88 GNUNET_CRYPTO_mpi_print_unsigned(private_key->lambda,
88 GNUNET_CRYPTO_PAILLIER_BITS / 8, 89 GNUNET_CRYPTO_PAILLIER_BITS / 8,
89 phi); 90 phi);
90 /* mu = phi^{-1} mod n, as we use g = n + 1 */ 91 /* mu = phi^{-1} mod n, as we use g = n + 1 */
91 GNUNET_assert (NULL != (mu = gcry_mpi_new (0))); 92 GNUNET_assert(NULL != (mu = gcry_mpi_new(0)));
92 GNUNET_assert (0 != gcry_mpi_invm (mu, 93 GNUNET_assert(0 != gcry_mpi_invm(mu,
93 phi, 94 phi,
94 n)); 95 n));
95 gcry_mpi_release (phi); 96 gcry_mpi_release(phi);
96 gcry_mpi_release (n); 97 gcry_mpi_release(n);
97 GNUNET_CRYPTO_mpi_print_unsigned (private_key->mu, 98 GNUNET_CRYPTO_mpi_print_unsigned(private_key->mu,
98 GNUNET_CRYPTO_PAILLIER_BITS / 8, 99 GNUNET_CRYPTO_PAILLIER_BITS / 8,
99 mu); 100 mu);
100 gcry_mpi_release (mu); 101 gcry_mpi_release(mu);
101} 102}
102 103
103 104
@@ -113,7 +114,7 @@ GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_ke
113 * or -1 if less than one homomorphic operation is possible 114 * or -1 if less than one homomorphic operation is possible
114 */ 115 */
115int 116int
116GNUNET_CRYPTO_paillier_encrypt1 (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, 117GNUNET_CRYPTO_paillier_encrypt1(const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
117 const gcry_mpi_t m, 118 const gcry_mpi_t m,
118 int desired_ops, 119 int desired_ops,
119 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext) 120 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext)
@@ -129,69 +130,70 @@ GNUNET_CRYPTO_paillier_encrypt1 (const struct GNUNET_CRYPTO_PaillierPublicKey *p
129 130
130 /* determine how many operations we could allow, if the other number 131 /* determine how many operations we could allow, if the other number
131 has the same length. */ 132 has the same length. */
132 GNUNET_assert (NULL != (tmp1 = gcry_mpi_set_ui (NULL, 1))); 133 GNUNET_assert(NULL != (tmp1 = gcry_mpi_set_ui(NULL, 1)));
133 GNUNET_assert (NULL != (tmp2 = gcry_mpi_set_ui (NULL, 2))); 134 GNUNET_assert(NULL != (tmp2 = gcry_mpi_set_ui(NULL, 2)));
134 gcry_mpi_mul_2exp (tmp1, tmp1, GNUNET_CRYPTO_PAILLIER_BITS); 135 gcry_mpi_mul_2exp(tmp1, tmp1, GNUNET_CRYPTO_PAILLIER_BITS);
135 136
136 /* count number of possible operations 137 /* count number of possible operations
137 this would be nicer with gcry_mpi_get_nbits, however it does not return 138 this would be nicer with gcry_mpi_get_nbits, however it does not return
138 the BITLENGTH of the given MPI's value, but the bits required 139 the BITLENGTH of the given MPI's value, but the bits required
139 to represent the number as MPI. */ 140 to represent the number as MPI. */
140 for (possible_opts = -2; gcry_mpi_cmp (tmp1, m) > 0; possible_opts++) 141 for (possible_opts = -2; gcry_mpi_cmp(tmp1, m) > 0; possible_opts++)
141 gcry_mpi_div (tmp1, NULL, tmp1, tmp2, 0); 142 gcry_mpi_div(tmp1, NULL, tmp1, tmp2, 0);
142 gcry_mpi_release (tmp1); 143 gcry_mpi_release(tmp1);
143 gcry_mpi_release (tmp2); 144 gcry_mpi_release(tmp2);
144 145
145 if (possible_opts < 1) 146 if (possible_opts < 1)
146 possible_opts = 0; 147 possible_opts = 0;
147 /* soft-cap by caller */ 148 /* soft-cap by caller */
148 possible_opts = (desired_ops < possible_opts)? desired_ops : possible_opts; 149 possible_opts = (desired_ops < possible_opts) ? desired_ops : possible_opts;
149 150
150 ciphertext->remaining_ops = htonl (possible_opts); 151 ciphertext->remaining_ops = htonl(possible_opts);
151 152
152 GNUNET_CRYPTO_mpi_scan_unsigned (&n, 153 GNUNET_CRYPTO_mpi_scan_unsigned(&n,
153 public_key, 154 public_key,
154 sizeof (struct GNUNET_CRYPTO_PaillierPublicKey)); 155 sizeof(struct GNUNET_CRYPTO_PaillierPublicKey));
155 highbit = GNUNET_CRYPTO_PAILLIER_BITS - 1; 156 highbit = GNUNET_CRYPTO_PAILLIER_BITS - 1;
156 while ( (! gcry_mpi_test_bit (n, highbit)) && 157 while ((!gcry_mpi_test_bit(n, highbit)) &&
157 (0 != highbit) ) 158 (0 != highbit))
158 highbit--; 159 highbit--;
159 if (0 == highbit) 160 if (0 == highbit)
160 { 161 {
161 /* invalid public key */ 162 /* invalid public key */
162 GNUNET_break_op (0); 163 GNUNET_break_op(0);
163 gcry_mpi_release (n); 164 gcry_mpi_release(n);
164 return GNUNET_SYSERR; 165 return GNUNET_SYSERR;
165 } 166 }
166 GNUNET_assert (0 != (n_square = gcry_mpi_new (0))); 167 GNUNET_assert(0 != (n_square = gcry_mpi_new(0)));
167 GNUNET_assert (0 != (r = gcry_mpi_new (0))); 168 GNUNET_assert(0 != (r = gcry_mpi_new(0)));
168 GNUNET_assert (0 != (c = gcry_mpi_new (0))); 169 GNUNET_assert(0 != (c = gcry_mpi_new(0)));
169 gcry_mpi_mul (n_square, n, n); 170 gcry_mpi_mul(n_square, n, n);
170 171
171 /* generate r < n (without bias) */ 172 /* generate r < n (without bias) */
172 do { 173 do
173 gcry_mpi_randomize (r, highbit + 1, GCRY_STRONG_RANDOM); 174 {
174 } 175 gcry_mpi_randomize(r, highbit + 1, GCRY_STRONG_RANDOM);
175 while (gcry_mpi_cmp (r, n) >= 0); 176 }
177 while (gcry_mpi_cmp(r, n) >= 0);
176 178
177 /* c = (n+1)^m mod n^2 */ 179 /* c = (n+1)^m mod n^2 */
178 /* c = n + 1 */ 180 /* c = n + 1 */
179 gcry_mpi_add_ui (c, n, 1); 181 gcry_mpi_add_ui(c, n, 1);
180 /* c = (n+1)^m mod n^2 */ 182 /* c = (n+1)^m mod n^2 */
181 gcry_mpi_powm (c, c, m, n_square); 183 gcry_mpi_powm(c, c, m, n_square);
182 /* r <- r^n mod n^2 */ 184 /* r <- r^n mod n^2 */
183 gcry_mpi_powm (r, r, n, n_square); 185 gcry_mpi_powm(r, r, n, n_square);
184 /* c <- r*c mod n^2 */ 186 /* c <- r*c mod n^2 */
185 gcry_mpi_mulm (c, r, c, n_square); 187 gcry_mpi_mulm(c, r, c, n_square);
186 188
187 GNUNET_CRYPTO_mpi_print_unsigned (ciphertext->bits, 189 GNUNET_CRYPTO_mpi_print_unsigned(ciphertext->bits,
188 sizeof ciphertext->bits, 190 sizeof ciphertext->bits,
189 c); 191 c);
190 192
191 gcry_mpi_release (n_square); 193 gcry_mpi_release(n_square);
192 gcry_mpi_release (n); 194 gcry_mpi_release(n);
193 gcry_mpi_release (r); 195 gcry_mpi_release(r);
194 gcry_mpi_release (c); 196 gcry_mpi_release(c);
195 197
196 return possible_opts; 198 return possible_opts;
197} 199}
@@ -209,10 +211,10 @@ GNUNET_CRYPTO_paillier_encrypt1 (const struct GNUNET_CRYPTO_PaillierPublicKey *p
209 * or -1 if less than one homomorphic operation is possible 211 * or -1 if less than one homomorphic operation is possible
210 */ 212 */
211int 213int
212GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, 214GNUNET_CRYPTO_paillier_encrypt(const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
213 const gcry_mpi_t m, 215 const gcry_mpi_t m,
214 int desired_ops, 216 int desired_ops,
215 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext) 217 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext)
216{ 218{
217 int possible_opts; 219 int possible_opts;
218 gcry_mpi_t n_square; 220 gcry_mpi_t n_square;
@@ -227,86 +229,87 @@ GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *pu
227 229
228 /* set max_num = 2^{GNUNET_CRYPTO_PAILLIER_BITS}, the largest 230 /* set max_num = 2^{GNUNET_CRYPTO_PAILLIER_BITS}, the largest
229 number we can have as a result */ 231 number we can have as a result */
230 GNUNET_assert (NULL != (max_num = gcry_mpi_set_ui (NULL, 1))); 232 GNUNET_assert(NULL != (max_num = gcry_mpi_set_ui(NULL, 1)));
231 gcry_mpi_mul_2exp (max_num, 233 gcry_mpi_mul_2exp(max_num,
232 max_num, 234 max_num,
233 GNUNET_CRYPTO_PAILLIER_BITS); 235 GNUNET_CRYPTO_PAILLIER_BITS);
234 236
235 /* Determine how many operations we could allow, assuming the other 237 /* Determine how many operations we could allow, assuming the other
236 number has the same length (or is smaller), by counting the 238 number has the same length (or is smaller), by counting the
237 number of possible operations. We essentially divide max_num by 239 number of possible operations. We essentially divide max_num by
238 2 until the result is no longer larger than 'm', incrementing the 240 2 until the result is no longer larger than 'm', incrementing the
239 maximum number of operations in each round, starting at -2 */ 241 maximum number of operations in each round, starting at -2 */
240 for (possible_opts = -2; gcry_mpi_cmp (max_num, m) > 0; possible_opts++) 242 for (possible_opts = -2; gcry_mpi_cmp(max_num, m) > 0; possible_opts++)
241 gcry_mpi_div (max_num, 243 gcry_mpi_div(max_num,
242 NULL, 244 NULL,
243 max_num, 245 max_num,
244 GCRYMPI_CONST_TWO, 246 GCRYMPI_CONST_TWO,
245 0); 247 0);
246 gcry_mpi_release (max_num); 248 gcry_mpi_release(max_num);
247 249
248 if (possible_opts < 1) 250 if (possible_opts < 1)
249 possible_opts = 0; 251 possible_opts = 0;
250 /* Enforce soft-cap by caller */ 252 /* Enforce soft-cap by caller */
251 possible_opts = GNUNET_MIN (desired_ops, possible_opts); 253 possible_opts = GNUNET_MIN(desired_ops, possible_opts);
252 ciphertext->remaining_ops = htonl (possible_opts); 254 ciphertext->remaining_ops = htonl(possible_opts);
253 255
254 GNUNET_CRYPTO_mpi_scan_unsigned (&n, 256 GNUNET_CRYPTO_mpi_scan_unsigned(&n,
255 public_key, 257 public_key,
256 sizeof (struct GNUNET_CRYPTO_PaillierPublicKey)); 258 sizeof(struct GNUNET_CRYPTO_PaillierPublicKey));
257 259
258 /* check public key for number of bits, bail out if key is all zeros */ 260 /* check public key for number of bits, bail out if key is all zeros */
259 highbit = GNUNET_CRYPTO_PAILLIER_BITS - 1; 261 highbit = GNUNET_CRYPTO_PAILLIER_BITS - 1;
260 while ( (! gcry_mpi_test_bit (n, highbit)) && 262 while ((!gcry_mpi_test_bit(n, highbit)) &&
261 (0 != highbit) ) 263 (0 != highbit))
262 highbit--; 264 highbit--;
263 if (0 == highbit) 265 if (0 == highbit)
264 { 266 {
265 /* invalid public key */ 267 /* invalid public key */
266 GNUNET_break_op (0); 268 GNUNET_break_op(0);
267 gcry_mpi_release (n); 269 gcry_mpi_release(n);
268 return GNUNET_SYSERR; 270 return GNUNET_SYSERR;
269 } 271 }
270 272
271 /* generate r < n (without bias) */ 273 /* generate r < n (without bias) */
272 GNUNET_assert (NULL != (r = gcry_mpi_new (0))); 274 GNUNET_assert(NULL != (r = gcry_mpi_new(0)));
273 do { 275 do
274 gcry_mpi_randomize (r, highbit + 1, GCRY_STRONG_RANDOM); 276 {
275 } 277 gcry_mpi_randomize(r, highbit + 1, GCRY_STRONG_RANDOM);
276 while (gcry_mpi_cmp (r, n) >= 0); 278 }
279 while (gcry_mpi_cmp(r, n) >= 0);
277 280
278 /* g = n + 1 */ 281 /* g = n + 1 */
279 GNUNET_assert (0 != (g = gcry_mpi_new (0))); 282 GNUNET_assert(0 != (g = gcry_mpi_new(0)));
280 gcry_mpi_add_ui (g, n, 1); 283 gcry_mpi_add_ui(g, n, 1);
281 284
282 /* n_square = n^2 */ 285 /* n_square = n^2 */
283 GNUNET_assert (0 != (n_square = gcry_mpi_new (0))); 286 GNUNET_assert(0 != (n_square = gcry_mpi_new(0)));
284 gcry_mpi_mul (n_square, 287 gcry_mpi_mul(n_square,
285 n, 288 n,
286 n); 289 n);
287 290
288 /* gm = g^m mod n^2 */ 291 /* gm = g^m mod n^2 */
289 GNUNET_assert (0 != (gm = gcry_mpi_new (0))); 292 GNUNET_assert(0 != (gm = gcry_mpi_new(0)));
290 gcry_mpi_powm (gm, g, m, n_square); 293 gcry_mpi_powm(gm, g, m, n_square);
291 gcry_mpi_release (g); 294 gcry_mpi_release(g);
292 295
293 /* rn <- r^n mod n^2 */ 296 /* rn <- r^n mod n^2 */
294 GNUNET_assert (0 != (rn = gcry_mpi_new (0))); 297 GNUNET_assert(0 != (rn = gcry_mpi_new(0)));
295 gcry_mpi_powm (rn, r, n, n_square); 298 gcry_mpi_powm(rn, r, n, n_square);
296 gcry_mpi_release (r); 299 gcry_mpi_release(r);
297 gcry_mpi_release (n); 300 gcry_mpi_release(n);
298 301
299 /* c <- rn * gm mod n^2 */ 302 /* c <- rn * gm mod n^2 */
300 GNUNET_assert (0 != (c = gcry_mpi_new (0))); 303 GNUNET_assert(0 != (c = gcry_mpi_new(0)));
301 gcry_mpi_mulm (c, rn, gm, n_square); 304 gcry_mpi_mulm(c, rn, gm, n_square);
302 gcry_mpi_release (n_square); 305 gcry_mpi_release(n_square);
303 gcry_mpi_release (gm); 306 gcry_mpi_release(gm);
304 gcry_mpi_release (rn); 307 gcry_mpi_release(rn);
305 308
306 GNUNET_CRYPTO_mpi_print_unsigned (ciphertext->bits, 309 GNUNET_CRYPTO_mpi_print_unsigned(ciphertext->bits,
307 sizeof (ciphertext->bits), 310 sizeof(ciphertext->bits),
308 c); 311 c);
309 gcry_mpi_release (c); 312 gcry_mpi_release(c);
310 313
311 return possible_opts; 314 return possible_opts;
312} 315}
@@ -321,10 +324,10 @@ GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *pu
321 * @param[out] m Decryption of @a ciphertext with @private_key. 324 * @param[out] m Decryption of @a ciphertext with @private_key.
322 */ 325 */
323void 326void
324GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key, 327GNUNET_CRYPTO_paillier_decrypt(const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key,
325 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, 328 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
326 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext, 329 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext,
327 gcry_mpi_t m) 330 gcry_mpi_t m)
328{ 331{
329 gcry_mpi_t mu; 332 gcry_mpi_t mu;
330 gcry_mpi_t lambda; 333 gcry_mpi_t lambda;
@@ -335,48 +338,48 @@ GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *p
335 gcry_mpi_t cmum1; 338 gcry_mpi_t cmum1;
336 gcry_mpi_t mod; 339 gcry_mpi_t mod;
337 340
338 GNUNET_CRYPTO_mpi_scan_unsigned (&lambda, 341 GNUNET_CRYPTO_mpi_scan_unsigned(&lambda,
339 private_key->lambda, 342 private_key->lambda,
340 sizeof (private_key->lambda)); 343 sizeof(private_key->lambda));
341 GNUNET_CRYPTO_mpi_scan_unsigned (&mu, 344 GNUNET_CRYPTO_mpi_scan_unsigned(&mu,
342 private_key->mu, 345 private_key->mu,
343 sizeof (private_key->mu)); 346 sizeof(private_key->mu));
344 GNUNET_CRYPTO_mpi_scan_unsigned (&n, 347 GNUNET_CRYPTO_mpi_scan_unsigned(&n,
345 public_key, 348 public_key,
346 sizeof (struct GNUNET_CRYPTO_PaillierPublicKey)); 349 sizeof(struct GNUNET_CRYPTO_PaillierPublicKey));
347 GNUNET_CRYPTO_mpi_scan_unsigned (&c, 350 GNUNET_CRYPTO_mpi_scan_unsigned(&c,
348 ciphertext->bits, 351 ciphertext->bits,
349 sizeof (ciphertext->bits)); 352 sizeof(ciphertext->bits));
350 353
351 /* n_square = n * n */ 354 /* n_square = n * n */
352 GNUNET_assert (0 != (n_square = gcry_mpi_new (0))); 355 GNUNET_assert(0 != (n_square = gcry_mpi_new(0)));
353 gcry_mpi_mul (n_square, n, n); 356 gcry_mpi_mul(n_square, n, n);
354 357
355 /* cmu = c^lambda mod n^2 */ 358 /* cmu = c^lambda mod n^2 */
356 GNUNET_assert (0 != (cmu = gcry_mpi_new (0))); 359 GNUNET_assert(0 != (cmu = gcry_mpi_new(0)));
357 gcry_mpi_powm (cmu, 360 gcry_mpi_powm(cmu,
358 c, 361 c,
359 lambda, 362 lambda,
360 n_square); 363 n_square);
361 gcry_mpi_release (n_square); 364 gcry_mpi_release(n_square);
362 gcry_mpi_release (lambda); 365 gcry_mpi_release(lambda);
363 gcry_mpi_release (c); 366 gcry_mpi_release(c);
364 367
365 /* cmum1 = cmu - 1 */ 368 /* cmum1 = cmu - 1 */
366 GNUNET_assert (0 != (cmum1 = gcry_mpi_new (0))); 369 GNUNET_assert(0 != (cmum1 = gcry_mpi_new(0)));
367 gcry_mpi_sub_ui (cmum1, cmu, 1); 370 gcry_mpi_sub_ui(cmum1, cmu, 1);
368 gcry_mpi_release (cmu); 371 gcry_mpi_release(cmu);
369 372
370 /* mod = cmum1 / n (mod n) */ 373 /* mod = cmum1 / n (mod n) */
371 GNUNET_assert (0 != (mod = gcry_mpi_new (0))); 374 GNUNET_assert(0 != (mod = gcry_mpi_new(0)));
372 gcry_mpi_div (mod, NULL, cmum1, n, 0); 375 gcry_mpi_div(mod, NULL, cmum1, n, 0);
373 gcry_mpi_release (cmum1); 376 gcry_mpi_release(cmum1);
374 377
375 /* m = mod * mu mod n */ 378 /* m = mod * mu mod n */
376 gcry_mpi_mulm (m, mod, mu, n); 379 gcry_mpi_mulm(m, mod, mu, n);
377 gcry_mpi_release (mod); 380 gcry_mpi_release(mod);
378 gcry_mpi_release (mu); 381 gcry_mpi_release(mu);
379 gcry_mpi_release (n); 382 gcry_mpi_release(n);
380} 383}
381 384
382 385
@@ -395,10 +398,10 @@ GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *p
395 * #GNUNET_SYSERR if no more homomorphic operations are remaining. 398 * #GNUNET_SYSERR if no more homomorphic operations are remaining.
396 */ 399 */
397int 400int
398GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key, 401GNUNET_CRYPTO_paillier_hom_add(const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
399 const struct GNUNET_CRYPTO_PaillierCiphertext *c1, 402 const struct GNUNET_CRYPTO_PaillierCiphertext *c1,
400 const struct GNUNET_CRYPTO_PaillierCiphertext *c2, 403 const struct GNUNET_CRYPTO_PaillierCiphertext *c2,
401 struct GNUNET_CRYPTO_PaillierCiphertext *result) 404 struct GNUNET_CRYPTO_PaillierCiphertext *result)
402{ 405{
403 gcry_mpi_t a; 406 gcry_mpi_t a;
404 gcry_mpi_t b; 407 gcry_mpi_t b;
@@ -408,42 +411,42 @@ GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierPublicKey *pu
408 int32_t o1; 411 int32_t o1;
409 int32_t o2; 412 int32_t o2;
410 413
411 o1 = (int32_t) ntohl (c1->remaining_ops); 414 o1 = (int32_t)ntohl(c1->remaining_ops);
412 o2 = (int32_t) ntohl (c2->remaining_ops); 415 o2 = (int32_t)ntohl(c2->remaining_ops);
413 if ( (0 >= o1) || (0 >= o2) ) 416 if ((0 >= o1) || (0 >= o2))
414 { 417 {
415 GNUNET_break_op (0); 418 GNUNET_break_op(0);
416 return GNUNET_SYSERR; 419 return GNUNET_SYSERR;
417 } 420 }
418 421
419 GNUNET_CRYPTO_mpi_scan_unsigned (&a, 422 GNUNET_CRYPTO_mpi_scan_unsigned(&a,
420 c1->bits, 423 c1->bits,
421 sizeof (c1->bits)); 424 sizeof(c1->bits));
422 GNUNET_CRYPTO_mpi_scan_unsigned (&b, 425 GNUNET_CRYPTO_mpi_scan_unsigned(&b,
423 c2->bits, 426 c2->bits,
424 sizeof (c2->bits)); 427 sizeof(c2->bits));
425 GNUNET_CRYPTO_mpi_scan_unsigned (&n, 428 GNUNET_CRYPTO_mpi_scan_unsigned(&n,
426 public_key, 429 public_key,
427 sizeof (struct GNUNET_CRYPTO_PaillierPublicKey)); 430 sizeof(struct GNUNET_CRYPTO_PaillierPublicKey));
428 431
429 /* n_square = n * n */ 432 /* n_square = n * n */
430 GNUNET_assert (0 != (n_square = gcry_mpi_new (0))); 433 GNUNET_assert(0 != (n_square = gcry_mpi_new(0)));
431 gcry_mpi_mul (n_square, n, n); 434 gcry_mpi_mul(n_square, n, n);
432 gcry_mpi_release (n); 435 gcry_mpi_release(n);
433 436
434 /* c = a * b mod n_square */ 437 /* c = a * b mod n_square */
435 GNUNET_assert (0 != (c = gcry_mpi_new (0))); 438 GNUNET_assert(0 != (c = gcry_mpi_new(0)));
436 gcry_mpi_mulm (c, a, b, n_square); 439 gcry_mpi_mulm(c, a, b, n_square);
437 gcry_mpi_release (n_square); 440 gcry_mpi_release(n_square);
438 gcry_mpi_release (a); 441 gcry_mpi_release(a);
439 gcry_mpi_release (b); 442 gcry_mpi_release(b);
440 443
441 result->remaining_ops = htonl (GNUNET_MIN (o1, o2) - 1); 444 result->remaining_ops = htonl(GNUNET_MIN(o1, o2) - 1);
442 GNUNET_CRYPTO_mpi_print_unsigned (result->bits, 445 GNUNET_CRYPTO_mpi_print_unsigned(result->bits,
443 sizeof (result->bits), 446 sizeof(result->bits),
444 c); 447 c);
445 gcry_mpi_release (c); 448 gcry_mpi_release(c);
446 return ntohl (result->remaining_ops); 449 return ntohl(result->remaining_ops);
447} 450}
448 451
449 452
@@ -454,10 +457,10 @@ GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierPublicKey *pu
454 * @return the number of remaining homomorphic operations 457 * @return the number of remaining homomorphic operations
455 */ 458 */
456int 459int
457GNUNET_CRYPTO_paillier_hom_get_remaining (const struct GNUNET_CRYPTO_PaillierCiphertext *c) 460GNUNET_CRYPTO_paillier_hom_get_remaining(const struct GNUNET_CRYPTO_PaillierCiphertext *c)
458{ 461{
459 GNUNET_assert (NULL != c); 462 GNUNET_assert(NULL != c);
460 return ntohl (c->remaining_ops); 463 return ntohl(c->remaining_ops);
461} 464}
462 465
463/* end of crypto_paillier.c */ 466/* end of crypto_paillier.c */
diff --git a/src/util/crypto_random.c b/src/util/crypto_random.c
index 58cab082e..d16ba2412 100644
--- a/src/util/crypto_random.c
+++ b/src/util/crypto_random.c
@@ -17,7 +17,7 @@
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21 21
22/** 22/**
23 * @file util/crypto_random.c 23 * @file util/crypto_random.c
@@ -28,23 +28,23 @@
28#include "gnunet_crypto_lib.h" 28#include "gnunet_crypto_lib.h"
29#include <gcrypt.h> 29#include <gcrypt.h>
30 30
31#define LOG(kind, ...) GNUNET_log_from (kind, "util-crypto-random", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-random", __VA_ARGS__)
32 32
33#define LOG_STRERROR(kind, syscall) \ 33#define LOG_STRERROR(kind, syscall) \
34 GNUNET_log_from_strerror (kind, "util-crypto-random", syscall) 34 GNUNET_log_from_strerror(kind, "util-crypto-random", syscall)
35 35
36 36
37/* TODO: ndurner, move this to plibc? */ 37/* TODO: ndurner, move this to plibc? */
38/* The code is derived from glibc, obviously */ 38/* The code is derived from glibc, obviously */
39#if ! HAVE_RANDOM || ! HAVE_SRANDOM 39#if !HAVE_RANDOM || !HAVE_SRANDOM
40#ifdef RANDOM 40#ifdef RANDOM
41#undef RANDOM 41#undef RANDOM
42#endif 42#endif
43#ifdef SRANDOM 43#ifdef SRANDOM
44#undef SRANDOM 44#undef SRANDOM
45#endif 45#endif
46#define RANDOM() glibc_weak_rand32 () 46#define RANDOM() glibc_weak_rand32()
47#define SRANDOM(s) glibc_weak_srand32 (s) 47#define SRANDOM(s) glibc_weak_srand32(s)
48#if defined(RAND_MAX) 48#if defined(RAND_MAX)
49#undef RAND_MAX 49#undef RAND_MAX
50#endif 50#endif
@@ -55,14 +55,14 @@ static int32_t glibc_weak_rand32_state = 1;
55 55
56 56
57void 57void
58glibc_weak_srand32 (int32_t s) 58glibc_weak_srand32(int32_t s)
59{ 59{
60 glibc_weak_rand32_state = s; 60 glibc_weak_rand32_state = s;
61} 61}
62 62
63 63
64int32_t 64int32_t
65glibc_weak_rand32 () 65glibc_weak_rand32()
66{ 66{
67 int32_t val = glibc_weak_rand32_state; 67 int32_t val = glibc_weak_rand32_state;
68 68
@@ -78,9 +78,9 @@ glibc_weak_rand32 ()
78 * @return number between 0 and 1. 78 * @return number between 0 and 1.
79 */ 79 */
80static double 80static double
81get_weak_random () 81get_weak_random()
82{ 82{
83 return ((double) random () / RAND_MAX); 83 return((double)random() / RAND_MAX);
84} 84}
85 85
86 86
@@ -91,9 +91,9 @@ get_weak_random ()
91 * @param seed the seed to use 91 * @param seed the seed to use
92 */ 92 */
93void 93void
94GNUNET_CRYPTO_seed_weak_random (int32_t seed) 94GNUNET_CRYPTO_seed_weak_random(int32_t seed)
95{ 95{
96 srandom (seed); 96 srandom(seed);
97} 97}
98 98
99 99
@@ -106,12 +106,12 @@ GNUNET_CRYPTO_seed_weak_random (int32_t seed)
106 * @param length buffer length 106 * @param length buffer length
107 */ 107 */
108void 108void
109GNUNET_CRYPTO_zero_keys (void *buffer, size_t length) 109GNUNET_CRYPTO_zero_keys(void *buffer, size_t length)
110{ 110{
111#if HAVE_MEMSET_S 111#if HAVE_MEMSET_S
112 memset_s (buffer, length, 0, length); 112 memset_s(buffer, length, 0, length);
113#elif HAVE_EXPLICIT_BZERO 113#elif HAVE_EXPLICIT_BZERO
114 explicit_bzero (buffer, length); 114 explicit_bzero(buffer, length);
115#else 115#else
116 volatile unsigned char *p = buffer; 116 volatile unsigned char *p = buffer;
117 while (length--) 117 while (length--)
@@ -129,37 +129,40 @@ GNUNET_CRYPTO_zero_keys (void *buffer, size_t length)
129 * @param length buffer length 129 * @param length buffer length
130 */ 130 */
131void 131void
132GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, 132GNUNET_CRYPTO_random_block(enum GNUNET_CRYPTO_Quality mode,
133 void *buffer, 133 void *buffer,
134 size_t length) 134 size_t length)
135{ 135{
136#ifdef gcry_fast_random_poll 136#ifdef gcry_fast_random_poll
137 static unsigned int invokeCount; 137 static unsigned int invokeCount;
138#endif 138#endif
139 switch (mode) 139 switch (mode)
140 { 140 {
141 case GNUNET_CRYPTO_QUALITY_STRONG: 141 case GNUNET_CRYPTO_QUALITY_STRONG:
142 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */ 142 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
143#ifdef gcry_fast_random_poll 143#ifdef gcry_fast_random_poll
144 if ((invokeCount++ % 256) == 0) 144 if ((invokeCount++ % 256) == 0)
145 gcry_fast_random_poll (); 145 gcry_fast_random_poll();
146#endif 146#endif
147 gcry_randomize (buffer, length, GCRY_STRONG_RANDOM); 147 gcry_randomize(buffer, length, GCRY_STRONG_RANDOM);
148 return; 148 return;
149 case GNUNET_CRYPTO_QUALITY_NONCE: 149
150 gcry_create_nonce (buffer, length); 150 case GNUNET_CRYPTO_QUALITY_NONCE:
151 return; 151 gcry_create_nonce(buffer, length);
152 case GNUNET_CRYPTO_QUALITY_WEAK: 152 return;
153 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */ 153
154 case GNUNET_CRYPTO_QUALITY_WEAK:
155 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
154#ifdef gcry_fast_random_poll 156#ifdef gcry_fast_random_poll
155 if ((invokeCount++ % 256) == 0) 157 if ((invokeCount++ % 256) == 0)
156 gcry_fast_random_poll (); 158 gcry_fast_random_poll();
157#endif 159#endif
158 gcry_randomize (buffer, length, GCRY_WEAK_RANDOM); 160 gcry_randomize(buffer, length, GCRY_WEAK_RANDOM);
159 return; 161 return;
160 default: 162
161 GNUNET_assert (0); 163 default:
162 } 164 GNUNET_assert(0);
165 }
163} 166}
164 167
165 168
@@ -171,7 +174,7 @@ GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode,
171 * @return a random value in the interval [0,i[. 174 * @return a random value in the interval [0,i[.
172 */ 175 */
173uint32_t 176uint32_t
174GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i) 177GNUNET_CRYPTO_random_u32(enum GNUNET_CRYPTO_Quality mode, uint32_t i)
175{ 178{
176#ifdef gcry_fast_random_poll 179#ifdef gcry_fast_random_poll
177 static unsigned int invokeCount; 180 static unsigned int invokeCount;
@@ -179,39 +182,44 @@ GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
179 uint32_t ret; 182 uint32_t ret;
180 uint32_t ul; 183 uint32_t ul;
181 184
182 GNUNET_assert (i > 0); 185 GNUNET_assert(i > 0);
183 186
184 switch (mode) 187 switch (mode)
185 { 188 {
186 case GNUNET_CRYPTO_QUALITY_STRONG: 189 case GNUNET_CRYPTO_QUALITY_STRONG:
187 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */ 190 /* see http://lists.gnupg.org/pipermail/gcrypt-devel/2004-May/000613.html */
188#ifdef gcry_fast_random_poll 191#ifdef gcry_fast_random_poll
189 if ((invokeCount++ % 256) == 0) 192 if ((invokeCount++ % 256) == 0)
190 gcry_fast_random_poll (); 193 gcry_fast_random_poll();
191#endif 194#endif
192 ul = UINT32_MAX - (UINT32_MAX % i); 195 ul = UINT32_MAX - (UINT32_MAX % i);
193 do 196 do
194 { 197 {
195 gcry_randomize ((unsigned char *) &ret, 198 gcry_randomize((unsigned char *)&ret,
196 sizeof (uint32_t), 199 sizeof(uint32_t),
197 GCRY_STRONG_RANDOM); 200 GCRY_STRONG_RANDOM);
198 } while (ret >= ul); 201 }
199 return ret % i; 202 while (ret >= ul);
200 case GNUNET_CRYPTO_QUALITY_NONCE: 203 return ret % i;
201 ul = UINT32_MAX - (UINT32_MAX % i); 204
202 do 205 case GNUNET_CRYPTO_QUALITY_NONCE:
203 { 206 ul = UINT32_MAX - (UINT32_MAX % i);
204 gcry_create_nonce (&ret, sizeof (ret)); 207 do
205 } while (ret >= ul); 208 {
206 return ret % i; 209 gcry_create_nonce(&ret, sizeof(ret));
207 case GNUNET_CRYPTO_QUALITY_WEAK: 210 }
208 ret = i * get_weak_random (); 211 while (ret >= ul);
209 if (ret >= i) 212 return ret % i;
210 ret = i - 1; 213
211 return ret; 214 case GNUNET_CRYPTO_QUALITY_WEAK:
212 default: 215 ret = i * get_weak_random();
213 GNUNET_assert (0); 216 if (ret >= i)
214 } 217 ret = i - 1;
218 return ret;
219
220 default:
221 GNUNET_assert(0);
222 }
215 return 0; 223 return 0;
216} 224}
217 225
@@ -225,24 +233,24 @@ GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i)
225 * @return the permutation array (allocated from heap) 233 * @return the permutation array (allocated from heap)
226 */ 234 */
227unsigned int * 235unsigned int *
228GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n) 236GNUNET_CRYPTO_random_permute(enum GNUNET_CRYPTO_Quality mode, unsigned int n)
229{ 237{
230 unsigned int *ret; 238 unsigned int *ret;
231 unsigned int i; 239 unsigned int i;
232 unsigned int tmp; 240 unsigned int tmp;
233 uint32_t x; 241 uint32_t x;
234 242
235 GNUNET_assert (n > 0); 243 GNUNET_assert(n > 0);
236 ret = GNUNET_malloc (n * sizeof (unsigned int)); 244 ret = GNUNET_malloc(n * sizeof(unsigned int));
237 for (i = 0; i < n; i++) 245 for (i = 0; i < n; i++)
238 ret[i] = i; 246 ret[i] = i;
239 for (i = n - 1; i > 0; i--) 247 for (i = n - 1; i > 0; i--)
240 { 248 {
241 x = GNUNET_CRYPTO_random_u32 (mode, i + 1); 249 x = GNUNET_CRYPTO_random_u32(mode, i + 1);
242 tmp = ret[x]; 250 tmp = ret[x];
243 ret[x] = ret[i]; 251 ret[x] = ret[i];
244 ret[i] = tmp; 252 ret[i] = tmp;
245 } 253 }
246 return ret; 254 return ret;
247} 255}
248 256
@@ -255,39 +263,44 @@ GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n)
255 * @return random 64-bit number 263 * @return random 64-bit number
256 */ 264 */
257uint64_t 265uint64_t
258GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max) 266GNUNET_CRYPTO_random_u64(enum GNUNET_CRYPTO_Quality mode, uint64_t max)
259{ 267{
260 uint64_t ret; 268 uint64_t ret;
261 uint64_t ul; 269 uint64_t ul;
262 270
263 GNUNET_assert (max > 0); 271 GNUNET_assert(max > 0);
264 switch (mode) 272 switch (mode)
265 {
266 case GNUNET_CRYPTO_QUALITY_STRONG:
267 ul = UINT64_MAX - (UINT64_MAX % max);
268 do
269 { 273 {
270 gcry_randomize ((unsigned char *) &ret, 274 case GNUNET_CRYPTO_QUALITY_STRONG:
271 sizeof (uint64_t), 275 ul = UINT64_MAX - (UINT64_MAX % max);
272 GCRY_STRONG_RANDOM); 276 do
273 } while (ret >= ul); 277 {
274 return ret % max; 278 gcry_randomize((unsigned char *)&ret,
275 case GNUNET_CRYPTO_QUALITY_NONCE: 279 sizeof(uint64_t),
276 ul = UINT64_MAX - (UINT64_MAX % max); 280 GCRY_STRONG_RANDOM);
277 do 281 }
278 { 282 while (ret >= ul);
279 gcry_create_nonce (&ret, sizeof (ret)); 283 return ret % max;
280 } while (ret >= ul); 284
281 285 case GNUNET_CRYPTO_QUALITY_NONCE:
282 return ret % max; 286 ul = UINT64_MAX - (UINT64_MAX % max);
283 case GNUNET_CRYPTO_QUALITY_WEAK: 287 do
284 ret = max * get_weak_random (); 288 {
285 if (ret >= max) 289 gcry_create_nonce(&ret, sizeof(ret));
286 ret = max - 1; 290 }
287 return ret; 291 while (ret >= ul);
288 default: 292
289 GNUNET_assert (0); 293 return ret % max;
290 } 294
295 case GNUNET_CRYPTO_QUALITY_WEAK:
296 ret = max * get_weak_random();
297 if (ret >= max)
298 ret = max - 1;
299 return ret;
300
301 default:
302 GNUNET_assert(0);
303 }
291 return 0; 304 return 0;
292} 305}
293 306
@@ -297,9 +310,9 @@ GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max)
297 * strategy of libgcrypt implementation. 310 * strategy of libgcrypt implementation.
298 */ 311 */
299static void * 312static void *
300w_malloc (size_t n) 313w_malloc(size_t n)
301{ 314{
302 return calloc (n, 1); 315 return calloc(n, 1);
303} 316}
304 317
305 318
@@ -308,9 +321,9 @@ w_malloc (size_t n)
308 * strategy of libgcrypt implementation. 321 * strategy of libgcrypt implementation.
309 */ 322 */
310static int 323static int
311w_check (const void *p) 324w_check(const void *p)
312{ 325{
313 (void) p; 326 (void)p;
314 return 0; /* not secure memory */ 327 return 0; /* not secure memory */
315} 328}
316 329
@@ -318,49 +331,49 @@ w_check (const void *p)
318/** 331/**
319 * Initialize libgcrypt. 332 * Initialize libgcrypt.
320 */ 333 */
321void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init () 334void __attribute__ ((constructor)) GNUNET_CRYPTO_random_init()
322{ 335{
323 gcry_error_t rc; 336 gcry_error_t rc;
324 337
325 if (! gcry_check_version (NEED_LIBGCRYPT_VERSION)) 338 if (!gcry_check_version(NEED_LIBGCRYPT_VERSION))
326 { 339 {
327 fprintf ( 340 fprintf(
328 stderr, 341 stderr,
329 _ ("libgcrypt has not the expected version (version %s is required).\n"), 342 _("libgcrypt has not the expected version (version %s is required).\n"),
330 NEED_LIBGCRYPT_VERSION); 343 NEED_LIBGCRYPT_VERSION);
331 GNUNET_assert (0); 344 GNUNET_assert(0);
332 } 345 }
333 /* set custom allocators */ 346 /* set custom allocators */
334 gcry_set_allocation_handler (&w_malloc, &w_malloc, &w_check, &realloc, &free); 347 gcry_set_allocation_handler(&w_malloc, &w_malloc, &w_check, &realloc, &free);
335 /* Disable use of secure memory */ 348 /* Disable use of secure memory */
336 if ((rc = gcry_control (GCRYCTL_DISABLE_SECMEM, 0))) 349 if ((rc = gcry_control(GCRYCTL_DISABLE_SECMEM, 0)))
337 fprintf (stderr, 350 fprintf(stderr,
338 "Failed to set libgcrypt option %s: %s\n", 351 "Failed to set libgcrypt option %s: %s\n",
339 "DISABLE_SECMEM", 352 "DISABLE_SECMEM",
340 gcry_strerror (rc)); 353 gcry_strerror(rc));
341 /* Otherwise gnunet-ecc takes forever to complete, besides 354 /* Otherwise gnunet-ecc takes forever to complete, besides
342 we are fine with "just" using GCRY_STRONG_RANDOM */ 355 we are fine with "just" using GCRY_STRONG_RANDOM */
343 if ((rc = gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0))) 356 if ((rc = gcry_control(GCRYCTL_ENABLE_QUICK_RANDOM, 0)))
344 fprintf (stderr, 357 fprintf(stderr,
345 "Failed to set libgcrypt option %s: %s\n", 358 "Failed to set libgcrypt option %s: %s\n",
346 "ENABLE_QUICK_RANDOM", 359 "ENABLE_QUICK_RANDOM",
347 gcry_strerror (rc)); 360 gcry_strerror(rc));
348 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0); 361 gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
349 gcry_fast_random_poll (); 362 gcry_fast_random_poll();
350 GNUNET_CRYPTO_seed_weak_random ( 363 GNUNET_CRYPTO_seed_weak_random(
351 time (NULL) ^ 364 time(NULL) ^
352 GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX)); 365 GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE, UINT32_MAX));
353} 366}
354 367
355 368
356/** 369/**
357 * Nicely shut down libgcrypt. 370 * Nicely shut down libgcrypt.
358 */ 371 */
359void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini () 372void __attribute__ ((destructor)) GNUNET_CRYPTO_random_fini()
360{ 373{
361 gcry_set_progress_handler (NULL, NULL); 374 gcry_set_progress_handler(NULL, NULL);
362#ifdef GCRYCTL_CLOSE_RANDOM_DEVICE 375#ifdef GCRYCTL_CLOSE_RANDOM_DEVICE
363 (void) gcry_control (GCRYCTL_CLOSE_RANDOM_DEVICE, 0); 376 (void)gcry_control(GCRYCTL_CLOSE_RANDOM_DEVICE, 0);
364#endif 377#endif
365} 378}
366 379
diff --git a/src/util/crypto_rsa.c b/src/util/crypto_rsa.c
index 8cb0fe6c6..0a20fdffa 100644
--- a/src/util/crypto_rsa.c
+++ b/src/util/crypto_rsa.c
@@ -1,22 +1,22 @@
1/* 1/*
2 This file is part of GNUnet 2 This file is part of GNUnet
3 Copyright (C) 2014,2016 GNUnet e.V. 3 Copyright (C) 2014,2016 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_rsa.c 22 * @file util/crypto_rsa.c
@@ -30,14 +30,13 @@
30#include "gnunet_crypto_lib.h" 30#include "gnunet_crypto_lib.h"
31#include "benchmark.h" 31#include "benchmark.h"
32 32
33#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-rsa", __VA_ARGS__) 33#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-rsa", __VA_ARGS__)
34 34
35 35
36/** 36/**
37 * The private information of an RSA key pair. 37 * The private information of an RSA key pair.
38 */ 38 */
39struct GNUNET_CRYPTO_RsaPrivateKey 39struct GNUNET_CRYPTO_RsaPrivateKey {
40{
41 /** 40 /**
42 * Libgcrypt S-expression for the RSA private key. 41 * Libgcrypt S-expression for the RSA private key.
43 */ 42 */
@@ -48,8 +47,7 @@ struct GNUNET_CRYPTO_RsaPrivateKey
48/** 47/**
49 * The public information of an RSA key pair. 48 * The public information of an RSA key pair.
50 */ 49 */
51struct GNUNET_CRYPTO_RsaPublicKey 50struct GNUNET_CRYPTO_RsaPublicKey {
52{
53 /** 51 /**
54 * Libgcrypt S-expression for the RSA public key. 52 * Libgcrypt S-expression for the RSA public key.
55 */ 53 */
@@ -60,8 +58,7 @@ struct GNUNET_CRYPTO_RsaPublicKey
60/** 58/**
61 * @brief an RSA signature 59 * @brief an RSA signature
62 */ 60 */
63struct GNUNET_CRYPTO_RsaSignature 61struct GNUNET_CRYPTO_RsaSignature {
64{
65 /** 62 /**
66 * Libgcrypt S-expression for the RSA signature. 63 * Libgcrypt S-expression for the RSA signature.
67 */ 64 */
@@ -72,8 +69,7 @@ struct GNUNET_CRYPTO_RsaSignature
72/** 69/**
73 * @brief RSA blinding key 70 * @brief RSA blinding key
74 */ 71 */
75struct RsaBlindingKey 72struct RsaBlindingKey {
76{
77 /** 73 /**
78 * Random value used for blinding. 74 * Random value used for blinding.
79 */ 75 */
@@ -91,50 +87,50 @@ struct RsaBlindingKey
91 * @return 0 on success 87 * @return 0 on success
92 */ 88 */
93static int 89static int
94key_from_sexp (gcry_mpi_t *array, 90key_from_sexp(gcry_mpi_t *array,
95 gcry_sexp_t sexp, 91 gcry_sexp_t sexp,
96 const char *topname, 92 const char *topname,
97 const char *elems) 93 const char *elems)
98{ 94{
99 gcry_sexp_t list; 95 gcry_sexp_t list;
100 gcry_sexp_t l2; 96 gcry_sexp_t l2;
101 const char *s; 97 const char *s;
102 unsigned int idx; 98 unsigned int idx;
103 99
104 if (! (list = gcry_sexp_find_token (sexp, topname, 0))) 100 if (!(list = gcry_sexp_find_token(sexp, topname, 0)))
105 return 1; 101 return 1;
106 l2 = gcry_sexp_cadr (list); 102 l2 = gcry_sexp_cadr(list);
107 gcry_sexp_release (list); 103 gcry_sexp_release(list);
108 list = l2; 104 list = l2;
109 if (! list) 105 if (!list)
110 return 2; 106 return 2;
111 idx = 0; 107 idx = 0;
112 for (s = elems; *s; s++, idx++) 108 for (s = elems; *s; s++, idx++)
113 {
114 if (! (l2 = gcry_sexp_find_token (list, s, 1)))
115 {
116 for (unsigned int i = 0; i < idx; i++)
117 {
118 gcry_free (array[i]);
119 array[i] = NULL;
120 }
121 gcry_sexp_release (list);
122 return 3; /* required parameter not found */
123 }
124 array[idx] = gcry_sexp_nth_mpi (l2, 1, GCRYMPI_FMT_USG);
125 gcry_sexp_release (l2);
126 if (! array[idx])
127 { 109 {
128 for (unsigned int i = 0; i < idx; i++) 110 if (!(l2 = gcry_sexp_find_token(list, s, 1)))
129 { 111 {
130 gcry_free (array[i]); 112 for (unsigned int i = 0; i < idx; i++)
131 array[i] = NULL; 113 {
132 } 114 gcry_free(array[i]);
133 gcry_sexp_release (list); 115 array[i] = NULL;
134 return 4; /* required parameter is invalid */ 116 }
117 gcry_sexp_release(list);
118 return 3; /* required parameter not found */
119 }
120 array[idx] = gcry_sexp_nth_mpi(l2, 1, GCRYMPI_FMT_USG);
121 gcry_sexp_release(l2);
122 if (!array[idx])
123 {
124 for (unsigned int i = 0; i < idx; i++)
125 {
126 gcry_free(array[i]);
127 array[i] = NULL;
128 }
129 gcry_sexp_release(list);
130 return 4; /* required parameter is invalid */
131 }
135 } 132 }
136 } 133 gcry_sexp_release(list);
137 gcry_sexp_release (list);
138 return 0; 134 return 0;
139} 135}
140 136
@@ -146,30 +142,30 @@ key_from_sexp (gcry_mpi_t *array,
146 * @return fresh private key 142 * @return fresh private key
147 */ 143 */
148struct GNUNET_CRYPTO_RsaPrivateKey * 144struct GNUNET_CRYPTO_RsaPrivateKey *
149GNUNET_CRYPTO_rsa_private_key_create (unsigned int len) 145GNUNET_CRYPTO_rsa_private_key_create(unsigned int len)
150{ 146{
151 struct GNUNET_CRYPTO_RsaPrivateKey *ret; 147 struct GNUNET_CRYPTO_RsaPrivateKey *ret;
152 gcry_sexp_t s_key; 148 gcry_sexp_t s_key;
153 gcry_sexp_t s_keyparam; 149 gcry_sexp_t s_keyparam;
154 150
155 BENCHMARK_START (rsa_private_key_create); 151 BENCHMARK_START(rsa_private_key_create);
156 152
157 GNUNET_assert (0 == 153 GNUNET_assert(0 ==
158 gcry_sexp_build (&s_keyparam, 154 gcry_sexp_build(&s_keyparam,
159 NULL, 155 NULL,
160 "(genkey(rsa(nbits %d)))", 156 "(genkey(rsa(nbits %d)))",
161 len)); 157 len));
162 GNUNET_assert (0 == 158 GNUNET_assert(0 ==
163 gcry_pk_genkey (&s_key, 159 gcry_pk_genkey(&s_key,
164 s_keyparam)); 160 s_keyparam));
165 gcry_sexp_release (s_keyparam); 161 gcry_sexp_release(s_keyparam);
166#if EXTRA_CHECKS 162#if EXTRA_CHECKS
167 GNUNET_assert (0 == 163 GNUNET_assert(0 ==
168 gcry_pk_testkey (s_key)); 164 gcry_pk_testkey(s_key));
169#endif 165#endif
170 ret = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey); 166 ret = GNUNET_new(struct GNUNET_CRYPTO_RsaPrivateKey);
171 ret->sexp = s_key; 167 ret->sexp = s_key;
172 BENCHMARK_END (rsa_private_key_create); 168 BENCHMARK_END(rsa_private_key_create);
173 return ret; 169 return ret;
174} 170}
175 171
@@ -180,10 +176,10 @@ GNUNET_CRYPTO_rsa_private_key_create (unsigned int len)
180 * @param key pointer to the memory to free 176 * @param key pointer to the memory to free
181 */ 177 */
182void 178void
183GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key) 179GNUNET_CRYPTO_rsa_private_key_free(struct GNUNET_CRYPTO_RsaPrivateKey *key)
184{ 180{
185 gcry_sexp_release (key->sexp); 181 gcry_sexp_release(key->sexp);
186 GNUNET_free (key); 182 GNUNET_free(key);
187} 183}
188 184
189 185
@@ -196,22 +192,22 @@ GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key)
196 * @return size of memory allocated in @a buffer 192 * @return size of memory allocated in @a buffer
197 */ 193 */
198size_t 194size_t
199GNUNET_CRYPTO_rsa_private_key_encode (const struct GNUNET_CRYPTO_RsaPrivateKey *key, 195GNUNET_CRYPTO_rsa_private_key_encode(const struct GNUNET_CRYPTO_RsaPrivateKey *key,
200 char **buffer) 196 char **buffer)
201{ 197{
202 size_t n; 198 size_t n;
203 char *b; 199 char *b;
204 200
205 n = gcry_sexp_sprint (key->sexp, 201 n = gcry_sexp_sprint(key->sexp,
206 GCRYSEXP_FMT_DEFAULT, 202 GCRYSEXP_FMT_DEFAULT,
207 NULL, 203 NULL,
208 0); 204 0);
209 b = GNUNET_malloc (n); 205 b = GNUNET_malloc(n);
210 GNUNET_assert ((n - 1) == /* since the last byte is \0 */ 206 GNUNET_assert((n - 1) == /* since the last byte is \0 */
211 gcry_sexp_sprint (key->sexp, 207 gcry_sexp_sprint(key->sexp,
212 GCRYSEXP_FMT_DEFAULT, 208 GCRYSEXP_FMT_DEFAULT,
213 b, 209 b,
214 n)); 210 n));
215 *buffer = b; 211 *buffer = b;
216 return n; 212 return n;
217} 213}
@@ -226,29 +222,30 @@ GNUNET_CRYPTO_rsa_private_key_encode (const struct GNUNET_CRYPTO_RsaPrivateKey *
226 * @return NULL on error 222 * @return NULL on error
227 */ 223 */
228struct GNUNET_CRYPTO_RsaPrivateKey * 224struct GNUNET_CRYPTO_RsaPrivateKey *
229GNUNET_CRYPTO_rsa_private_key_decode (const char *buf, 225GNUNET_CRYPTO_rsa_private_key_decode(const char *buf,
230 size_t len) 226 size_t len)
231{ 227{
232 struct GNUNET_CRYPTO_RsaPrivateKey *key; 228 struct GNUNET_CRYPTO_RsaPrivateKey *key;
233 key = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey); 229
230 key = GNUNET_new(struct GNUNET_CRYPTO_RsaPrivateKey);
234 if (0 != 231 if (0 !=
235 gcry_sexp_new (&key->sexp, 232 gcry_sexp_new(&key->sexp,
236 buf, 233 buf,
237 len, 234 len,
238 0)) 235 0))
239 { 236 {
240 LOG (GNUNET_ERROR_TYPE_WARNING, 237 LOG(GNUNET_ERROR_TYPE_WARNING,
241 "Decoded private key is not valid\n"); 238 "Decoded private key is not valid\n");
242 GNUNET_free (key); 239 GNUNET_free(key);
243 return NULL; 240 return NULL;
244 } 241 }
245 if (0 != gcry_pk_testkey (key->sexp)) 242 if (0 != gcry_pk_testkey(key->sexp))
246 { 243 {
247 LOG (GNUNET_ERROR_TYPE_WARNING, 244 LOG(GNUNET_ERROR_TYPE_WARNING,
248 "Decoded private key is not valid\n"); 245 "Decoded private key is not valid\n");
249 GNUNET_CRYPTO_rsa_private_key_free (key); 246 GNUNET_CRYPTO_rsa_private_key_free(key);
250 return NULL; 247 return NULL;
251 } 248 }
252 return key; 249 return key;
253} 250}
254 251
@@ -260,35 +257,35 @@ GNUNET_CRYPTO_rsa_private_key_decode (const char *buf,
260 * @retur NULL on error, otherwise the public key 257 * @retur NULL on error, otherwise the public key
261 */ 258 */
262struct GNUNET_CRYPTO_RsaPublicKey * 259struct GNUNET_CRYPTO_RsaPublicKey *
263GNUNET_CRYPTO_rsa_private_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey *priv) 260GNUNET_CRYPTO_rsa_private_key_get_public(const struct GNUNET_CRYPTO_RsaPrivateKey *priv)
264{ 261{
265 struct GNUNET_CRYPTO_RsaPublicKey *pub; 262 struct GNUNET_CRYPTO_RsaPublicKey *pub;
266 gcry_mpi_t ne[2]; 263 gcry_mpi_t ne[2];
267 int rc; 264 int rc;
268 gcry_sexp_t result; 265 gcry_sexp_t result;
269 266
270 BENCHMARK_START (rsa_private_key_get_public); 267 BENCHMARK_START(rsa_private_key_get_public);
271 268
272 rc = key_from_sexp (ne, priv->sexp, "public-key", "ne"); 269 rc = key_from_sexp(ne, priv->sexp, "public-key", "ne");
273 if (0 != rc) 270 if (0 != rc)
274 rc = key_from_sexp (ne, priv->sexp, "private-key", "ne"); 271 rc = key_from_sexp(ne, priv->sexp, "private-key", "ne");
275 if (0 != rc) 272 if (0 != rc)
276 rc = key_from_sexp (ne, priv->sexp, "rsa", "ne"); 273 rc = key_from_sexp(ne, priv->sexp, "rsa", "ne");
277 if (0 != rc) 274 if (0 != rc)
278 { 275 {
279 GNUNET_break_op (0); 276 GNUNET_break_op(0);
280 return NULL; 277 return NULL;
281 } 278 }
282 rc = gcry_sexp_build (&result, 279 rc = gcry_sexp_build(&result,
283 NULL, 280 NULL,
284 "(public-key(rsa(n %m)(e %m)))", 281 "(public-key(rsa(n %m)(e %m)))",
285 ne[0], 282 ne[0],
286 ne[1]); 283 ne[1]);
287 gcry_mpi_release (ne[0]); 284 gcry_mpi_release(ne[0]);
288 gcry_mpi_release (ne[1]); 285 gcry_mpi_release(ne[1]);
289 pub = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey); 286 pub = GNUNET_new(struct GNUNET_CRYPTO_RsaPublicKey);
290 pub->sexp = result; 287 pub->sexp = result;
291 BENCHMARK_END (rsa_private_key_get_public); 288 BENCHMARK_END(rsa_private_key_get_public);
292 return pub; 289 return pub;
293} 290}
294 291
@@ -299,10 +296,10 @@ GNUNET_CRYPTO_rsa_private_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateK
299 * @param key pointer to the memory to free 296 * @param key pointer to the memory to free
300 */ 297 */
301void 298void
302GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key) 299GNUNET_CRYPTO_rsa_public_key_free(struct GNUNET_CRYPTO_RsaPublicKey *key)
303{ 300{
304 gcry_sexp_release (key->sexp); 301 gcry_sexp_release(key->sexp);
305 GNUNET_free (key); 302 GNUNET_free(key);
306} 303}
307 304
308 305
@@ -315,22 +312,22 @@ GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key)
315 * @return size of memory allocated in @a buffer 312 * @return size of memory allocated in @a buffer
316 */ 313 */
317size_t 314size_t
318GNUNET_CRYPTO_rsa_public_key_encode (const struct GNUNET_CRYPTO_RsaPublicKey *key, 315GNUNET_CRYPTO_rsa_public_key_encode(const struct GNUNET_CRYPTO_RsaPublicKey *key,
319 char **buffer) 316 char **buffer)
320{ 317{
321 size_t n; 318 size_t n;
322 char *b; 319 char *b;
323 320
324 n = gcry_sexp_sprint (key->sexp, 321 n = gcry_sexp_sprint(key->sexp,
325 GCRYSEXP_FMT_ADVANCED, 322 GCRYSEXP_FMT_ADVANCED,
326 NULL, 323 NULL,
327 0); 324 0);
328 b = GNUNET_malloc (n); 325 b = GNUNET_malloc(n);
329 GNUNET_assert ((n -1) == /* since the last byte is \0 */ 326 GNUNET_assert((n - 1) == /* since the last byte is \0 */
330 gcry_sexp_sprint (key->sexp, 327 gcry_sexp_sprint(key->sexp,
331 GCRYSEXP_FMT_ADVANCED, 328 GCRYSEXP_FMT_ADVANCED,
332 b, 329 b,
333 n)); 330 n));
334 *buffer = b; 331 *buffer = b;
335 return n; 332 return n;
336} 333}
@@ -343,18 +340,18 @@ GNUNET_CRYPTO_rsa_public_key_encode (const struct GNUNET_CRYPTO_RsaPublicKey *ke
343 * @param hc where to store the hash code 340 * @param hc where to store the hash code
344 */ 341 */
345void 342void
346GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key, 343GNUNET_CRYPTO_rsa_public_key_hash(const struct GNUNET_CRYPTO_RsaPublicKey *key,
347 struct GNUNET_HashCode *hc) 344 struct GNUNET_HashCode *hc)
348{ 345{
349 char *buf; 346 char *buf;
350 size_t buf_size; 347 size_t buf_size;
351 348
352 buf_size = GNUNET_CRYPTO_rsa_public_key_encode (key, 349 buf_size = GNUNET_CRYPTO_rsa_public_key_encode(key,
353 &buf); 350 &buf);
354 GNUNET_CRYPTO_hash (buf, 351 GNUNET_CRYPTO_hash(buf,
355 buf_size, 352 buf_size,
356 hc); 353 hc);
357 GNUNET_free (buf); 354 GNUNET_free(buf);
358} 355}
359 356
360 357
@@ -367,37 +364,37 @@ GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key,
367 * @return NULL on error 364 * @return NULL on error
368 */ 365 */
369struct GNUNET_CRYPTO_RsaPublicKey * 366struct GNUNET_CRYPTO_RsaPublicKey *
370GNUNET_CRYPTO_rsa_public_key_decode (const char *buf, 367GNUNET_CRYPTO_rsa_public_key_decode(const char *buf,
371 size_t len) 368 size_t len)
372{ 369{
373 struct GNUNET_CRYPTO_RsaPublicKey *key; 370 struct GNUNET_CRYPTO_RsaPublicKey *key;
374 gcry_mpi_t n; 371 gcry_mpi_t n;
375 int ret; 372 int ret;
376 373
377 key = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey); 374 key = GNUNET_new(struct GNUNET_CRYPTO_RsaPublicKey);
378 if (0 != 375 if (0 !=
379 gcry_sexp_new (&key->sexp, 376 gcry_sexp_new(&key->sexp,
380 buf, 377 buf,
381 len, 378 len,
382 0)) 379 0))
383 { 380 {
384 GNUNET_break_op (0); 381 GNUNET_break_op(0);
385 GNUNET_free (key); 382 GNUNET_free(key);
386 return NULL; 383 return NULL;
387 } 384 }
388 /* verify that this is an RSA public key */ 385 /* verify that this is an RSA public key */
389 ret = key_from_sexp (&n, key->sexp, "public-key", "n"); 386 ret = key_from_sexp(&n, key->sexp, "public-key", "n");
390 if (0 != ret) 387 if (0 != ret)
391 ret = key_from_sexp (&n, key->sexp, "rsa", "n"); 388 ret = key_from_sexp(&n, key->sexp, "rsa", "n");
392 if (0 != ret) 389 if (0 != ret)
393 { 390 {
394 /* this is no public RSA key */ 391 /* this is no public RSA key */
395 GNUNET_break (0); 392 GNUNET_break(0);
396 gcry_sexp_release (key->sexp); 393 gcry_sexp_release(key->sexp);
397 GNUNET_free (key); 394 GNUNET_free(key);
398 return NULL; 395 return NULL;
399 } 396 }
400 gcry_mpi_release (n); 397 gcry_mpi_release(n);
401 return key; 398 return key;
402} 399}
403 400
@@ -419,9 +416,9 @@ rsa_gcd_validate(gcry_mpi_t r, gcry_mpi_t n)
419 gcry_mpi_t g; 416 gcry_mpi_t g;
420 int t; 417 int t;
421 418
422 g = gcry_mpi_new (0); 419 g = gcry_mpi_new(0);
423 t = gcry_mpi_gcd(g,r,n); 420 t = gcry_mpi_gcd(g, r, n);
424 gcry_mpi_release (g); 421 gcry_mpi_release(g);
425 return t; 422 return t;
426} 423}
427 424
@@ -434,77 +431,78 @@ rsa_gcd_validate(gcry_mpi_t r, gcry_mpi_t n)
434 * @return the newly created blinding key, NULL if RSA key is malicious 431 * @return the newly created blinding key, NULL if RSA key is malicious
435 */ 432 */
436static struct RsaBlindingKey * 433static struct RsaBlindingKey *
437rsa_blinding_key_derive (const struct GNUNET_CRYPTO_RsaPublicKey *pkey, 434rsa_blinding_key_derive(const struct GNUNET_CRYPTO_RsaPublicKey *pkey,
438 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks) 435 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks)
439{ 436{
440 char *xts = "Blinding KDF extrator HMAC key"; /* Trusts bks' randomness more */ 437 char *xts = "Blinding KDF extrator HMAC key"; /* Trusts bks' randomness more */
441 struct RsaBlindingKey *blind; 438 struct RsaBlindingKey *blind;
442 gcry_mpi_t n; 439 gcry_mpi_t n;
443 440
444 blind = GNUNET_new (struct RsaBlindingKey); 441 blind = GNUNET_new(struct RsaBlindingKey);
445 GNUNET_assert( NULL != blind ); 442 GNUNET_assert(NULL != blind);
446 443
447 /* Extract the composite n from the RSA public key */ 444 /* Extract the composite n from the RSA public key */
448 GNUNET_assert( 0 == key_from_sexp (&n, pkey->sexp, "rsa", "n") ); 445 GNUNET_assert(0 == key_from_sexp(&n, pkey->sexp, "rsa", "n"));
449 /* Assert that it at least looks like an RSA key */ 446 /* Assert that it at least looks like an RSA key */
450 GNUNET_assert( 0 == gcry_mpi_get_flag(n, GCRYMPI_FLAG_OPAQUE) ); 447 GNUNET_assert(0 == gcry_mpi_get_flag(n, GCRYMPI_FLAG_OPAQUE));
451 448
452 GNUNET_CRYPTO_kdf_mod_mpi (&blind->r, 449 GNUNET_CRYPTO_kdf_mod_mpi(&blind->r,
453 n, 450 n,
454 xts, strlen(xts), 451 xts, strlen(xts),
455 bks, sizeof(*bks), 452 bks, sizeof(*bks),
456 "Blinding KDF"); 453 "Blinding KDF");
457 if (0 == rsa_gcd_validate(blind->r, n)) { 454 if (0 == rsa_gcd_validate(blind->r, n))
458 GNUNET_free (blind); 455 {
459 blind = NULL; 456 GNUNET_free(blind);
460 } 457 blind = NULL;
461 458 }
462 gcry_mpi_release (n); 459
460 gcry_mpi_release(n);
463 return blind; 461 return blind;
464} 462}
465 463
466 464
467/* 465/*
468We originally added GNUNET_CRYPTO_kdf_mod_mpi for the benifit of the 466 We originally added GNUNET_CRYPTO_kdf_mod_mpi for the benifit of the
469previous routine. 467 previous routine.
470 468
471There was previously a call to GNUNET_CRYPTO_kdf in 469 There was previously a call to GNUNET_CRYPTO_kdf in
472 bkey = rsa_blinding_key_derive (len, bks); 470 bkey = rsa_blinding_key_derive (len, bks);
473that gives exactly len bits where 471 that gives exactly len bits where
474 len = GNUNET_CRYPTO_rsa_public_key_len (pkey); 472 len = GNUNET_CRYPTO_rsa_public_key_len (pkey);
475 473
476Now r = 2^(len-1)/pkey.n is the probability that a set high bit being 474 Now r = 2^(len-1)/pkey.n is the probability that a set high bit being
477okay, meaning bkey < pkey.n. It follows that (1-r)/2 of the time bkey > 475 okay, meaning bkey < pkey.n. It follows that (1-r)/2 of the time bkey >
478pkey.n making the effective bkey be 476 pkey.n making the effective bkey be
479 bkey mod pkey.n = bkey - pkey.n 477 bkey mod pkey.n = bkey - pkey.n
480so the effective bkey has its high bit set with probability r/2. 478 so the effective bkey has its high bit set with probability r/2.
481 479
482We expect r to be close to 1/2 if the exchange is honest, but the 480 We expect r to be close to 1/2 if the exchange is honest, but the
483exchange can choose r otherwise. 481 exchange can choose r otherwise.
484 482
485In blind signing, the exchange sees 483 In blind signing, the exchange sees
486 B = bkey * S mod pkey.n 484 B = bkey * S mod pkey.n
487On deposit, the exchange sees S so they can compute bkey' = B/S mod 485 On deposit, the exchange sees S so they can compute bkey' = B/S mod
488pkey.n for all B they recorded to see if bkey' has it's high bit set. 486 pkey.n for all B they recorded to see if bkey' has it's high bit set.
489Also, note the exchange can compute 1/S efficiently since they know the 487 Also, note the exchange can compute 1/S efficiently since they know the
490factors of pkey.n. 488 factors of pkey.n.
491 489
492I suppose that happens with probability r/(1+r) if its the wrong B, not 490 I suppose that happens with probability r/(1+r) if its the wrong B, not
493completely sure. If otoh we've the right B, then we've the probability 491 completely sure. If otoh we've the right B, then we've the probability
494r/2 of a set high bit in the effective bkey. 492 r/2 of a set high bit in the effective bkey.
495 493
496Interestingly, r^2-r has a maximum at the default r=1/2 anyways, giving 494 Interestingly, r^2-r has a maximum at the default r=1/2 anyways, giving
497the wrong and right probabilities 1/3 and 1/4, respectively. 495 the wrong and right probabilities 1/3 and 1/4, respectively.
498 496
499I feared this gives the exchange a meaningful fraction of a bit of 497 I feared this gives the exchange a meaningful fraction of a bit of
500information per coin involved in the transaction. It sounds damaging if 498 information per coin involved in the transaction. It sounds damaging if
501numerous coins were involved. And it could run across transactions in 499 numerous coins were involved. And it could run across transactions in
502some scenarios. 500 some scenarios.
503 501
504We fixed this by using a more uniform deterministic pseudo-random number 502 We fixed this by using a more uniform deterministic pseudo-random number
505generator for blinding factors. I do not believe this to be a problem 503 generator for blinding factors. I do not believe this to be a problem
506for the rsa_full_domain_hash routine, but better safe than sorry. 504 for the rsa_full_domain_hash routine, but better safe than sorry.
507*/ 505 */
508 506
509 507
510/** 508/**
@@ -515,8 +513,8 @@ for the rsa_full_domain_hash routine, but better safe than sorry.
515 * @return 0 if the two are equal 513 * @return 0 if the two are equal
516 */ 514 */
517int 515int
518GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1, 516GNUNET_CRYPTO_rsa_signature_cmp(struct GNUNET_CRYPTO_RsaSignature *s1,
519 struct GNUNET_CRYPTO_RsaSignature *s2) 517 struct GNUNET_CRYPTO_RsaSignature *s2)
520{ 518{
521 char *b1; 519 char *b1;
522 char *b2; 520 char *b2;
@@ -524,18 +522,18 @@ GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1,
524 size_t z2; 522 size_t z2;
525 int ret; 523 int ret;
526 524
527 z1 = GNUNET_CRYPTO_rsa_signature_encode (s1, 525 z1 = GNUNET_CRYPTO_rsa_signature_encode(s1,
528 &b1); 526 &b1);
529 z2 = GNUNET_CRYPTO_rsa_signature_encode (s2, 527 z2 = GNUNET_CRYPTO_rsa_signature_encode(s2,
530 &b2); 528 &b2);
531 if (z1 != z2) 529 if (z1 != z2)
532 ret = 1; 530 ret = 1;
533 else 531 else
534 ret = memcmp (b1, 532 ret = memcmp(b1,
535 b2, 533 b2,
536 z1); 534 z1);
537 GNUNET_free (b1); 535 GNUNET_free(b1);
538 GNUNET_free (b2); 536 GNUNET_free(b2);
539 return ret; 537 return ret;
540} 538}
541 539
@@ -548,8 +546,8 @@ GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1,
548 * @return 0 if the two are equal 546 * @return 0 if the two are equal
549 */ 547 */
550int 548int
551GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1, 549GNUNET_CRYPTO_rsa_public_key_cmp(struct GNUNET_CRYPTO_RsaPublicKey *p1,
552 struct GNUNET_CRYPTO_RsaPublicKey *p2) 550 struct GNUNET_CRYPTO_RsaPublicKey *p2)
553{ 551{
554 char *b1; 552 char *b1;
555 char *b2; 553 char *b2;
@@ -557,18 +555,18 @@ GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1,
557 size_t z2; 555 size_t z2;
558 int ret; 556 int ret;
559 557
560 z1 = GNUNET_CRYPTO_rsa_public_key_encode (p1, 558 z1 = GNUNET_CRYPTO_rsa_public_key_encode(p1,
561 &b1); 559 &b1);
562 z2 = GNUNET_CRYPTO_rsa_public_key_encode (p2, 560 z2 = GNUNET_CRYPTO_rsa_public_key_encode(p2,
563 &b2); 561 &b2);
564 if (z1 != z2) 562 if (z1 != z2)
565 ret = 1; 563 ret = 1;
566 else 564 else
567 ret = memcmp (b1, 565 ret = memcmp(b1,
568 b2, 566 b2,
569 z1); 567 z1);
570 GNUNET_free (b1); 568 GNUNET_free(b1);
571 GNUNET_free (b2); 569 GNUNET_free(b2);
572 return ret; 570 return ret;
573} 571}
574 572
@@ -581,8 +579,8 @@ GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1,
581 * @return 0 if the two are equal 579 * @return 0 if the two are equal
582 */ 580 */
583int 581int
584GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1, 582GNUNET_CRYPTO_rsa_private_key_cmp(struct GNUNET_CRYPTO_RsaPrivateKey *p1,
585 struct GNUNET_CRYPTO_RsaPrivateKey *p2) 583 struct GNUNET_CRYPTO_RsaPrivateKey *p2)
586{ 584{
587 char *b1; 585 char *b1;
588 char *b2; 586 char *b2;
@@ -590,18 +588,18 @@ GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1,
590 size_t z2; 588 size_t z2;
591 int ret; 589 int ret;
592 590
593 z1 = GNUNET_CRYPTO_rsa_private_key_encode (p1, 591 z1 = GNUNET_CRYPTO_rsa_private_key_encode(p1,
594 &b1); 592 &b1);
595 z2 = GNUNET_CRYPTO_rsa_private_key_encode (p2, 593 z2 = GNUNET_CRYPTO_rsa_private_key_encode(p2,
596 &b2); 594 &b2);
597 if (z1 != z2) 595 if (z1 != z2)
598 ret = 1; 596 ret = 1;
599 else 597 else
600 ret = memcmp (b1, 598 ret = memcmp(b1,
601 b2, 599 b2,
602 z1); 600 z1);
603 GNUNET_free (b1); 601 GNUNET_free(b1);
604 GNUNET_free (b2); 602 GNUNET_free(b2);
605 return ret; 603 return ret;
606} 604}
607 605
@@ -613,18 +611,18 @@ GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1,
613 * @return length of the key in bits 611 * @return length of the key in bits
614 */ 612 */
615unsigned int 613unsigned int
616GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key) 614GNUNET_CRYPTO_rsa_public_key_len(const struct GNUNET_CRYPTO_RsaPublicKey *key)
617{ 615{
618 gcry_mpi_t n; 616 gcry_mpi_t n;
619 unsigned int rval; 617 unsigned int rval;
620 618
621 if (0 != key_from_sexp (&n, key->sexp, "rsa", "n")) 619 if (0 != key_from_sexp(&n, key->sexp, "rsa", "n"))
622 { /* Not an RSA public key */ 620 { /* Not an RSA public key */
623 GNUNET_break (0); 621 GNUNET_break(0);
624 return 0; 622 return 0;
625 } 623 }
626 rval = gcry_mpi_get_nbits (n); 624 rval = gcry_mpi_get_nbits(n);
627 gcry_mpi_release (n); 625 gcry_mpi_release(n);
628 return rval; 626 return rval;
629} 627}
630 628
@@ -635,10 +633,10 @@ GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key)
635 * @param bkey the blinding key to destroy 633 * @param bkey the blinding key to destroy
636 */ 634 */
637static void 635static void
638rsa_blinding_key_free (struct RsaBlindingKey *bkey) 636rsa_blinding_key_free(struct RsaBlindingKey *bkey)
639{ 637{
640 gcry_mpi_release (bkey->r); 638 gcry_mpi_release(bkey->r);
641 GNUNET_free (bkey); 639 GNUNET_free(bkey);
642} 640}
643 641
644 642
@@ -650,25 +648,25 @@ rsa_blinding_key_free (struct RsaBlindingKey *bkey)
650 * @return number of bytes stored in @a buffer 648 * @return number of bytes stored in @a buffer
651 */ 649 */
652static size_t 650static size_t
653numeric_mpi_alloc_n_print (gcry_mpi_t v, 651numeric_mpi_alloc_n_print(gcry_mpi_t v,
654 char **buffer) 652 char **buffer)
655{ 653{
656 size_t n; 654 size_t n;
657 char *b; 655 char *b;
658 size_t rsize; 656 size_t rsize;
659 657
660 gcry_mpi_print (GCRYMPI_FMT_USG, 658 gcry_mpi_print(GCRYMPI_FMT_USG,
661 NULL, 659 NULL,
662 0, 660 0,
663 &n, 661 &n,
664 v); 662 v);
665 b = GNUNET_malloc (n); 663 b = GNUNET_malloc(n);
666 GNUNET_assert (0 == 664 GNUNET_assert(0 ==
667 gcry_mpi_print (GCRYMPI_FMT_USG, 665 gcry_mpi_print(GCRYMPI_FMT_USG,
668 (unsigned char *) b, 666 (unsigned char *)b,
669 n, 667 n,
670 &rsize, 668 &rsize,
671 v)); 669 v));
672 *buffer = b; 670 *buffer = b;
673 return n; 671 return n;
674} 672}
@@ -687,37 +685,37 @@ numeric_mpi_alloc_n_print (gcry_mpi_t v,
687 * @return MPI value set to the FDH, NULL if RSA key is malicious 685 * @return MPI value set to the FDH, NULL if RSA key is malicious
688 */ 686 */
689static gcry_mpi_t 687static gcry_mpi_t
690rsa_full_domain_hash (const struct GNUNET_CRYPTO_RsaPublicKey *pkey, 688rsa_full_domain_hash(const struct GNUNET_CRYPTO_RsaPublicKey *pkey,
691 const struct GNUNET_HashCode *hash) 689 const struct GNUNET_HashCode *hash)
692{ 690{
693 gcry_mpi_t r,n; 691 gcry_mpi_t r, n;
694 char *xts; 692 char *xts;
695 size_t xts_len; 693 size_t xts_len;
696 int ok; 694 int ok;
697 695
698 /* Extract the composite n from the RSA public key */ 696 /* Extract the composite n from the RSA public key */
699 GNUNET_assert( 0 == key_from_sexp (&n, pkey->sexp, "rsa", "n") ); 697 GNUNET_assert(0 == key_from_sexp(&n, pkey->sexp, "rsa", "n"));
700 /* Assert that it at least looks like an RSA key */ 698 /* Assert that it at least looks like an RSA key */
701 GNUNET_assert( 0 == gcry_mpi_get_flag(n, GCRYMPI_FLAG_OPAQUE) ); 699 GNUNET_assert(0 == gcry_mpi_get_flag(n, GCRYMPI_FLAG_OPAQUE));
702 700
703 /* We key with the public denomination key as a homage to RSA-PSS by * 701 /* We key with the public denomination key as a homage to RSA-PSS by *
704 * Mihir Bellare and Phillip Rogaway. Doing this lowers the degree * 702 * Mihir Bellare and Phillip Rogaway. Doing this lowers the degree *
705 * of the hypothetical polyomial-time attack on RSA-KTI created by a * 703 * of the hypothetical polyomial-time attack on RSA-KTI created by a *
706 * polynomial-time one-more forgary attack. Yey seeding! */ 704 * polynomial-time one-more forgary attack. Yey seeding! */
707 xts_len = GNUNET_CRYPTO_rsa_public_key_encode (pkey, &xts); 705 xts_len = GNUNET_CRYPTO_rsa_public_key_encode(pkey, &xts);
708 706
709 GNUNET_CRYPTO_kdf_mod_mpi (&r, 707 GNUNET_CRYPTO_kdf_mod_mpi(&r,
710 n, 708 n,
711 xts, xts_len, 709 xts, xts_len,
712 hash, sizeof(*hash), 710 hash, sizeof(*hash),
713 "RSA-FDA FTpsW!"); 711 "RSA-FDA FTpsW!");
714 GNUNET_free (xts); 712 GNUNET_free(xts);
715 713
716 ok = rsa_gcd_validate(r,n); 714 ok = rsa_gcd_validate(r, n);
717 gcry_mpi_release (n); 715 gcry_mpi_release(n);
718 if (ok) 716 if (ok)
719 return r; 717 return r;
720 gcry_mpi_release (r); 718 gcry_mpi_release(r);
721 return NULL; 719 return NULL;
722} 720}
723 721
@@ -733,10 +731,10 @@ rsa_full_domain_hash (const struct GNUNET_CRYPTO_RsaPublicKey *pkey,
733 * @return #GNUNET_YES if successful, #GNUNET_NO if RSA key is malicious 731 * @return #GNUNET_YES if successful, #GNUNET_NO if RSA key is malicious
734 */ 732 */
735int 733int
736GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash, 734GNUNET_CRYPTO_rsa_blind(const struct GNUNET_HashCode *hash,
737 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, 735 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
738 struct GNUNET_CRYPTO_RsaPublicKey *pkey, 736 struct GNUNET_CRYPTO_RsaPublicKey *pkey,
739 char **buf, size_t *buf_size) 737 char **buf, size_t *buf_size)
740{ 738{
741 struct RsaBlindingKey *bkey; 739 struct RsaBlindingKey *bkey;
742 gcry_mpi_t data; 740 gcry_mpi_t data;
@@ -745,58 +743,59 @@ GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash,
745 gcry_mpi_t data_r_e; 743 gcry_mpi_t data_r_e;
746 int ret; 744 int ret;
747 745
748 BENCHMARK_START (rsa_blind); 746 BENCHMARK_START(rsa_blind);
749 747
750 GNUNET_assert (buf != NULL && buf_size != NULL); 748 GNUNET_assert(buf != NULL && buf_size != NULL);
751 ret = key_from_sexp (ne, pkey->sexp, "public-key", "ne"); 749 ret = key_from_sexp(ne, pkey->sexp, "public-key", "ne");
752 if (0 != ret) 750 if (0 != ret)
753 ret = key_from_sexp (ne, pkey->sexp, "rsa", "ne"); 751 ret = key_from_sexp(ne, pkey->sexp, "rsa", "ne");
754 if (0 != ret) 752 if (0 != ret)
755 { 753 {
756 GNUNET_break (0); 754 GNUNET_break(0);
757 *buf = NULL; 755 *buf = NULL;
758 *buf_size = 0; 756 *buf_size = 0;
759 return 0; 757 return 0;
760 } 758 }
761 759
762 data = rsa_full_domain_hash (pkey, hash); 760 data = rsa_full_domain_hash(pkey, hash);
763 if (NULL == data) 761 if (NULL == data)
764 goto rsa_gcd_validate_failure; 762 goto rsa_gcd_validate_failure;
765 763
766 bkey = rsa_blinding_key_derive (pkey, bks); 764 bkey = rsa_blinding_key_derive(pkey, bks);
767 if (NULL == bkey) { 765 if (NULL == bkey)
768 gcry_mpi_release (data); 766 {
769 goto rsa_gcd_validate_failure; 767 gcry_mpi_release(data);
770 } 768 goto rsa_gcd_validate_failure;
771 769 }
772 r_e = gcry_mpi_new (0); 770
773 gcry_mpi_powm (r_e, 771 r_e = gcry_mpi_new(0);
774 bkey->r, 772 gcry_mpi_powm(r_e,
775 ne[1], 773 bkey->r,
776 ne[0]); 774 ne[1],
777 data_r_e = gcry_mpi_new (0); 775 ne[0]);
778 gcry_mpi_mulm (data_r_e, 776 data_r_e = gcry_mpi_new(0);
779 data, 777 gcry_mpi_mulm(data_r_e,
780 r_e, 778 data,
781 ne[0]); 779 r_e,
782 gcry_mpi_release (data); 780 ne[0]);
783 gcry_mpi_release (ne[0]); 781 gcry_mpi_release(data);
784 gcry_mpi_release (ne[1]); 782 gcry_mpi_release(ne[0]);
785 gcry_mpi_release (r_e); 783 gcry_mpi_release(ne[1]);
786 rsa_blinding_key_free (bkey); 784 gcry_mpi_release(r_e);
787 785 rsa_blinding_key_free(bkey);
788 *buf_size = numeric_mpi_alloc_n_print (data_r_e, buf); 786
789 gcry_mpi_release (data_r_e); 787 *buf_size = numeric_mpi_alloc_n_print(data_r_e, buf);
790 788 gcry_mpi_release(data_r_e);
791 BENCHMARK_END (rsa_blind); 789
790 BENCHMARK_END(rsa_blind);
792 791
793 return GNUNET_YES; 792 return GNUNET_YES;
794 793
795rsa_gcd_validate_failure: 794rsa_gcd_validate_failure:
796 /* We know the RSA key is malicious here, so warn the wallet. */ 795 /* We know the RSA key is malicious here, so warn the wallet. */
797 /* GNUNET_break_op (0); */ 796 /* GNUNET_break_op (0); */
798 gcry_mpi_release (ne[0]); 797 gcry_mpi_release(ne[0]);
799 gcry_mpi_release (ne[1]); 798 gcry_mpi_release(ne[1]);
800 *buf = NULL; 799 *buf = NULL;
801 *buf_size = 0; 800 *buf_size = 0;
802 return GNUNET_NO; 801 return GNUNET_NO;
@@ -810,15 +809,15 @@ rsa_gcd_validate_failure:
810 * @return converted s-expression 809 * @return converted s-expression
811 */ 810 */
812static gcry_sexp_t 811static gcry_sexp_t
813mpi_to_sexp (gcry_mpi_t value) 812mpi_to_sexp(gcry_mpi_t value)
814{ 813{
815 gcry_sexp_t data = NULL; 814 gcry_sexp_t data = NULL;
816 815
817 GNUNET_assert (0 == 816 GNUNET_assert(0 ==
818 gcry_sexp_build (&data, 817 gcry_sexp_build(&data,
819 NULL, 818 NULL,
820 "(data (flags raw) (value %M))", 819 "(data (flags raw) (value %M))",
821 value)); 820 value));
822 return data; 821 return data;
823} 822}
824 823
@@ -831,53 +830,53 @@ mpi_to_sexp (gcry_mpi_t value)
831 * @return NULL on error, signature on success 830 * @return NULL on error, signature on success
832 */ 831 */
833static struct GNUNET_CRYPTO_RsaSignature * 832static struct GNUNET_CRYPTO_RsaSignature *
834rsa_sign_mpi (const struct GNUNET_CRYPTO_RsaPrivateKey *key, 833rsa_sign_mpi(const struct GNUNET_CRYPTO_RsaPrivateKey *key,
835 gcry_mpi_t value) 834 gcry_mpi_t value)
836{ 835{
837 struct GNUNET_CRYPTO_RsaSignature *sig; 836 struct GNUNET_CRYPTO_RsaSignature *sig;
838 gcry_sexp_t data; 837 gcry_sexp_t data;
839 gcry_sexp_t result; 838 gcry_sexp_t result;
840 int rc; 839 int rc;
841 840
842 data = mpi_to_sexp (value); 841 data = mpi_to_sexp(value);
843 842
844 if (0 != 843 if (0 !=
845 (rc = gcry_pk_sign (&result, 844 (rc = gcry_pk_sign(&result,
846 data, 845 data,
847 key->sexp))) 846 key->sexp)))
848 { 847 {
849 LOG (GNUNET_ERROR_TYPE_WARNING, 848 LOG(GNUNET_ERROR_TYPE_WARNING,
850 _("RSA signing failed at %s:%d: %s\n"), 849 _("RSA signing failed at %s:%d: %s\n"),
851 __FILE__, 850 __FILE__,
852 __LINE__, 851 __LINE__,
853 gcry_strerror (rc)); 852 gcry_strerror(rc));
854 GNUNET_break (0); 853 GNUNET_break(0);
855 return NULL; 854 return NULL;
856 } 855 }
857 856
858 /* Lenstra protection was first added to libgcrypt 1.6.4 857 /* Lenstra protection was first added to libgcrypt 1.6.4
859 * with commit c17f84bd02d7ee93845e92e20f6ddba814961588. 858 * with commit c17f84bd02d7ee93845e92e20f6ddba814961588.
860 */ 859 */
861#if GCRYPT_VERSION_NUMBER < 0x010604 860#if GCRYPT_VERSION_NUMBER < 0x010604
862 /* verify signature (guards against Lenstra's attack with fault injection...) */ 861 /* verify signature (guards against Lenstra's attack with fault injection...) */
863 struct GNUNET_CRYPTO_RsaPublicKey *public_key = GNUNET_CRYPTO_rsa_private_key_get_public (key); 862 struct GNUNET_CRYPTO_RsaPublicKey *public_key = GNUNET_CRYPTO_rsa_private_key_get_public(key);
864 if (0 != 863 if (0 !=
865 gcry_pk_verify (result, 864 gcry_pk_verify(result,
866 data, 865 data,
867 public_key->sexp)) 866 public_key->sexp))
868 { 867 {
869 GNUNET_break (0); 868 GNUNET_break(0);
870 GNUNET_CRYPTO_rsa_public_key_free (public_key); 869 GNUNET_CRYPTO_rsa_public_key_free(public_key);
871 gcry_sexp_release (data); 870 gcry_sexp_release(data);
872 gcry_sexp_release (result); 871 gcry_sexp_release(result);
873 return NULL; 872 return NULL;
874 } 873 }
875 GNUNET_CRYPTO_rsa_public_key_free (public_key); 874 GNUNET_CRYPTO_rsa_public_key_free(public_key);
876#endif 875#endif
877 876
878 /* return signature */ 877 /* return signature */
879 gcry_sexp_release (data); 878 gcry_sexp_release(data);
880 sig = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature); 879 sig = GNUNET_new(struct GNUNET_CRYPTO_RsaSignature);
881 sig->sexp = result; 880 sig->sexp = result;
882 return sig; 881 return sig;
883} 882}
@@ -892,25 +891,25 @@ rsa_sign_mpi (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
892 * @return NULL on error, signature on success 891 * @return NULL on error, signature on success
893 */ 892 */
894struct GNUNET_CRYPTO_RsaSignature * 893struct GNUNET_CRYPTO_RsaSignature *
895GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key, 894GNUNET_CRYPTO_rsa_sign_blinded(const struct GNUNET_CRYPTO_RsaPrivateKey *key,
896 const void *msg, 895 const void *msg,
897 size_t msg_len) 896 size_t msg_len)
898{ 897{
899 gcry_mpi_t v = NULL; 898 gcry_mpi_t v = NULL;
900 struct GNUNET_CRYPTO_RsaSignature *sig; 899 struct GNUNET_CRYPTO_RsaSignature *sig;
901 900
902 BENCHMARK_START (rsa_sign_blinded); 901 BENCHMARK_START(rsa_sign_blinded);
903 902
904 GNUNET_assert (0 == 903 GNUNET_assert(0 ==
905 gcry_mpi_scan (&v, 904 gcry_mpi_scan(&v,
906 GCRYMPI_FMT_USG, 905 GCRYMPI_FMT_USG,
907 msg, 906 msg,
908 msg_len, 907 msg_len,
909 NULL)); 908 NULL));
910 909
911 sig = rsa_sign_mpi (key, v); 910 sig = rsa_sign_mpi(key, v);
912 gcry_mpi_release (v); 911 gcry_mpi_release(v);
913 BENCHMARK_END (rsa_sign_blinded); 912 BENCHMARK_END(rsa_sign_blinded);
914 return sig; 913 return sig;
915} 914}
916 915
@@ -923,21 +922,21 @@ GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
923 * @return NULL on error, including a malicious RSA key, signature on success 922 * @return NULL on error, including a malicious RSA key, signature on success
924 */ 923 */
925struct GNUNET_CRYPTO_RsaSignature * 924struct GNUNET_CRYPTO_RsaSignature *
926GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key, 925GNUNET_CRYPTO_rsa_sign_fdh(const struct GNUNET_CRYPTO_RsaPrivateKey *key,
927 const struct GNUNET_HashCode *hash) 926 const struct GNUNET_HashCode *hash)
928{ 927{
929 struct GNUNET_CRYPTO_RsaPublicKey *pkey; 928 struct GNUNET_CRYPTO_RsaPublicKey *pkey;
930 gcry_mpi_t v = NULL; 929 gcry_mpi_t v = NULL;
931 struct GNUNET_CRYPTO_RsaSignature *sig; 930 struct GNUNET_CRYPTO_RsaSignature *sig;
932 931
933 pkey = GNUNET_CRYPTO_rsa_private_key_get_public (key); 932 pkey = GNUNET_CRYPTO_rsa_private_key_get_public(key);
934 v = rsa_full_domain_hash (pkey, hash); 933 v = rsa_full_domain_hash(pkey, hash);
935 GNUNET_CRYPTO_rsa_public_key_free (pkey); 934 GNUNET_CRYPTO_rsa_public_key_free(pkey);
936 if (NULL == v) /* rsa_gcd_validate failed meaning */ 935 if (NULL == v) /* rsa_gcd_validate failed meaning */
937 return NULL; /* our *own* RSA key is malicious. */ 936 return NULL; /* our *own* RSA key is malicious. */
938 937
939 sig = rsa_sign_mpi (key, v); 938 sig = rsa_sign_mpi(key, v);
940 gcry_mpi_release (v); 939 gcry_mpi_release(v);
941 return sig; 940 return sig;
942} 941}
943 942
@@ -948,10 +947,10 @@ GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
948 * @param sig memory to freee 947 * @param sig memory to freee
949 */ 948 */
950void 949void
951GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig) 950GNUNET_CRYPTO_rsa_signature_free(struct GNUNET_CRYPTO_RsaSignature *sig)
952{ 951{
953 gcry_sexp_release (sig->sexp); 952 gcry_sexp_release(sig->sexp);
954 GNUNET_free (sig); 953 GNUNET_free(sig);
955} 954}
956 955
957 956
@@ -963,22 +962,22 @@ GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig)
963 * @return size of memory allocated in @a buffer 962 * @return size of memory allocated in @a buffer
964 */ 963 */
965size_t 964size_t
966GNUNET_CRYPTO_rsa_signature_encode (const struct GNUNET_CRYPTO_RsaSignature *sig, 965GNUNET_CRYPTO_rsa_signature_encode(const struct GNUNET_CRYPTO_RsaSignature *sig,
967 char **buffer) 966 char **buffer)
968{ 967{
969 size_t n; 968 size_t n;
970 char *b; 969 char *b;
971 970
972 n = gcry_sexp_sprint (sig->sexp, 971 n = gcry_sexp_sprint(sig->sexp,
973 GCRYSEXP_FMT_ADVANCED, 972 GCRYSEXP_FMT_ADVANCED,
974 NULL, 973 NULL,
975 0); 974 0);
976 b = GNUNET_malloc (n); 975 b = GNUNET_malloc(n);
977 GNUNET_assert ((n - 1) == /* since the last byte is \0 */ 976 GNUNET_assert((n - 1) == /* since the last byte is \0 */
978 gcry_sexp_sprint (sig->sexp, 977 gcry_sexp_sprint(sig->sexp,
979 GCRYSEXP_FMT_ADVANCED, 978 GCRYSEXP_FMT_ADVANCED,
980 b, 979 b,
981 n)); 980 n));
982 *buffer = b; 981 *buffer = b;
983 return n; 982 return n;
984} 983}
@@ -993,37 +992,37 @@ GNUNET_CRYPTO_rsa_signature_encode (const struct GNUNET_CRYPTO_RsaSignature *sig
993 * @return NULL on error 992 * @return NULL on error
994 */ 993 */
995struct GNUNET_CRYPTO_RsaSignature * 994struct GNUNET_CRYPTO_RsaSignature *
996GNUNET_CRYPTO_rsa_signature_decode (const char *buf, 995GNUNET_CRYPTO_rsa_signature_decode(const char *buf,
997 size_t len) 996 size_t len)
998{ 997{
999 struct GNUNET_CRYPTO_RsaSignature *sig; 998 struct GNUNET_CRYPTO_RsaSignature *sig;
1000 int ret; 999 int ret;
1001 gcry_mpi_t s; 1000 gcry_mpi_t s;
1002 1001
1003 sig = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature); 1002 sig = GNUNET_new(struct GNUNET_CRYPTO_RsaSignature);
1004 if (0 != 1003 if (0 !=
1005 gcry_sexp_new (&sig->sexp, 1004 gcry_sexp_new(&sig->sexp,
1006 buf, 1005 buf,
1007 len, 1006 len,
1008 0)) 1007 0))
1009 { 1008 {
1010 GNUNET_break_op (0); 1009 GNUNET_break_op(0);
1011 GNUNET_free (sig); 1010 GNUNET_free(sig);
1012 return NULL; 1011 return NULL;
1013 } 1012 }
1014 /* verify that this is an RSA signature */ 1013 /* verify that this is an RSA signature */
1015 ret = key_from_sexp (&s, sig->sexp, "sig-val", "s"); 1014 ret = key_from_sexp(&s, sig->sexp, "sig-val", "s");
1016 if (0 != ret) 1015 if (0 != ret)
1017 ret = key_from_sexp (&s, sig->sexp, "rsa", "s"); 1016 ret = key_from_sexp(&s, sig->sexp, "rsa", "s");
1018 if (0 != ret) 1017 if (0 != ret)
1019 { 1018 {
1020 /* this is no RSA Signature */ 1019 /* this is no RSA Signature */
1021 GNUNET_break_op (0); 1020 GNUNET_break_op(0);
1022 gcry_sexp_release (sig->sexp); 1021 gcry_sexp_release(sig->sexp);
1023 GNUNET_free (sig); 1022 GNUNET_free(sig);
1024 return NULL; 1023 return NULL;
1025 } 1024 }
1026 gcry_mpi_release (s); 1025 gcry_mpi_release(s);
1027 return sig; 1026 return sig;
1028} 1027}
1029 1028
@@ -1035,19 +1034,19 @@ GNUNET_CRYPTO_rsa_signature_decode (const char *buf,
1035 * @return the duplicate key; NULL upon error 1034 * @return the duplicate key; NULL upon error
1036 */ 1035 */
1037struct GNUNET_CRYPTO_RsaPublicKey * 1036struct GNUNET_CRYPTO_RsaPublicKey *
1038GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key) 1037GNUNET_CRYPTO_rsa_public_key_dup(const struct GNUNET_CRYPTO_RsaPublicKey *key)
1039{ 1038{
1040 struct GNUNET_CRYPTO_RsaPublicKey *dup; 1039 struct GNUNET_CRYPTO_RsaPublicKey *dup;
1041 gcry_sexp_t dup_sexp; 1040 gcry_sexp_t dup_sexp;
1042 size_t erroff; 1041 size_t erroff;
1043 1042
1044 /* check if we really are exporting a public key */ 1043 /* check if we really are exporting a public key */
1045 dup_sexp = gcry_sexp_find_token (key->sexp, "public-key", 0); 1044 dup_sexp = gcry_sexp_find_token(key->sexp, "public-key", 0);
1046 GNUNET_assert (NULL != dup_sexp); 1045 GNUNET_assert(NULL != dup_sexp);
1047 gcry_sexp_release (dup_sexp); 1046 gcry_sexp_release(dup_sexp);
1048 /* copy the sexp */ 1047 /* copy the sexp */
1049 GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", key->sexp)); 1048 GNUNET_assert(0 == gcry_sexp_build(&dup_sexp, &erroff, "%S", key->sexp));
1050 dup = GNUNET_new (struct GNUNET_CRYPTO_RsaPublicKey); 1049 dup = GNUNET_new(struct GNUNET_CRYPTO_RsaPublicKey);
1051 dup->sexp = dup_sexp; 1050 dup->sexp = dup_sexp;
1052 return dup; 1051 return dup;
1053} 1052}
@@ -1064,9 +1063,9 @@ GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key)
1064 * @return unblinded signature on success, NULL if RSA key is bad or malicious. 1063 * @return unblinded signature on success, NULL if RSA key is bad or malicious.
1065 */ 1064 */
1066struct GNUNET_CRYPTO_RsaSignature * 1065struct GNUNET_CRYPTO_RsaSignature *
1067GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig, 1066GNUNET_CRYPTO_rsa_unblind(const struct GNUNET_CRYPTO_RsaSignature *sig,
1068 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks, 1067 const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
1069 struct GNUNET_CRYPTO_RsaPublicKey *pkey) 1068 struct GNUNET_CRYPTO_RsaPublicKey *pkey)
1070{ 1069{
1071 struct RsaBlindingKey *bkey; 1070 struct RsaBlindingKey *bkey;
1072 gcry_mpi_t n; 1071 gcry_mpi_t n;
@@ -1076,70 +1075,70 @@ GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig,
1076 int ret; 1075 int ret;
1077 struct GNUNET_CRYPTO_RsaSignature *sret; 1076 struct GNUNET_CRYPTO_RsaSignature *sret;
1078 1077
1079 BENCHMARK_START (rsa_unblind); 1078 BENCHMARK_START(rsa_unblind);
1080 1079
1081 ret = key_from_sexp (&n, pkey->sexp, "public-key", "n"); 1080 ret = key_from_sexp(&n, pkey->sexp, "public-key", "n");
1082 if (0 != ret) 1081 if (0 != ret)
1083 ret = key_from_sexp (&n, pkey->sexp, "rsa", "n"); 1082 ret = key_from_sexp(&n, pkey->sexp, "rsa", "n");
1084 if (0 != ret) 1083 if (0 != ret)
1085 { 1084 {
1086 GNUNET_break_op (0); 1085 GNUNET_break_op(0);
1087 return NULL; 1086 return NULL;
1088 } 1087 }
1089 ret = key_from_sexp (&s, sig->sexp, "sig-val", "s"); 1088 ret = key_from_sexp(&s, sig->sexp, "sig-val", "s");
1090 if (0 != ret) 1089 if (0 != ret)
1091 ret = key_from_sexp (&s, sig->sexp, "rsa", "s"); 1090 ret = key_from_sexp(&s, sig->sexp, "rsa", "s");
1092 if (0 != ret) 1091 if (0 != ret)
1093 { 1092 {
1094 gcry_mpi_release (n); 1093 gcry_mpi_release(n);
1095 GNUNET_break_op (0); 1094 GNUNET_break_op(0);
1096 return NULL; 1095 return NULL;
1097 } 1096 }
1098 1097
1099 bkey = rsa_blinding_key_derive (pkey, bks); 1098 bkey = rsa_blinding_key_derive(pkey, bks);
1100 if (NULL == bkey) 1099 if (NULL == bkey)
1101 { 1100 {
1102 /* RSA key is malicious since rsa_gcd_validate failed here. 1101 /* RSA key is malicious since rsa_gcd_validate failed here.
1103 * It should have failed during GNUNET_CRYPTO_rsa_blind too though, 1102 * It should have failed during GNUNET_CRYPTO_rsa_blind too though,
1104 * so the exchange is being malicious in an unfamilair way, maybe 1103 * so the exchange is being malicious in an unfamilair way, maybe
1105 * just trying to crash us. */ 1104 * just trying to crash us. */
1106 GNUNET_break_op (0); 1105 GNUNET_break_op(0);
1107 gcry_mpi_release (n); 1106 gcry_mpi_release(n);
1108 gcry_mpi_release (s); 1107 gcry_mpi_release(s);
1109 return NULL; 1108 return NULL;
1110 } 1109 }
1111 1110
1112 r_inv = gcry_mpi_new (0); 1111 r_inv = gcry_mpi_new(0);
1113 if (1 != 1112 if (1 !=
1114 gcry_mpi_invm (r_inv, 1113 gcry_mpi_invm(r_inv,
1115 bkey->r, 1114 bkey->r,
1116 n)) 1115 n))
1117 { 1116 {
1118 /* We cannot find r mod n, so gcd(r,n) != 1, which should get * 1117 /* We cannot find r mod n, so gcd(r,n) != 1, which should get *
1119 * caught above, but we handle it the same here. */ 1118 * caught above, but we handle it the same here. */
1120 GNUNET_break_op (0); 1119 GNUNET_break_op(0);
1121 gcry_mpi_release (r_inv); 1120 gcry_mpi_release(r_inv);
1122 rsa_blinding_key_free (bkey); 1121 rsa_blinding_key_free(bkey);
1123 gcry_mpi_release (n); 1122 gcry_mpi_release(n);
1124 gcry_mpi_release (s); 1123 gcry_mpi_release(s);
1125 return NULL; 1124 return NULL;
1126 } 1125 }
1127 1126
1128 ubsig = gcry_mpi_new (0); 1127 ubsig = gcry_mpi_new(0);
1129 gcry_mpi_mulm (ubsig, s, r_inv, n); 1128 gcry_mpi_mulm(ubsig, s, r_inv, n);
1130 gcry_mpi_release (n); 1129 gcry_mpi_release(n);
1131 gcry_mpi_release (r_inv); 1130 gcry_mpi_release(r_inv);
1132 gcry_mpi_release (s); 1131 gcry_mpi_release(s);
1133 rsa_blinding_key_free (bkey); 1132 rsa_blinding_key_free(bkey);
1134 1133
1135 sret = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature); 1134 sret = GNUNET_new(struct GNUNET_CRYPTO_RsaSignature);
1136 GNUNET_assert (0 == 1135 GNUNET_assert(0 ==
1137 gcry_sexp_build (&sret->sexp, 1136 gcry_sexp_build(&sret->sexp,
1138 NULL, 1137 NULL,
1139 "(sig-val (rsa (s %M)))", 1138 "(sig-val (rsa (s %M)))",
1140 ubsig)); 1139 ubsig));
1141 gcry_mpi_release (ubsig); 1140 gcry_mpi_release(ubsig);
1142 BENCHMARK_END (rsa_unblind); 1141 BENCHMARK_END(rsa_unblind);
1143 return sret; 1142 return sret;
1144} 1143}
1145 1144
@@ -1154,46 +1153,47 @@ GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig,
1154 * @returns #GNUNET_YES if ok, #GNUNET_NO if RSA key is malicious, #GNUNET_SYSERR if signature is invalid 1153 * @returns #GNUNET_YES if ok, #GNUNET_NO if RSA key is malicious, #GNUNET_SYSERR if signature is invalid
1155 */ 1154 */
1156int 1155int
1157GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash, 1156GNUNET_CRYPTO_rsa_verify(const struct GNUNET_HashCode *hash,
1158 const struct GNUNET_CRYPTO_RsaSignature *sig, 1157 const struct GNUNET_CRYPTO_RsaSignature *sig,
1159 const struct GNUNET_CRYPTO_RsaPublicKey *pkey) 1158 const struct GNUNET_CRYPTO_RsaPublicKey *pkey)
1160{ 1159{
1161 gcry_sexp_t data; 1160 gcry_sexp_t data;
1162 gcry_mpi_t r; 1161 gcry_mpi_t r;
1163 int rc; 1162 int rc;
1164 1163
1165 BENCHMARK_START (rsa_verify); 1164 BENCHMARK_START(rsa_verify);
1166 1165
1167 r = rsa_full_domain_hash (pkey, hash); 1166 r = rsa_full_domain_hash(pkey, hash);
1168 if (NULL == r) { 1167 if (NULL == r)
1169 GNUNET_break_op (0); 1168 {
1170 /* RSA key is malicious since rsa_gcd_validate failed here. 1169 GNUNET_break_op(0);
1171 * It should have failed during GNUNET_CRYPTO_rsa_blind too though, 1170 /* RSA key is malicious since rsa_gcd_validate failed here.
1172 * so the exchange is being malicious in an unfamilair way, maybe 1171 * It should have failed during GNUNET_CRYPTO_rsa_blind too though,
1173 * just trying to crash us. Arguably, we've only an internal error 1172 * so the exchange is being malicious in an unfamilair way, maybe
1174 * though because we should've detected this in our previous call 1173 * just trying to crash us. Arguably, we've only an internal error
1175 * to GNUNET_CRYPTO_rsa_unblind. */ 1174 * though because we should've detected this in our previous call
1176 return GNUNET_NO; 1175 * to GNUNET_CRYPTO_rsa_unblind. */
1177 } 1176 return GNUNET_NO;
1177 }
1178 1178
1179 data = mpi_to_sexp(r); 1179 data = mpi_to_sexp(r);
1180 gcry_mpi_release (r); 1180 gcry_mpi_release(r);
1181 1181
1182 rc = gcry_pk_verify (sig->sexp, 1182 rc = gcry_pk_verify(sig->sexp,
1183 data, 1183 data,
1184 pkey->sexp); 1184 pkey->sexp);
1185 gcry_sexp_release (data); 1185 gcry_sexp_release(data);
1186 if (0 != rc) 1186 if (0 != rc)
1187 { 1187 {
1188 LOG (GNUNET_ERROR_TYPE_WARNING, 1188 LOG(GNUNET_ERROR_TYPE_WARNING,
1189 _("RSA signature verification failed at %s:%d: %s\n"), 1189 _("RSA signature verification failed at %s:%d: %s\n"),
1190 __FILE__, 1190 __FILE__,
1191 __LINE__, 1191 __LINE__,
1192 gcry_strerror (rc)); 1192 gcry_strerror(rc));
1193 return GNUNET_SYSERR; 1193 return GNUNET_SYSERR;
1194 BENCHMARK_END (rsa_verify); 1194 BENCHMARK_END(rsa_verify);
1195 } 1195 }
1196 BENCHMARK_END (rsa_verify); 1196 BENCHMARK_END(rsa_verify);
1197 return GNUNET_OK; 1197 return GNUNET_OK;
1198} 1198}
1199 1199
@@ -1205,19 +1205,19 @@ GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash,
1205 * @return the duplicate key; NULL upon error 1205 * @return the duplicate key; NULL upon error
1206 */ 1206 */
1207struct GNUNET_CRYPTO_RsaPrivateKey * 1207struct GNUNET_CRYPTO_RsaPrivateKey *
1208GNUNET_CRYPTO_rsa_private_key_dup (const struct GNUNET_CRYPTO_RsaPrivateKey *key) 1208GNUNET_CRYPTO_rsa_private_key_dup(const struct GNUNET_CRYPTO_RsaPrivateKey *key)
1209{ 1209{
1210 struct GNUNET_CRYPTO_RsaPrivateKey *dup; 1210 struct GNUNET_CRYPTO_RsaPrivateKey *dup;
1211 gcry_sexp_t dup_sexp; 1211 gcry_sexp_t dup_sexp;
1212 size_t erroff; 1212 size_t erroff;
1213 1213
1214 /* check if we really are exporting a private key */ 1214 /* check if we really are exporting a private key */
1215 dup_sexp = gcry_sexp_find_token (key->sexp, "private-key", 0); 1215 dup_sexp = gcry_sexp_find_token(key->sexp, "private-key", 0);
1216 GNUNET_assert (NULL != dup_sexp); 1216 GNUNET_assert(NULL != dup_sexp);
1217 gcry_sexp_release (dup_sexp); 1217 gcry_sexp_release(dup_sexp);
1218 /* copy the sexp */ 1218 /* copy the sexp */
1219 GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", key->sexp)); 1219 GNUNET_assert(0 == gcry_sexp_build(&dup_sexp, &erroff, "%S", key->sexp));
1220 dup = GNUNET_new (struct GNUNET_CRYPTO_RsaPrivateKey); 1220 dup = GNUNET_new(struct GNUNET_CRYPTO_RsaPrivateKey);
1221 dup->sexp = dup_sexp; 1221 dup->sexp = dup_sexp;
1222 return dup; 1222 return dup;
1223} 1223}
@@ -1230,7 +1230,7 @@ GNUNET_CRYPTO_rsa_private_key_dup (const struct GNUNET_CRYPTO_RsaPrivateKey *key
1230 * @return the duplicate key; NULL upon error 1230 * @return the duplicate key; NULL upon error
1231 */ 1231 */
1232struct GNUNET_CRYPTO_RsaSignature * 1232struct GNUNET_CRYPTO_RsaSignature *
1233GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig) 1233GNUNET_CRYPTO_rsa_signature_dup(const struct GNUNET_CRYPTO_RsaSignature *sig)
1234{ 1234{
1235 struct GNUNET_CRYPTO_RsaSignature *dup; 1235 struct GNUNET_CRYPTO_RsaSignature *dup;
1236 gcry_sexp_t dup_sexp; 1236 gcry_sexp_t dup_sexp;
@@ -1239,14 +1239,14 @@ GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig)
1239 int ret; 1239 int ret;
1240 1240
1241 /* verify that this is an RSA signature */ 1241 /* verify that this is an RSA signature */
1242 ret = key_from_sexp (&s, sig->sexp, "sig-val", "s"); 1242 ret = key_from_sexp(&s, sig->sexp, "sig-val", "s");
1243 if (0 != ret) 1243 if (0 != ret)
1244 ret = key_from_sexp (&s, sig->sexp, "rsa", "s"); 1244 ret = key_from_sexp(&s, sig->sexp, "rsa", "s");
1245 GNUNET_assert (0 == ret); 1245 GNUNET_assert(0 == ret);
1246 gcry_mpi_release (s); 1246 gcry_mpi_release(s);
1247 /* copy the sexp */ 1247 /* copy the sexp */
1248 GNUNET_assert (0 == gcry_sexp_build (&dup_sexp, &erroff, "%S", sig->sexp)); 1248 GNUNET_assert(0 == gcry_sexp_build(&dup_sexp, &erroff, "%S", sig->sexp));
1249 dup = GNUNET_new (struct GNUNET_CRYPTO_RsaSignature); 1249 dup = GNUNET_new(struct GNUNET_CRYPTO_RsaSignature);
1250 dup->sexp = dup_sexp; 1250 dup->sexp = dup_sexp;
1251 return dup; 1251 return dup;
1252} 1252}
diff --git a/src/util/crypto_symmetric.c b/src/util/crypto_symmetric.c
index 18784d127..7fad2a884 100644
--- a/src/util/crypto_symmetric.c
+++ b/src/util/crypto_symmetric.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/crypto_symmetric.c 22 * @file util/crypto_symmetric.c
@@ -29,7 +29,7 @@
29#include "gnunet_crypto_lib.h" 29#include "gnunet_crypto_lib.h"
30#include <gcrypt.h> 30#include <gcrypt.h>
31 31
32#define LOG(kind,...) GNUNET_log_from (kind, "util-crypto-symmetric", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-crypto-symmetric", __VA_ARGS__)
33 33
34/** 34/**
35 * Create a new SessionKey (for symmetric encryption). 35 * Create a new SessionKey (for symmetric encryption).
@@ -37,14 +37,14 @@
37 * @param key session key to initialize 37 * @param key session key to initialize
38 */ 38 */
39void 39void
40GNUNET_CRYPTO_symmetric_create_session_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key) 40GNUNET_CRYPTO_symmetric_create_session_key(struct GNUNET_CRYPTO_SymmetricSessionKey *key)
41{ 41{
42 gcry_randomize (key->aes_key, 42 gcry_randomize(key->aes_key,
43 GNUNET_CRYPTO_AES_KEY_LENGTH, 43 GNUNET_CRYPTO_AES_KEY_LENGTH,
44 GCRY_STRONG_RANDOM); 44 GCRY_STRONG_RANDOM);
45 gcry_randomize (key->twofish_key, 45 gcry_randomize(key->twofish_key,
46 GNUNET_CRYPTO_AES_KEY_LENGTH, 46 GNUNET_CRYPTO_AES_KEY_LENGTH,
47 GCRY_STRONG_RANDOM); 47 GCRY_STRONG_RANDOM);
48} 48}
49 49
50 50
@@ -57,23 +57,23 @@ GNUNET_CRYPTO_symmetric_create_session_key (struct GNUNET_CRYPTO_SymmetricSessio
57 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 57 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
58 */ 58 */
59static int 59static int
60setup_cipher_aes (gcry_cipher_hd_t *handle, 60setup_cipher_aes(gcry_cipher_hd_t *handle,
61 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, 61 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
62 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv) 62 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
63{ 63{
64 int rc; 64 int rc;
65 65
66 GNUNET_assert (0 == 66 GNUNET_assert(0 ==
67 gcry_cipher_open (handle, GCRY_CIPHER_AES256, 67 gcry_cipher_open(handle, GCRY_CIPHER_AES256,
68 GCRY_CIPHER_MODE_CFB, 0)); 68 GCRY_CIPHER_MODE_CFB, 0));
69 rc = gcry_cipher_setkey (*handle, 69 rc = gcry_cipher_setkey(*handle,
70 sessionkey->aes_key, 70 sessionkey->aes_key,
71 sizeof (sessionkey->aes_key)); 71 sizeof(sessionkey->aes_key));
72 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 72 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
73 rc = gcry_cipher_setiv (*handle, 73 rc = gcry_cipher_setiv(*handle,
74 iv->aes_iv, 74 iv->aes_iv,
75 sizeof (iv->aes_iv)); 75 sizeof(iv->aes_iv));
76 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 76 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
77 return GNUNET_OK; 77 return GNUNET_OK;
78} 78}
79 79
@@ -87,23 +87,23 @@ setup_cipher_aes (gcry_cipher_hd_t *handle,
87 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 87 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
88 */ 88 */
89static int 89static int
90setup_cipher_twofish (gcry_cipher_hd_t *handle, 90setup_cipher_twofish(gcry_cipher_hd_t *handle,
91 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, 91 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
92 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv) 92 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv)
93{ 93{
94 int rc; 94 int rc;
95 95
96 GNUNET_assert (0 == 96 GNUNET_assert(0 ==
97 gcry_cipher_open (handle, GCRY_CIPHER_TWOFISH, 97 gcry_cipher_open(handle, GCRY_CIPHER_TWOFISH,
98 GCRY_CIPHER_MODE_CFB, 0)); 98 GCRY_CIPHER_MODE_CFB, 0));
99 rc = gcry_cipher_setkey (*handle, 99 rc = gcry_cipher_setkey(*handle,
100 sessionkey->twofish_key, 100 sessionkey->twofish_key,
101 sizeof (sessionkey->twofish_key)); 101 sizeof(sessionkey->twofish_key));
102 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 102 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
103 rc = gcry_cipher_setiv (*handle, 103 rc = gcry_cipher_setiv(*handle,
104 iv->twofish_iv, 104 iv->twofish_iv,
105 sizeof (iv->twofish_iv)); 105 sizeof(iv->twofish_iv));
106 GNUNET_assert ((0 == rc) || ((char) rc == GPG_ERR_WEAK_KEY)); 106 GNUNET_assert((0 == rc) || ((char)rc == GPG_ERR_WEAK_KEY));
107 return GNUNET_OK; 107 return GNUNET_OK;
108} 108}
109 109
@@ -122,24 +122,24 @@ setup_cipher_twofish (gcry_cipher_hd_t *handle,
122 * this size should be the same as @c len. 122 * this size should be the same as @c len.
123 */ 123 */
124ssize_t 124ssize_t
125GNUNET_CRYPTO_symmetric_encrypt (const void *block, 125GNUNET_CRYPTO_symmetric_encrypt(const void *block,
126 size_t size, 126 size_t size,
127 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, 127 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
128 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, 128 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
129 void *result) 129 void *result)
130{ 130{
131 gcry_cipher_hd_t handle; 131 gcry_cipher_hd_t handle;
132 char tmp[size]; 132 char tmp[size];
133 133
134 if (GNUNET_OK != setup_cipher_aes (&handle, sessionkey, iv)) 134 if (GNUNET_OK != setup_cipher_aes(&handle, sessionkey, iv))
135 return -1; 135 return -1;
136 GNUNET_assert (0 == gcry_cipher_encrypt (handle, tmp, size, block, size)); 136 GNUNET_assert(0 == gcry_cipher_encrypt(handle, tmp, size, block, size));
137 gcry_cipher_close (handle); 137 gcry_cipher_close(handle);
138 if (GNUNET_OK != setup_cipher_twofish (&handle, sessionkey, iv)) 138 if (GNUNET_OK != setup_cipher_twofish(&handle, sessionkey, iv))
139 return -1; 139 return -1;
140 GNUNET_assert (0 == gcry_cipher_encrypt (handle, result, size, tmp, size)); 140 GNUNET_assert(0 == gcry_cipher_encrypt(handle, result, size, tmp, size));
141 gcry_cipher_close (handle); 141 gcry_cipher_close(handle);
142 memset (tmp, 0, sizeof (tmp)); 142 memset(tmp, 0, sizeof(tmp));
143 return size; 143 return size;
144} 144}
145 145
@@ -158,24 +158,24 @@ GNUNET_CRYPTO_symmetric_encrypt (const void *block,
158 * this size should be the same as @c size. 158 * this size should be the same as @c size.
159 */ 159 */
160ssize_t 160ssize_t
161GNUNET_CRYPTO_symmetric_decrypt (const void *block, 161GNUNET_CRYPTO_symmetric_decrypt(const void *block,
162 size_t size, 162 size_t size,
163 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey, 163 const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
164 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, 164 const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
165 void *result) 165 void *result)
166{ 166{
167 gcry_cipher_hd_t handle; 167 gcry_cipher_hd_t handle;
168 char tmp[size]; 168 char tmp[size];
169 169
170 if (GNUNET_OK != setup_cipher_twofish (&handle, sessionkey, iv)) 170 if (GNUNET_OK != setup_cipher_twofish(&handle, sessionkey, iv))
171 return -1; 171 return -1;
172 GNUNET_assert (0 == gcry_cipher_decrypt (handle, tmp, size, block, size)); 172 GNUNET_assert(0 == gcry_cipher_decrypt(handle, tmp, size, block, size));
173 gcry_cipher_close (handle); 173 gcry_cipher_close(handle);
174 if (GNUNET_OK != setup_cipher_aes (&handle, sessionkey, iv)) 174 if (GNUNET_OK != setup_cipher_aes(&handle, sessionkey, iv))
175 return -1; 175 return -1;
176 GNUNET_assert (0 == gcry_cipher_decrypt (handle, result, size, tmp, size)); 176 GNUNET_assert(0 == gcry_cipher_decrypt(handle, result, size, tmp, size));
177 gcry_cipher_close (handle); 177 gcry_cipher_close(handle);
178 memset (tmp, 0, sizeof (tmp)); 178 memset(tmp, 0, sizeof(tmp));
179 return size; 179 return size;
180} 180}
181 181
@@ -190,17 +190,17 @@ GNUNET_CRYPTO_symmetric_decrypt (const void *block,
190 * @param ... pairs of void * & size_t for context chunks, terminated by NULL 190 * @param ... pairs of void * & size_t for context chunks, terminated by NULL
191 */ 191 */
192void 192void
193GNUNET_CRYPTO_symmetric_derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, 193GNUNET_CRYPTO_symmetric_derive_iv(struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
194 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, 194 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
195 const void *salt, 195 const void *salt,
196 size_t salt_len, 196 size_t salt_len,
197 ...) 197 ...)
198{ 198{
199 va_list argp; 199 va_list argp;
200 200
201 va_start (argp, salt_len); 201 va_start(argp, salt_len);
202 GNUNET_CRYPTO_symmetric_derive_iv_v (iv, skey, salt, salt_len, argp); 202 GNUNET_CRYPTO_symmetric_derive_iv_v(iv, skey, salt, salt_len, argp);
203 va_end (argp); 203 va_end(argp);
204} 204}
205 205
206 206
@@ -214,33 +214,33 @@ GNUNET_CRYPTO_symmetric_derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationV
214 * @param argp pairs of void * & size_t for context chunks, terminated by NULL 214 * @param argp pairs of void * & size_t for context chunks, terminated by NULL
215 */ 215 */
216void 216void
217GNUNET_CRYPTO_symmetric_derive_iv_v (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv, 217GNUNET_CRYPTO_symmetric_derive_iv_v(struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
218 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey, 218 const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
219 const void *salt, 219 const void *salt,
220 size_t salt_len, 220 size_t salt_len,
221 va_list argp) 221 va_list argp)
222{ 222{
223 char aes_salt[salt_len + 4]; 223 char aes_salt[salt_len + 4];
224 char twofish_salt[salt_len + 4]; 224 char twofish_salt[salt_len + 4];
225 225
226 GNUNET_memcpy (aes_salt, salt, salt_len); 226 GNUNET_memcpy(aes_salt, salt, salt_len);
227 GNUNET_memcpy (&aes_salt[salt_len], "AES!", 4); 227 GNUNET_memcpy(&aes_salt[salt_len], "AES!", 4);
228 GNUNET_memcpy (twofish_salt, salt, salt_len); 228 GNUNET_memcpy(twofish_salt, salt, salt_len);
229 GNUNET_memcpy (&twofish_salt[salt_len], "FISH", 4); 229 GNUNET_memcpy(&twofish_salt[salt_len], "FISH", 4);
230 GNUNET_CRYPTO_kdf_v (iv->aes_iv, 230 GNUNET_CRYPTO_kdf_v(iv->aes_iv,
231 sizeof (iv->aes_iv), 231 sizeof(iv->aes_iv),
232 aes_salt, 232 aes_salt,
233 salt_len + 4, 233 salt_len + 4,
234 skey->aes_key, 234 skey->aes_key,
235 sizeof (skey->aes_key), 235 sizeof(skey->aes_key),
236 argp); 236 argp);
237 GNUNET_CRYPTO_kdf_v (iv->twofish_iv, 237 GNUNET_CRYPTO_kdf_v(iv->twofish_iv,
238 sizeof (iv->twofish_iv), 238 sizeof(iv->twofish_iv),
239 twofish_salt, 239 twofish_salt,
240 salt_len + 4, 240 salt_len + 4,
241 skey->twofish_key, 241 skey->twofish_key,
242 sizeof (skey->twofish_key), 242 sizeof(skey->twofish_key),
243 argp); 243 argp);
244} 244}
245 245
246/* end of crypto_symmetric.c */ 246/* end of crypto_symmetric.c */
diff --git a/src/util/disk.c b/src/util/disk.c
index 959cb62cf..450a19ab1 100644
--- a/src/util/disk.c
+++ b/src/util/disk.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/disk.c 21 * @file util/disk.c
22 * @brief disk IO convenience methods 22 * @brief disk IO convenience methods
@@ -28,13 +28,13 @@
28#include "gnunet_strings_lib.h" 28#include "gnunet_strings_lib.h"
29#include "gnunet_disk_lib.h" 29#include "gnunet_disk_lib.h"
30 30
31#define LOG(kind, ...) GNUNET_log_from (kind, "util-disk", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-disk", __VA_ARGS__)
32 32
33#define LOG_STRERROR(kind, syscall) \ 33#define LOG_STRERROR(kind, syscall) \
34 GNUNET_log_from_strerror (kind, "util-disk", syscall) 34 GNUNET_log_from_strerror(kind, "util-disk", syscall)
35 35
36#define LOG_STRERROR_FILE(kind, syscall, filename) \ 36#define LOG_STRERROR_FILE(kind, syscall, filename) \
37 GNUNET_log_from_strerror_file (kind, "util-disk", syscall, filename) 37 GNUNET_log_from_strerror_file(kind, "util-disk", syscall, filename)
38 38
39/** 39/**
40 * Block size for IO for copying files. 40 * Block size for IO for copying files.
@@ -58,15 +58,14 @@
58#ifndef S_ISLNK 58#ifndef S_ISLNK
59#define _IFMT 0170000 /* type of file */ 59#define _IFMT 0170000 /* type of file */
60#define _IFLNK 0120000 /* symbolic link */ 60#define _IFLNK 0120000 /* symbolic link */
61#define S_ISLNK(m) (((m) &_IFMT) == _IFLNK) 61#define S_ISLNK(m) (((m) & _IFMT) == _IFLNK)
62#endif 62#endif
63 63
64 64
65/** 65/**
66 * Handle used to manage a pipe. 66 * Handle used to manage a pipe.
67 */ 67 */
68struct GNUNET_DISK_PipeHandle 68struct GNUNET_DISK_PipeHandle {
69{
70 /** 69 /**
71 * File descriptors for the pipe. 70 * File descriptors for the pipe.
72 * One or both of them could be NULL. 71 * One or both of them could be NULL.
@@ -79,8 +78,7 @@ struct GNUNET_DISK_PipeHandle
79 * Closure for the recursion to determine the file size 78 * Closure for the recursion to determine the file size
80 * of a directory. 79 * of a directory.
81 */ 80 */
82struct GetFileSizeData 81struct GetFileSizeData {
83{
84 /** 82 /**
85 * Set to the total file size. 83 * Set to the total file size.
86 */ 84 */
@@ -107,7 +105,7 @@ struct GetFileSizeData
107 * @return file permissions, UNIX style 105 * @return file permissions, UNIX style
108 */ 106 */
109static int 107static int
110translate_unix_perms (enum GNUNET_DISK_AccessPermissions perm) 108translate_unix_perms(enum GNUNET_DISK_AccessPermissions perm)
111{ 109{
112 int mode; 110 int mode;
113 111
@@ -145,41 +143,41 @@ translate_unix_perms (enum GNUNET_DISK_AccessPermissions perm)
145 * @return #GNUNET_SYSERR on serious errors, otherwise #GNUNET_OK 143 * @return #GNUNET_SYSERR on serious errors, otherwise #GNUNET_OK
146 */ 144 */
147static int 145static int
148getSizeRec (void *cls, const char *fn) 146getSizeRec(void *cls, const char *fn)
149{ 147{
150 struct GetFileSizeData *gfsd = cls; 148 struct GetFileSizeData *gfsd = cls;
151 149
152#if defined(HAVE_STAT64) && \ 150#if defined(HAVE_STAT64) && \
153 ! (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64) 151 !(defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS == 64)
154 STRUCT_STAT64 buf; 152 STRUCT_STAT64 buf;
155 153
156 if (0 != stat64 (fn, &buf)) 154 if (0 != stat64(fn, &buf))
157 { 155 {
158 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat64", fn); 156 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_DEBUG, "stat64", fn);
159 return GNUNET_SYSERR; 157 return GNUNET_SYSERR;
160 } 158 }
161#else 159#else
162 struct stat buf; 160 struct stat buf;
163 161
164 if (0 != stat (fn, &buf)) 162 if (0 != stat(fn, &buf))
165 { 163 {
166 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "stat", fn); 164 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_DEBUG, "stat", fn);
167 return GNUNET_SYSERR; 165 return GNUNET_SYSERR;
168 } 166 }
169#endif 167#endif
170 if ((S_ISDIR (buf.st_mode)) && (gfsd->single_file_mode == GNUNET_YES)) 168 if ((S_ISDIR(buf.st_mode)) && (gfsd->single_file_mode == GNUNET_YES))
171 { 169 {
172 errno = EISDIR; 170 errno = EISDIR;
173 return GNUNET_SYSERR;
174 }
175 if ((! S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
176 gfsd->total += buf.st_size;
177 if ((S_ISDIR (buf.st_mode)) && (0 == access (fn, X_OK)) &&
178 ((! S_ISLNK (buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
179 {
180 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan (fn, &getSizeRec, gfsd))
181 return GNUNET_SYSERR; 171 return GNUNET_SYSERR;
182 } 172 }
173 if ((!S_ISLNK(buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES))
174 gfsd->total += buf.st_size;
175 if ((S_ISDIR(buf.st_mode)) && (0 == access(fn, X_OK)) &&
176 ((!S_ISLNK(buf.st_mode)) || (gfsd->include_sym_links == GNUNET_YES)))
177 {
178 if (GNUNET_SYSERR == GNUNET_DISK_directory_scan(fn, &getSizeRec, gfsd))
179 return GNUNET_SYSERR;
180 }
183 return GNUNET_OK; 181 return GNUNET_OK;
184} 182}
185 183
@@ -191,12 +189,12 @@ getSizeRec (void *cls, const char *fn)
191 * @return #GNUNET_YES if invalid, #GNUNET_NO if valid 189 * @return #GNUNET_YES if invalid, #GNUNET_NO if valid
192 */ 190 */
193int 191int
194GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h) 192GNUNET_DISK_handle_invalid(const struct GNUNET_DISK_FileHandle *h)
195{ 193{
196#ifdef MINGW 194#ifdef MINGW
197 return ((! h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO; 195 return ((!h) || (h->h == INVALID_HANDLE_VALUE)) ? GNUNET_YES : GNUNET_NO;
198#else 196#else
199 return ((! h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO; 197 return ((!h) || (h->fd == -1)) ? GNUNET_YES : GNUNET_NO;
200#endif 198#endif
201} 199}
202 200
@@ -208,22 +206,22 @@ GNUNET_DISK_handle_invalid (const struct GNUNET_DISK_FileHandle *h)
208 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 206 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
209 */ 207 */
210int 208int
211GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh, off_t *size) 209GNUNET_DISK_file_handle_size(struct GNUNET_DISK_FileHandle *fh, off_t *size)
212{ 210{
213#if WINDOWS 211#if WINDOWS
214 BOOL b; 212 BOOL b;
215 LARGE_INTEGER li; 213 LARGE_INTEGER li;
216 b = GetFileSizeEx (fh->h, &li); 214 b = GetFileSizeEx(fh->h, &li);
217 if (! b) 215 if (!b)
218 { 216 {
219 SetErrnoFromWinError (GetLastError ()); 217 SetErrnoFromWinError(GetLastError());
220 return GNUNET_SYSERR; 218 return GNUNET_SYSERR;
221 } 219 }
222 *size = (off_t) li.QuadPart; 220 *size = (off_t)li.QuadPart;
223#else 221#else
224 struct stat sbuf; 222 struct stat sbuf;
225 223
226 if (0 != fstat (fh->fd, &sbuf)) 224 if (0 != fstat(fh->fd, &sbuf))
227 return GNUNET_SYSERR; 225 return GNUNET_SYSERR;
228 *size = sbuf.st_size; 226 *size = sbuf.st_size;
229#endif 227#endif
@@ -240,35 +238,35 @@ GNUNET_DISK_file_handle_size (struct GNUNET_DISK_FileHandle *fh, off_t *size)
240 * @return the new position on success, #GNUNET_SYSERR otherwise 238 * @return the new position on success, #GNUNET_SYSERR otherwise
241 */ 239 */
242off_t 240off_t
243GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle *h, 241GNUNET_DISK_file_seek(const struct GNUNET_DISK_FileHandle *h,
244 off_t offset, 242 off_t offset,
245 enum GNUNET_DISK_Seek whence) 243 enum GNUNET_DISK_Seek whence)
246{ 244{
247 if (h == NULL) 245 if (h == NULL)
248 { 246 {
249 errno = EINVAL; 247 errno = EINVAL;
250 return GNUNET_SYSERR; 248 return GNUNET_SYSERR;
251 } 249 }
252 250
253#ifdef MINGW 251#ifdef MINGW
254 LARGE_INTEGER li; 252 LARGE_INTEGER li;
255 LARGE_INTEGER new_pos; 253 LARGE_INTEGER new_pos;
256 BOOL b; 254 BOOL b;
257 255
258 static DWORD t[] = {FILE_BEGIN, FILE_CURRENT, FILE_END}; 256 static DWORD t[] = { FILE_BEGIN, FILE_CURRENT, FILE_END };
259 li.QuadPart = offset; 257 li.QuadPart = offset;
260 258
261 b = SetFilePointerEx (h->h, li, &new_pos, t[whence]); 259 b = SetFilePointerEx(h->h, li, &new_pos, t[whence]);
262 if (b == 0) 260 if (b == 0)
263 { 261 {
264 SetErrnoFromWinError (GetLastError ()); 262 SetErrnoFromWinError(GetLastError());
265 return GNUNET_SYSERR; 263 return GNUNET_SYSERR;
266 } 264 }
267 return (off_t) new_pos.QuadPart; 265 return (off_t)new_pos.QuadPart;
268#else 266#else
269 static int t[] = {SEEK_SET, SEEK_CUR, SEEK_END}; 267 static int t[] = { SEEK_SET, SEEK_CUR, SEEK_END };
270 268
271 return lseek (h->fd, offset, t[whence]); 269 return lseek(h->fd, offset, t[whence]);
272#endif 270#endif
273} 271}
274 272
@@ -288,19 +286,19 @@ GNUNET_DISK_file_seek (const struct GNUNET_DISK_FileHandle *h,
288 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 286 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
289 */ 287 */
290int 288int
291GNUNET_DISK_file_size (const char *filename, 289GNUNET_DISK_file_size(const char *filename,
292 uint64_t *size, 290 uint64_t *size,
293 int include_symbolic_links, 291 int include_symbolic_links,
294 int single_file_mode) 292 int single_file_mode)
295{ 293{
296 struct GetFileSizeData gfsd; 294 struct GetFileSizeData gfsd;
297 int ret; 295 int ret;
298 296
299 GNUNET_assert (size != NULL); 297 GNUNET_assert(size != NULL);
300 gfsd.total = 0; 298 gfsd.total = 0;
301 gfsd.include_sym_links = include_symbolic_links; 299 gfsd.include_sym_links = include_symbolic_links;
302 gfsd.single_file_mode = single_file_mode; 300 gfsd.single_file_mode = single_file_mode;
303 ret = getSizeRec (&gfsd, filename); 301 ret = getSizeRec(&gfsd, filename);
304 *size = gfsd.total; 302 *size = gfsd.total;
305 return ret; 303 return ret;
306} 304}
@@ -322,9 +320,9 @@ GNUNET_DISK_file_size (const char *filename,
322 * @return #GNUNET_OK on success 320 * @return #GNUNET_OK on success
323 */ 321 */
324int 322int
325GNUNET_DISK_file_get_identifiers (const char *filename, 323GNUNET_DISK_file_get_identifiers(const char *filename,
326 uint64_t *dev, 324 uint64_t *dev,
327 uint64_t *ino) 325 uint64_t *ino)
328{ 326{
329#if WINDOWS 327#if WINDOWS
330 { 328 {
@@ -333,19 +331,19 @@ GNUNET_DISK_file_get_identifiers (const char *filename,
333 BY_HANDLE_FILE_INFORMATION info; 331 BY_HANDLE_FILE_INFORMATION info;
334 int succ; 332 int succ;
335 333
336 fh = GNUNET_DISK_file_open (filename, 334 fh = GNUNET_DISK_file_open(filename,
337 GNUNET_DISK_OPEN_READ, 335 GNUNET_DISK_OPEN_READ,
338 GNUNET_DISK_PERM_NONE); 336 GNUNET_DISK_PERM_NONE);
339 if (NULL == fh) 337 if (NULL == fh)
340 return GNUNET_SYSERR; 338 return GNUNET_SYSERR;
341 succ = GetFileInformationByHandle (fh->h, &info); 339 succ = GetFileInformationByHandle(fh->h, &info);
342 GNUNET_DISK_file_close (fh); 340 GNUNET_DISK_file_close(fh);
343 if (! succ) 341 if (!succ)
344 { 342 {
345 return GNUNET_SYSERR; 343 return GNUNET_SYSERR;
346 } 344 }
347 *dev = info.dwVolumeSerialNumber; 345 *dev = info.dwVolumeSerialNumber;
348 *ino = ((((uint64_t) info.nFileIndexHigh) << (sizeof (DWORD) * 8)) | 346 *ino = ((((uint64_t)info.nFileIndexHigh) << (sizeof(DWORD) * 8)) |
349 info.nFileIndexLow); 347 info.nFileIndexLow);
350 } 348 }
351#else /* !WINDOWS */ 349#else /* !WINDOWS */
@@ -353,11 +351,11 @@ GNUNET_DISK_file_get_identifiers (const char *filename,
353 { 351 {
354 struct stat sbuf; 352 struct stat sbuf;
355 353
356 if (0 != stat (filename, &sbuf)) 354 if (0 != stat(filename, &sbuf))
357 { 355 {
358 return GNUNET_SYSERR; 356 return GNUNET_SYSERR;
359 } 357 }
360 *ino = (uint64_t) sbuf.st_ino; 358 *ino = (uint64_t)sbuf.st_ino;
361 } 359 }
362#else 360#else
363 *ino = 0; 361 *ino = 0;
@@ -366,22 +364,22 @@ GNUNET_DISK_file_get_identifiers (const char *filename,
366 { 364 {
367 struct statvfs fbuf; 365 struct statvfs fbuf;
368 366
369 if (0 != statvfs (filename, &fbuf)) 367 if (0 != statvfs(filename, &fbuf))
370 { 368 {
371 return GNUNET_SYSERR; 369 return GNUNET_SYSERR;
372 } 370 }
373 *dev = (uint64_t) fbuf.f_fsid; 371 *dev = (uint64_t)fbuf.f_fsid;
374 } 372 }
375#elif HAVE_STATFS 373#elif HAVE_STATFS
376 { 374 {
377 struct statfs fbuf; 375 struct statfs fbuf;
378 376
379 if (0 != statfs (filename, &fbuf)) 377 if (0 != statfs(filename, &fbuf))
380 { 378 {
381 return GNUNET_SYSERR; 379 return GNUNET_SYSERR;
382 } 380 }
383 *dev = 381 *dev =
384 ((uint64_t) fbuf.f_fsid.val[0]) << 32 || ((uint64_t) fbuf.f_fsid.val[1]); 382 ((uint64_t)fbuf.f_fsid.val[0]) << 32 || ((uint64_t)fbuf.f_fsid.val[1]);
385 } 383 }
386#else 384#else
387 *dev = 0; 385 *dev = 0;
@@ -398,7 +396,7 @@ GNUNET_DISK_file_get_identifiers (const char *filename,
398 * @return name ready for passing to 'mktemp' or 'mkdtemp', NULL on error 396 * @return name ready for passing to 'mktemp' or 'mkdtemp', NULL on error
399 */ 397 */
400static char * 398static char *
401mktemp_name (const char *t) 399mktemp_name(const char *t)
402{ 400{
403 const char *tmpdir; 401 const char *tmpdir;
404 char *tmpl; 402 char *tmpl;
@@ -406,33 +404,33 @@ mktemp_name (const char *t)
406 404
407 if ((t[0] != '/') && (t[0] != '\\') 405 if ((t[0] != '/') && (t[0] != '\\')
408#if WINDOWS 406#if WINDOWS
409 && ! (isalpha ((int) t[0]) && (t[0] != '\0') && (t[1] == ':')) 407 && !(isalpha((int)t[0]) && (t[0] != '\0') && (t[1] == ':'))
410#endif 408#endif
411 ) 409 )
412 { 410 {
413 /* FIXME: This uses system codepage on W32, not UTF-8 */ 411 /* FIXME: This uses system codepage on W32, not UTF-8 */
414 tmpdir = getenv ("TMPDIR"); 412 tmpdir = getenv("TMPDIR");
415 if (NULL == tmpdir) 413 if (NULL == tmpdir)
416 tmpdir = getenv ("TMP"); 414 tmpdir = getenv("TMP");
417 if (NULL == tmpdir) 415 if (NULL == tmpdir)
418 tmpdir = getenv ("TEMP"); 416 tmpdir = getenv("TEMP");
419 if (NULL == tmpdir) 417 if (NULL == tmpdir)
420 tmpdir = "/tmp"; 418 tmpdir = "/tmp";
421 GNUNET_asprintf (&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX"); 419 GNUNET_asprintf(&tmpl, "%s/%s%s", tmpdir, t, "XXXXXX");
422 } 420 }
423 else 421 else
424 { 422 {
425 GNUNET_asprintf (&tmpl, "%s%s", t, "XXXXXX"); 423 GNUNET_asprintf(&tmpl, "%s%s", t, "XXXXXX");
426 } 424 }
427#ifdef MINGW 425#ifdef MINGW
428 fn = (char *) GNUNET_malloc (MAX_PATH + 1); 426 fn = (char *)GNUNET_malloc(MAX_PATH + 1);
429 if (ERROR_SUCCESS != plibc_conv_to_win_path (tmpl, fn)) 427 if (ERROR_SUCCESS != plibc_conv_to_win_path(tmpl, fn))
430 { 428 {
431 GNUNET_free (fn); 429 GNUNET_free(fn);
432 GNUNET_free (tmpl); 430 GNUNET_free(tmpl);
433 return NULL; 431 return NULL;
434 } 432 }
435 GNUNET_free (tmpl); 433 GNUNET_free(tmpl);
436#else 434#else
437 fn = tmpl; 435 fn = tmpl;
438#endif 436#endif
@@ -442,32 +440,32 @@ mktemp_name (const char *t)
442 440
443#if WINDOWS 441#if WINDOWS
444static char * 442static char *
445mkdtemp (char *fn) 443mkdtemp(char *fn)
446{ 444{
447 char *random_fn; 445 char *random_fn;
448 char *tfn; 446 char *tfn;
449 447
450 while (1) 448 while (1)
451 {
452 tfn = GNUNET_strdup (fn);
453 random_fn = _mktemp (tfn);
454 if (NULL == random_fn)
455 {
456 GNUNET_free (tfn);
457 return NULL;
458 }
459 /* FIXME: assume fn to be UTF-8-encoded and do the right thing */
460 if (0 == CreateDirectoryA (tfn, NULL))
461 { 449 {
462 DWORD error = GetLastError (); 450 tfn = GNUNET_strdup(fn);
463 GNUNET_free (tfn); 451 random_fn = _mktemp(tfn);
464 if (ERROR_ALREADY_EXISTS == error) 452 if (NULL == random_fn)
465 continue; 453 {
466 return NULL; 454 GNUNET_free(tfn);
455 return NULL;
456 }
457 /* FIXME: assume fn to be UTF-8-encoded and do the right thing */
458 if (0 == CreateDirectoryA(tfn, NULL))
459 {
460 DWORD error = GetLastError();
461 GNUNET_free(tfn);
462 if (ERROR_ALREADY_EXISTS == error)
463 continue;
464 return NULL;
465 }
466 break;
467 } 467 }
468 break; 468 strcpy(fn, tfn);
469 }
470 strcpy (fn, tfn);
471 return fn; 469 return fn;
472} 470}
473 471
@@ -481,9 +479,9 @@ mkdtemp (char *fn)
481 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set 479 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set
482 */ 480 */
483void 481void
484GNUNET_DISK_fix_permissions (const char *fn, 482GNUNET_DISK_fix_permissions(const char *fn,
485 int require_uid_match, 483 int require_uid_match,
486 int require_gid_match) 484 int require_gid_match)
487{ 485{
488 /* nothing on W32 */ 486 /* nothing on W32 */
489} 487}
@@ -499,9 +497,9 @@ GNUNET_DISK_fix_permissions (const char *fn,
499 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set 497 * @param require_gid_match #GNUNET_YES means 770 unless @a require_uid_match is set
500 */ 498 */
501void 499void
502GNUNET_DISK_fix_permissions (const char *fn, 500GNUNET_DISK_fix_permissions(const char *fn,
503 int require_uid_match, 501 int require_uid_match,
504 int require_gid_match) 502 int require_gid_match)
505{ 503{
506 mode_t mode; 504 mode_t mode;
507 505
@@ -512,8 +510,8 @@ GNUNET_DISK_fix_permissions (const char *fn,
512 else 510 else
513 mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH | 511 mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP | S_IXGRP | S_IROTH |
514 S_IWOTH | S_IXOTH; 512 S_IWOTH | S_IXOTH;
515 if (0 != chmod (fn, mode)) 513 if (0 != chmod(fn, mode))
516 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "chmod", fn); 514 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "chmod", fn);
517} 515}
518 516
519#endif 517#endif
@@ -530,21 +528,21 @@ GNUNET_DISK_fix_permissions (const char *fn,
530 * file on disk in directory for temporary files 528 * file on disk in directory for temporary files
531 */ 529 */
532char * 530char *
533GNUNET_DISK_mkdtemp (const char *t) 531GNUNET_DISK_mkdtemp(const char *t)
534{ 532{
535 char *fn; 533 char *fn;
536 mode_t omask; 534 mode_t omask;
537 535
538 omask = umask (S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH); 536 omask = umask(S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH);
539 fn = mktemp_name (t); 537 fn = mktemp_name(t);
540 if (fn != mkdtemp (fn)) 538 if (fn != mkdtemp(fn))
541 { 539 {
542 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdtemp", fn); 540 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "mkdtemp", fn);
543 GNUNET_free (fn); 541 GNUNET_free(fn);
544 umask (omask); 542 umask(omask);
545 return NULL; 543 return NULL;
546 } 544 }
547 umask (omask); 545 umask(omask);
548 return fn; 546 return fn;
549} 547}
550 548
@@ -557,22 +555,23 @@ GNUNET_DISK_mkdtemp (const char *t)
557 * @param fil name of the file to back up 555 * @param fil name of the file to back up
558 */ 556 */
559void 557void
560GNUNET_DISK_file_backup (const char *fil) 558GNUNET_DISK_file_backup(const char *fil)
561{ 559{
562 size_t slen; 560 size_t slen;
563 char *target; 561 char *target;
564 unsigned int num; 562 unsigned int num;
565 563
566 slen = strlen (fil) + 20; 564 slen = strlen(fil) + 20;
567 target = GNUNET_malloc (slen); 565 target = GNUNET_malloc(slen);
568 num = 0; 566 num = 0;
569 do 567 do
570 { 568 {
571 GNUNET_snprintf (target, slen, "%s.%u~", fil, num++); 569 GNUNET_snprintf(target, slen, "%s.%u~", fil, num++);
572 } while (0 == access (target, F_OK)); 570 }
573 if (0 != rename (fil, target)) 571 while (0 == access(target, F_OK));
574 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "rename", fil); 572 if (0 != rename(fil, target))
575 GNUNET_free (target); 573 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "rename", fil);
574 GNUNET_free(target);
576} 575}
577 576
578 577
@@ -588,24 +587,24 @@ GNUNET_DISK_file_backup (const char *fil)
588 * file on disk in directory for temporary files 587 * file on disk in directory for temporary files
589 */ 588 */
590char * 589char *
591GNUNET_DISK_mktemp (const char *t) 590GNUNET_DISK_mktemp(const char *t)
592{ 591{
593 int fd; 592 int fd;
594 char *fn; 593 char *fn;
595 mode_t omask; 594 mode_t omask;
596 595
597 omask = umask (S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH); 596 omask = umask(S_IWGRP | S_IWOTH | S_IRGRP | S_IROTH);
598 fn = mktemp_name (t); 597 fn = mktemp_name(t);
599 if (-1 == (fd = mkstemp (fn))) 598 if (-1 == (fd = mkstemp(fn)))
600 { 599 {
601 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn); 600 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "mkstemp", fn);
602 GNUNET_free (fn); 601 GNUNET_free(fn);
603 umask (omask); 602 umask(omask);
604 return NULL; 603 return NULL;
605 } 604 }
606 umask (omask); 605 umask(omask);
607 if (0 != close (fd)) 606 if (0 != close(fd))
608 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "close", fn); 607 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "close", fn);
609 return fn; 608 return fn;
610} 609}
611 610
@@ -623,34 +622,34 @@ GNUNET_DISK_mktemp (const char *t)
623 * does not exist or stat'ed 622 * does not exist or stat'ed
624 */ 623 */
625int 624int
626GNUNET_DISK_directory_test (const char *fil, int is_readable) 625GNUNET_DISK_directory_test(const char *fil, int is_readable)
627{ 626{
628 struct stat filestat; 627 struct stat filestat;
629 int ret; 628 int ret;
630 629
631 ret = stat (fil, &filestat); 630 ret = stat(fil, &filestat);
632 if (ret != 0) 631 if (ret != 0)
633 { 632 {
634 if (errno != ENOENT) 633 if (errno != ENOENT)
635 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", fil); 634 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", fil);
636 return GNUNET_SYSERR; 635 return GNUNET_SYSERR;
637 } 636 }
638 if (! S_ISDIR (filestat.st_mode)) 637 if (!S_ISDIR(filestat.st_mode))
639 { 638 {
640 LOG (GNUNET_ERROR_TYPE_INFO, 639 LOG(GNUNET_ERROR_TYPE_INFO,
641 "A file already exits with the same name %s\n", 640 "A file already exits with the same name %s\n",
642 fil); 641 fil);
643 return GNUNET_NO; 642 return GNUNET_NO;
644 } 643 }
645 if (GNUNET_YES == is_readable) 644 if (GNUNET_YES == is_readable)
646 ret = access (fil, R_OK | X_OK); 645 ret = access(fil, R_OK | X_OK);
647 else 646 else
648 ret = access (fil, X_OK); 647 ret = access(fil, X_OK);
649 if (ret < 0) 648 if (ret < 0)
650 { 649 {
651 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", fil); 650 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "access", fil);
652 return GNUNET_NO; 651 return GNUNET_NO;
653 } 652 }
654 return GNUNET_YES; 653 return GNUNET_YES;
655} 654}
656 655
@@ -664,40 +663,40 @@ GNUNET_DISK_directory_test (const char *fil, int is_readable)
664 * else (will print an error message in that case, too). 663 * else (will print an error message in that case, too).
665 */ 664 */
666int 665int
667GNUNET_DISK_file_test (const char *fil) 666GNUNET_DISK_file_test(const char *fil)
668{ 667{
669 struct stat filestat; 668 struct stat filestat;
670 int ret; 669 int ret;
671 char *rdir; 670 char *rdir;
672 671
673 rdir = GNUNET_STRINGS_filename_expand (fil); 672 rdir = GNUNET_STRINGS_filename_expand(fil);
674 if (rdir == NULL) 673 if (rdir == NULL)
675 return GNUNET_SYSERR; 674 return GNUNET_SYSERR;
676 675
677 ret = stat (rdir, &filestat); 676 ret = stat(rdir, &filestat);
678 if (ret != 0) 677 if (ret != 0)
679 {
680 if (errno != ENOENT)
681 { 678 {
682 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", rdir); 679 if (errno != ENOENT)
683 GNUNET_free (rdir); 680 {
681 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", rdir);
682 GNUNET_free(rdir);
683 return GNUNET_SYSERR;
684 }
685 GNUNET_free(rdir);
686 return GNUNET_NO;
687 }
688 if (!S_ISREG(filestat.st_mode))
689 {
690 GNUNET_free(rdir);
691 return GNUNET_NO;
692 }
693 if (access(rdir, F_OK) < 0)
694 {
695 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "access", rdir);
696 GNUNET_free(rdir);
684 return GNUNET_SYSERR; 697 return GNUNET_SYSERR;
685 } 698 }
686 GNUNET_free (rdir); 699 GNUNET_free(rdir);
687 return GNUNET_NO;
688 }
689 if (! S_ISREG (filestat.st_mode))
690 {
691 GNUNET_free (rdir);
692 return GNUNET_NO;
693 }
694 if (access (rdir, F_OK) < 0)
695 {
696 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", rdir);
697 GNUNET_free (rdir);
698 return GNUNET_SYSERR;
699 }
700 GNUNET_free (rdir);
701 return GNUNET_YES; 700 return GNUNET_YES;
702} 701}
703 702
@@ -709,7 +708,7 @@ GNUNET_DISK_file_test (const char *fil)
709 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 708 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
710 */ 709 */
711int 710int
712GNUNET_DISK_directory_create (const char *dir) 711GNUNET_DISK_directory_create(const char *dir)
713{ 712{
714 char *rdir; 713 char *rdir;
715 unsigned int len; 714 unsigned int len;
@@ -717,105 +716,105 @@ GNUNET_DISK_directory_create (const char *dir)
717 unsigned int pos2; 716 unsigned int pos2;
718 int ret = GNUNET_OK; 717 int ret = GNUNET_OK;
719 718
720 rdir = GNUNET_STRINGS_filename_expand (dir); 719 rdir = GNUNET_STRINGS_filename_expand(dir);
721 if (rdir == NULL) 720 if (rdir == NULL)
722 { 721 {
723 GNUNET_break (0); 722 GNUNET_break(0);
724 return GNUNET_SYSERR; 723 return GNUNET_SYSERR;
725 } 724 }
726 725
727 len = strlen (rdir); 726 len = strlen(rdir);
728#ifndef MINGW 727#ifndef MINGW
729 pos = 1; /* skip heading '/' */ 728 pos = 1; /* skip heading '/' */
730#else 729#else
731 /* Local or Network path? */ 730 /* Local or Network path? */
732 if (strncmp (rdir, "\\\\", 2) == 0) 731 if (strncmp(rdir, "\\\\", 2) == 0)
733 {
734 pos = 2;
735 while (rdir[pos])
736 { 732 {
737 if (rdir[pos] == '\\') 733 pos = 2;
738 { 734 while (rdir[pos])
739 pos++; 735 {
740 break; 736 if (rdir[pos] == '\\')
741 } 737 {
742 pos++; 738 pos++;
739 break;
740 }
741 pos++;
742 }
743 } 743 }
744 }
745 else 744 else
746 { 745 {
747 pos = 3; /* strlen("C:\\") */ 746 pos = 3; /* strlen("C:\\") */
748 } 747 }
749#endif 748#endif
750 /* Check which low level directories already exist */ 749 /* Check which low level directories already exist */
751 pos2 = len; 750 pos2 = len;
752 rdir[len] = DIR_SEPARATOR; 751 rdir[len] = DIR_SEPARATOR;
753 while (pos <= pos2) 752 while (pos <= pos2)
754 {
755 if (DIR_SEPARATOR == rdir[pos2])
756 { 753 {
757 rdir[pos2] = '\0'; 754 if (DIR_SEPARATOR == rdir[pos2])
758 ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO); 755 {
759 if (GNUNET_NO == ret) 756 rdir[pos2] = '\0';
760 { 757 ret = GNUNET_DISK_directory_test(rdir, GNUNET_NO);
761 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 758 if (GNUNET_NO == ret)
762 "Creating directory `%s' failed", 759 {
763 rdir); 760 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
764 GNUNET_free (rdir); 761 "Creating directory `%s' failed",
765 return GNUNET_SYSERR; 762 rdir);
766 } 763 GNUNET_free(rdir);
767 rdir[pos2] = DIR_SEPARATOR; 764 return GNUNET_SYSERR;
768 if (GNUNET_YES == ret) 765 }
769 { 766 rdir[pos2] = DIR_SEPARATOR;
770 pos2++; 767 if (GNUNET_YES == ret)
771 break; 768 {
772 } 769 pos2++;
770 break;
771 }
772 }
773 pos2--;
773 } 774 }
774 pos2--;
775 }
776 rdir[len] = '\0'; 775 rdir[len] = '\0';
777 if (pos < pos2) 776 if (pos < pos2)
778 pos = pos2; 777 pos = pos2;
779 /* Start creating directories */ 778 /* Start creating directories */
780 while (pos <= len) 779 while (pos <= len)
781 {
782 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
783 { 780 {
784 rdir[pos] = '\0'; 781 if ((rdir[pos] == DIR_SEPARATOR) || (pos == len))
785 ret = GNUNET_DISK_directory_test (rdir, GNUNET_NO); 782 {
786 if (GNUNET_NO == ret) 783 rdir[pos] = '\0';
787 { 784 ret = GNUNET_DISK_directory_test(rdir, GNUNET_NO);
788 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 785 if (GNUNET_NO == ret)
789 "Creating directory `%s' failed", 786 {
790 rdir); 787 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
791 GNUNET_free (rdir); 788 "Creating directory `%s' failed",
792 return GNUNET_SYSERR; 789 rdir);
793 } 790 GNUNET_free(rdir);
794 if (GNUNET_SYSERR == ret) 791 return GNUNET_SYSERR;
795 { 792 }
793 if (GNUNET_SYSERR == ret)
794 {
796#ifndef MINGW 795#ifndef MINGW
797 ret = mkdir (rdir, 796 ret = mkdir(rdir,
798 S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | 797 S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH |
799 S_IXOTH); /* 755 */ 798 S_IXOTH); /* 755 */
800#else 799#else
801 wchar_t wrdir[MAX_PATH + 1]; 800 wchar_t wrdir[MAX_PATH + 1];
802 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv (rdir, wrdir)) 801 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(rdir, wrdir))
803 ret = ! CreateDirectoryW (wrdir, NULL); 802 ret = !CreateDirectoryW(wrdir, NULL);
804 else 803 else
805 ret = 1; 804 ret = 1;
806#endif 805#endif
807 if ((ret != 0) && (errno != EEXIST)) 806 if ((ret != 0) && (errno != EEXIST))
808 { 807 {
809 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "mkdir", rdir); 808 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "mkdir", rdir);
810 GNUNET_free (rdir); 809 GNUNET_free(rdir);
811 return GNUNET_SYSERR; 810 return GNUNET_SYSERR;
811 }
812 }
813 rdir[pos] = DIR_SEPARATOR;
812 } 814 }
813 } 815 pos++;
814 rdir[pos] = DIR_SEPARATOR;
815 } 816 }
816 pos++; 817 GNUNET_free(rdir);
817 }
818 GNUNET_free (rdir);
819 return GNUNET_OK; 818 return GNUNET_OK;
820} 819}
821 820
@@ -830,40 +829,40 @@ GNUNET_DISK_directory_create (const char *dir)
830 * exists but is not writeable for us 829 * exists but is not writeable for us
831 */ 830 */
832int 831int
833GNUNET_DISK_directory_create_for_file (const char *filename) 832GNUNET_DISK_directory_create_for_file(const char *filename)
834{ 833{
835 char *rdir; 834 char *rdir;
836 size_t len; 835 size_t len;
837 int ret; 836 int ret;
838 int eno; 837 int eno;
839 838
840 rdir = GNUNET_STRINGS_filename_expand (filename); 839 rdir = GNUNET_STRINGS_filename_expand(filename);
841 if (NULL == rdir) 840 if (NULL == rdir)
842 { 841 {
843 errno = EINVAL; 842 errno = EINVAL;
844 return GNUNET_SYSERR; 843 return GNUNET_SYSERR;
845 } 844 }
846 if (0 == access (rdir, W_OK)) 845 if (0 == access(rdir, W_OK))
847 { 846 {
848 GNUNET_free (rdir); 847 GNUNET_free(rdir);
849 return GNUNET_OK; 848 return GNUNET_OK;
850 } 849 }
851 850
852 len = strlen (rdir); 851 len = strlen(rdir);
853 while ((len > 0) && (rdir[len] != DIR_SEPARATOR)) 852 while ((len > 0) && (rdir[len] != DIR_SEPARATOR))
854 len--; 853 len--;
855 rdir[len] = '\0'; 854 rdir[len] = '\0';
856 /* The empty path is invalid and in this case refers to / */ 855 /* The empty path is invalid and in this case refers to / */
857 if (0 == len) 856 if (0 == len)
858 { 857 {
859 GNUNET_free (rdir); 858 GNUNET_free(rdir);
860 rdir = GNUNET_strdup ("/"); 859 rdir = GNUNET_strdup("/");
861 } 860 }
862 ret = GNUNET_DISK_directory_create (rdir); 861 ret = GNUNET_DISK_directory_create(rdir);
863 if ((GNUNET_OK == ret) && (0 != access (rdir, W_OK))) 862 if ((GNUNET_OK == ret) && (0 != access(rdir, W_OK)))
864 ret = GNUNET_NO; 863 ret = GNUNET_NO;
865 eno = errno; 864 eno = errno;
866 GNUNET_free (rdir); 865 GNUNET_free(rdir);
867 errno = eno; 866 errno = eno;
868 return ret; 867 return ret;
869} 868}
@@ -878,51 +877,51 @@ GNUNET_DISK_directory_create_for_file (const char *filename)
878 * @return the number of bytes read on success, #GNUNET_SYSERR on failure 877 * @return the number of bytes read on success, #GNUNET_SYSERR on failure
879 */ 878 */
880ssize_t 879ssize_t
881GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h, 880GNUNET_DISK_file_read(const struct GNUNET_DISK_FileHandle *h,
882 void *result, 881 void *result,
883 size_t len) 882 size_t len)
884{ 883{
885 if (NULL == h) 884 if (NULL == h)
886 { 885 {
887 errno = EINVAL; 886 errno = EINVAL;
888 return GNUNET_SYSERR; 887 return GNUNET_SYSERR;
889 } 888 }
890 889
891#ifdef MINGW 890#ifdef MINGW
892 DWORD bytes_read; 891 DWORD bytes_read;
893 892
894 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE) 893 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
895 {
896 if (! ReadFile (h->h, result, len, &bytes_read, NULL))
897 { 894 {
898 SetErrnoFromWinError (GetLastError ()); 895 if (!ReadFile(h->h, result, len, &bytes_read, NULL))
899 return GNUNET_SYSERR; 896 {
897 SetErrnoFromWinError(GetLastError());
898 return GNUNET_SYSERR;
899 }
900 } 900 }
901 }
902 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE) 901 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
903 {
904 if (! ReadFile (h->h, result, len, &bytes_read, h->oOverlapRead))
905 { 902 {
906 if (GetLastError () != ERROR_IO_PENDING) 903 if (!ReadFile(h->h, result, len, &bytes_read, h->oOverlapRead))
907 { 904 {
908 LOG (GNUNET_ERROR_TYPE_DEBUG, 905 if (GetLastError() != ERROR_IO_PENDING)
909 "Error reading from pipe: %u\n", 906 {
910 GetLastError ()); 907 LOG(GNUNET_ERROR_TYPE_DEBUG,
911 SetErrnoFromWinError (GetLastError ()); 908 "Error reading from pipe: %u\n",
912 return GNUNET_SYSERR; 909 GetLastError());
913 } 910 SetErrnoFromWinError(GetLastError());
914 LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n"); 911 return GNUNET_SYSERR;
915 GetOverlappedResult (h->h, h->oOverlapRead, &bytes_read, TRUE); 912 }
913 LOG(GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
914 GetOverlappedResult(h->h, h->oOverlapRead, &bytes_read, TRUE);
915 }
916 LOG(GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes from pipe\n", bytes_read);
916 } 917 }
917 LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes from pipe\n", bytes_read);
918 }
919 else 918 else
920 { 919 {
921 bytes_read = 0; 920 bytes_read = 0;
922 } 921 }
923 return bytes_read; 922 return bytes_read;
924#else 923#else
925 return read (h->fd, result, len); 924 return read(h->fd, result, len);
926#endif 925#endif
927} 926}
928 927
@@ -938,69 +937,69 @@ GNUNET_DISK_file_read (const struct GNUNET_DISK_FileHandle *h,
938 * @return the number of bytes read on success, #GNUNET_SYSERR on failure 937 * @return the number of bytes read on success, #GNUNET_SYSERR on failure
939 */ 938 */
940ssize_t 939ssize_t
941GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle *h, 940GNUNET_DISK_file_read_non_blocking(const struct GNUNET_DISK_FileHandle *h,
942 void *result, 941 void *result,
943 size_t len) 942 size_t len)
944{ 943{
945 if (NULL == h) 944 if (NULL == h)
946 { 945 {
947 errno = EINVAL; 946 errno = EINVAL;
948 return GNUNET_SYSERR; 947 return GNUNET_SYSERR;
949 } 948 }
950 949
951#ifdef MINGW 950#ifdef MINGW
952 DWORD bytes_read; 951 DWORD bytes_read;
953 952
954 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE) 953 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
955 {
956 if (! ReadFile (h->h, result, len, &bytes_read, NULL))
957 { 954 {
958 SetErrnoFromWinError (GetLastError ()); 955 if (!ReadFile(h->h, result, len, &bytes_read, NULL))
959 return GNUNET_SYSERR; 956 {
957 SetErrnoFromWinError(GetLastError());
958 return GNUNET_SYSERR;
959 }
960 } 960 }
961 }
962 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE) 961 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
963 {
964 if (! ReadFile (h->h, result, len, &bytes_read, h->oOverlapRead))
965 { 962 {
966 if (GetLastError () != ERROR_IO_PENDING) 963 if (!ReadFile(h->h, result, len, &bytes_read, h->oOverlapRead))
967 { 964 {
968 LOG (GNUNET_ERROR_TYPE_DEBUG, 965 if (GetLastError() != ERROR_IO_PENDING)
969 "Error reading from pipe: %u\n", 966 {
970 GetLastError ()); 967 LOG(GNUNET_ERROR_TYPE_DEBUG,
971 SetErrnoFromWinError (GetLastError ()); 968 "Error reading from pipe: %u\n",
972 return GNUNET_SYSERR; 969 GetLastError());
973 } 970 SetErrnoFromWinError(GetLastError());
974 else 971 return GNUNET_SYSERR;
975 { 972 }
976 LOG (GNUNET_ERROR_TYPE_DEBUG, "ReadFile() queued a read, cancelling\n"); 973 else
977 CancelIo (h->h); 974 {
978 errno = EAGAIN; 975 LOG(GNUNET_ERROR_TYPE_DEBUG, "ReadFile() queued a read, cancelling\n");
979 return GNUNET_SYSERR; 976 CancelIo(h->h);
980 } 977 errno = EAGAIN;
978 return GNUNET_SYSERR;
979 }
980 }
981 LOG(GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes\n", bytes_read);
981 } 982 }
982 LOG (GNUNET_ERROR_TYPE_DEBUG, "Read %u bytes\n", bytes_read);
983 }
984 else 983 else
985 { 984 {
986 bytes_read = 0; 985 bytes_read = 0;
987 } 986 }
988 return bytes_read; 987 return bytes_read;
989#else 988#else
990 int flags; 989 int flags;
991 ssize_t ret; 990 ssize_t ret;
992 991
993 /* set to non-blocking, read, then set back */ 992 /* set to non-blocking, read, then set back */
994 flags = fcntl (h->fd, F_GETFL); 993 flags = fcntl(h->fd, F_GETFL);
995 if (0 == (flags & O_NONBLOCK)) 994 if (0 == (flags & O_NONBLOCK))
996 (void) fcntl (h->fd, F_SETFL, flags | O_NONBLOCK); 995 (void)fcntl(h->fd, F_SETFL, flags | O_NONBLOCK);
997 ret = read (h->fd, result, len); 996 ret = read(h->fd, result, len);
998 if (0 == (flags & O_NONBLOCK)) 997 if (0 == (flags & O_NONBLOCK))
999 { 998 {
1000 int eno = errno; 999 int eno = errno;
1001 (void) fcntl (h->fd, F_SETFL, flags); 1000 (void)fcntl(h->fd, F_SETFL, flags);
1002 errno = eno; 1001 errno = eno;
1003 } 1002 }
1004 return ret; 1003 return ret;
1005#endif 1004#endif
1006} 1005}
@@ -1015,18 +1014,18 @@ GNUNET_DISK_file_read_non_blocking (const struct GNUNET_DISK_FileHandle *h,
1015 * @return number of bytes read, #GNUNET_SYSERR on failure 1014 * @return number of bytes read, #GNUNET_SYSERR on failure
1016 */ 1015 */
1017ssize_t 1016ssize_t
1018GNUNET_DISK_fn_read (const char *fn, void *result, size_t len) 1017GNUNET_DISK_fn_read(const char *fn, void *result, size_t len)
1019{ 1018{
1020 struct GNUNET_DISK_FileHandle *fh; 1019 struct GNUNET_DISK_FileHandle *fh;
1021 ssize_t ret; 1020 ssize_t ret;
1022 int eno; 1021 int eno;
1023 1022
1024 fh = GNUNET_DISK_file_open (fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE); 1023 fh = GNUNET_DISK_file_open(fn, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
1025 if (NULL == fh) 1024 if (NULL == fh)
1026 return GNUNET_SYSERR; 1025 return GNUNET_SYSERR;
1027 ret = GNUNET_DISK_file_read (fh, result, len); 1026 ret = GNUNET_DISK_file_read(fh, result, len);
1028 eno = errno; 1027 eno = errno;
1029 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); 1028 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
1030 errno = eno; 1029 errno = eno;
1031 return ret; 1030 return ret;
1032} 1031}
@@ -1041,87 +1040,87 @@ GNUNET_DISK_fn_read (const char *fn, void *result, size_t len)
1041 * @return number of bytes written on success, #GNUNET_SYSERR on error 1040 * @return number of bytes written on success, #GNUNET_SYSERR on error
1042 */ 1041 */
1043ssize_t 1042ssize_t
1044GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle *h, 1043GNUNET_DISK_file_write(const struct GNUNET_DISK_FileHandle *h,
1045 const void *buffer, 1044 const void *buffer,
1046 size_t n) 1045 size_t n)
1047{ 1046{
1048 if (NULL == h) 1047 if (NULL == h)
1049 { 1048 {
1050 errno = EINVAL; 1049 errno = EINVAL;
1051 return GNUNET_SYSERR; 1050 return GNUNET_SYSERR;
1052 } 1051 }
1053 1052
1054#ifdef MINGW 1053#ifdef MINGW
1055 DWORD bytes_written; 1054 DWORD bytes_written;
1056 1055
1057 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE) 1056 if (h->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1058 {
1059 if (! WriteFile (h->h, buffer, n, &bytes_written, NULL))
1060 { 1057 {
1061 SetErrnoFromWinError (GetLastError ()); 1058 if (!WriteFile(h->h, buffer, n, &bytes_written, NULL))
1062 return GNUNET_SYSERR; 1059 {
1060 SetErrnoFromWinError(GetLastError());
1061 return GNUNET_SYSERR;
1062 }
1063 } 1063 }
1064 }
1065 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE) 1064 else if (h->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1066 {
1067 LOG (GNUNET_ERROR_TYPE_DEBUG, "It is a pipe trying to write %u bytes\n", n);
1068 if (! WriteFile (h->h, buffer, n, &bytes_written, h->oOverlapWrite))
1069 {
1070 if (GetLastError () != ERROR_IO_PENDING)
1071 {
1072 SetErrnoFromWinError (GetLastError ());
1073 LOG (GNUNET_ERROR_TYPE_DEBUG,
1074 "Error writing to pipe: %u\n",
1075 GetLastError ());
1076 return GNUNET_SYSERR;
1077 }
1078 LOG (GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
1079 if (! GetOverlappedResult (h->h, h->oOverlapWrite, &bytes_written, TRUE))
1080 {
1081 SetErrnoFromWinError (GetLastError ());
1082 LOG (GNUNET_ERROR_TYPE_DEBUG,
1083 "Error getting overlapped result while writing to pipe: %u\n",
1084 GetLastError ());
1085 return GNUNET_SYSERR;
1086 }
1087 }
1088 else
1089 { 1065 {
1090 DWORD ovr; 1066 LOG(GNUNET_ERROR_TYPE_DEBUG, "It is a pipe trying to write %u bytes\n", n);
1091 if (! GetOverlappedResult (h->h, h->oOverlapWrite, &ovr, TRUE)) 1067 if (!WriteFile(h->h, buffer, n, &bytes_written, h->oOverlapWrite))
1092 { 1068 {
1093 LOG (GNUNET_ERROR_TYPE_DEBUG, 1069 if (GetLastError() != ERROR_IO_PENDING)
1094 "Error getting control overlapped result while writing to pipe: %u\n", 1070 {
1095 GetLastError ()); 1071 SetErrnoFromWinError(GetLastError());
1096 } 1072 LOG(GNUNET_ERROR_TYPE_DEBUG,
1073 "Error writing to pipe: %u\n",
1074 GetLastError());
1075 return GNUNET_SYSERR;
1076 }
1077 LOG(GNUNET_ERROR_TYPE_DEBUG, "Will get overlapped result\n");
1078 if (!GetOverlappedResult(h->h, h->oOverlapWrite, &bytes_written, TRUE))
1079 {
1080 SetErrnoFromWinError(GetLastError());
1081 LOG(GNUNET_ERROR_TYPE_DEBUG,
1082 "Error getting overlapped result while writing to pipe: %u\n",
1083 GetLastError());
1084 return GNUNET_SYSERR;
1085 }
1086 }
1097 else 1087 else
1098 { 1088 {
1099 LOG (GNUNET_ERROR_TYPE_DEBUG, 1089 DWORD ovr;
1100 "Wrote %u bytes (ovr says %u), picking the greatest\n", 1090 if (!GetOverlappedResult(h->h, h->oOverlapWrite, &ovr, TRUE))
1101 bytes_written, 1091 {
1102 ovr); 1092 LOG(GNUNET_ERROR_TYPE_DEBUG,
1103 } 1093 "Error getting control overlapped result while writing to pipe: %u\n",
1094 GetLastError());
1095 }
1096 else
1097 {
1098 LOG(GNUNET_ERROR_TYPE_DEBUG,
1099 "Wrote %u bytes (ovr says %u), picking the greatest\n",
1100 bytes_written,
1101 ovr);
1102 }
1103 }
1104 if (bytes_written == 0)
1105 {
1106 if (n > 0)
1107 {
1108 LOG(GNUNET_ERROR_TYPE_DEBUG,
1109 "Wrote %u bytes, returning -1 with EAGAIN\n",
1110 bytes_written);
1111 errno = EAGAIN;
1112 return GNUNET_SYSERR;
1113 }
1114 }
1115 LOG(GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytes_written);
1104 } 1116 }
1105 if (bytes_written == 0) 1117 else
1106 { 1118 {
1107 if (n > 0) 1119 bytes_written = 0;
1108 {
1109 LOG (GNUNET_ERROR_TYPE_DEBUG,
1110 "Wrote %u bytes, returning -1 with EAGAIN\n",
1111 bytes_written);
1112 errno = EAGAIN;
1113 return GNUNET_SYSERR;
1114 }
1115 } 1120 }
1116 LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytes_written);
1117 }
1118 else
1119 {
1120 bytes_written = 0;
1121 }
1122 return bytes_written; 1121 return bytes_written;
1123#else 1122#else
1124 return write (h->fd, buffer, n); 1123 return write(h->fd, buffer, n);
1125#endif 1124#endif
1126} 1125}
1127 1126
@@ -1135,54 +1134,54 @@ GNUNET_DISK_file_write (const struct GNUNET_DISK_FileHandle *h,
1135 * @return number of bytes written on success, #GNUNET_SYSERR on error 1134 * @return number of bytes written on success, #GNUNET_SYSERR on error
1136 */ 1135 */
1137ssize_t 1136ssize_t
1138GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle *h, 1137GNUNET_DISK_file_write_blocking(const struct GNUNET_DISK_FileHandle *h,
1139 const void *buffer, 1138 const void *buffer,
1140 size_t n) 1139 size_t n)
1141{ 1140{
1142 if (NULL == h) 1141 if (NULL == h)
1143 { 1142 {
1144 errno = EINVAL; 1143 errno = EINVAL;
1145 return GNUNET_SYSERR; 1144 return GNUNET_SYSERR;
1146 } 1145 }
1147 1146
1148#ifdef MINGW 1147#ifdef MINGW
1149 DWORD bytes_written; 1148 DWORD bytes_written;
1150 /* We do a non-overlapped write, which is as blocking as it gets */ 1149 /* We do a non-overlapped write, which is as blocking as it gets */
1151 LOG (GNUNET_ERROR_TYPE_DEBUG, "Writing %u bytes\n", n); 1150 LOG(GNUNET_ERROR_TYPE_DEBUG, "Writing %u bytes\n", n);
1152 if (! WriteFile (h->h, buffer, n, &bytes_written, NULL)) 1151 if (!WriteFile(h->h, buffer, n, &bytes_written, NULL))
1153 { 1152 {
1154 SetErrnoFromWinError (GetLastError ()); 1153 SetErrnoFromWinError(GetLastError());
1155 LOG (GNUNET_ERROR_TYPE_DEBUG, 1154 LOG(GNUNET_ERROR_TYPE_DEBUG,
1156 "Error writing to pipe: %u\n", 1155 "Error writing to pipe: %u\n",
1157 GetLastError ()); 1156 GetLastError());
1158 return GNUNET_SYSERR;
1159 }
1160 if (bytes_written == 0 && n > 0)
1161 {
1162 LOG (GNUNET_ERROR_TYPE_DEBUG, "Waiting for pipe to clean\n");
1163 WaitForSingleObject (h->h, INFINITE);
1164 if (! WriteFile (h->h, buffer, n, &bytes_written, NULL))
1165 {
1166 SetErrnoFromWinError (GetLastError ());
1167 LOG (GNUNET_ERROR_TYPE_DEBUG,
1168 "Error writing to pipe: %u\n",
1169 GetLastError ());
1170 return GNUNET_SYSERR; 1157 return GNUNET_SYSERR;
1171 } 1158 }
1172 } 1159 if (bytes_written == 0 && n > 0)
1173 LOG (GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytes_written); 1160 {
1161 LOG(GNUNET_ERROR_TYPE_DEBUG, "Waiting for pipe to clean\n");
1162 WaitForSingleObject(h->h, INFINITE);
1163 if (!WriteFile(h->h, buffer, n, &bytes_written, NULL))
1164 {
1165 SetErrnoFromWinError(GetLastError());
1166 LOG(GNUNET_ERROR_TYPE_DEBUG,
1167 "Error writing to pipe: %u\n",
1168 GetLastError());
1169 return GNUNET_SYSERR;
1170 }
1171 }
1172 LOG(GNUNET_ERROR_TYPE_DEBUG, "Wrote %u bytes\n", bytes_written);
1174 return bytes_written; 1173 return bytes_written;
1175#else 1174#else
1176 int flags; 1175 int flags;
1177 ssize_t ret; 1176 ssize_t ret;
1178 1177
1179 /* set to blocking, write, then set back */ 1178 /* set to blocking, write, then set back */
1180 flags = fcntl (h->fd, F_GETFL); 1179 flags = fcntl(h->fd, F_GETFL);
1181 if (0 != (flags & O_NONBLOCK)) 1180 if (0 != (flags & O_NONBLOCK))
1182 (void) fcntl (h->fd, F_SETFL, flags - O_NONBLOCK); 1181 (void)fcntl(h->fd, F_SETFL, flags - O_NONBLOCK);
1183 ret = write (h->fd, buffer, n); 1182 ret = write(h->fd, buffer, n);
1184 if (0 == (flags & O_NONBLOCK)) 1183 if (0 == (flags & O_NONBLOCK))
1185 (void) fcntl (h->fd, F_SETFL, flags); 1184 (void)fcntl(h->fd, F_SETFL, flags);
1186 return ret; 1185 return ret;
1187#endif 1186#endif
1188} 1187}
@@ -1199,23 +1198,23 @@ GNUNET_DISK_file_write_blocking (const struct GNUNET_DISK_FileHandle *h,
1199 * @return number of bytes written on success, #GNUNET_SYSERR on error 1198 * @return number of bytes written on success, #GNUNET_SYSERR on error
1200 */ 1199 */
1201ssize_t 1200ssize_t
1202GNUNET_DISK_fn_write (const char *fn, 1201GNUNET_DISK_fn_write(const char *fn,
1203 const void *buffer, 1202 const void *buffer,
1204 size_t n, 1203 size_t n,
1205 enum GNUNET_DISK_AccessPermissions mode) 1204 enum GNUNET_DISK_AccessPermissions mode)
1206{ 1205{
1207 struct GNUNET_DISK_FileHandle *fh; 1206 struct GNUNET_DISK_FileHandle *fh;
1208 ssize_t ret; 1207 ssize_t ret;
1209 1208
1210 fh = 1209 fh =
1211 GNUNET_DISK_file_open (fn, 1210 GNUNET_DISK_file_open(fn,
1212 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE | 1211 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_TRUNCATE |
1213 GNUNET_DISK_OPEN_CREATE, 1212 GNUNET_DISK_OPEN_CREATE,
1214 mode); 1213 mode);
1215 if (! fh) 1214 if (!fh)
1216 return GNUNET_SYSERR; 1215 return GNUNET_SYSERR;
1217 ret = GNUNET_DISK_file_write (fh, buffer, n); 1216 ret = GNUNET_DISK_file_write(fh, buffer, n);
1218 GNUNET_assert (GNUNET_OK == GNUNET_DISK_file_close (fh)); 1217 GNUNET_assert(GNUNET_OK == GNUNET_DISK_file_close(fh));
1219 return ret; 1218 return ret;
1220} 1219}
1221 1220
@@ -1231,9 +1230,9 @@ GNUNET_DISK_fn_write (const char *fn,
1231 * ieration aborted by callback returning #GNUNET_SYSERR 1230 * ieration aborted by callback returning #GNUNET_SYSERR
1232 */ 1231 */
1233int 1232int
1234GNUNET_DISK_directory_scan (const char *dir_name, 1233GNUNET_DISK_directory_scan(const char *dir_name,
1235 GNUNET_FileNameCallback callback, 1234 GNUNET_FileNameCallback callback,
1236 void *callback_cls) 1235 void *callback_cls)
1237{ 1236{
1238 DIR *dinfo; 1237 DIR *dinfo;
1239 struct dirent *finfo; 1238 struct dirent *finfo;
@@ -1245,80 +1244,80 @@ GNUNET_DISK_directory_scan (const char *dir_name,
1245 unsigned int name_len; 1244 unsigned int name_len;
1246 unsigned int n_size; 1245 unsigned int n_size;
1247 1246
1248 GNUNET_assert (NULL != dir_name); 1247 GNUNET_assert(NULL != dir_name);
1249 dname = GNUNET_STRINGS_filename_expand (dir_name); 1248 dname = GNUNET_STRINGS_filename_expand(dir_name);
1250 if (NULL == dname) 1249 if (NULL == dname)
1251 return GNUNET_SYSERR; 1250 return GNUNET_SYSERR;
1252 while ((strlen (dname) > 0) && (dname[strlen (dname) - 1] == DIR_SEPARATOR)) 1251 while ((strlen(dname) > 0) && (dname[strlen(dname) - 1] == DIR_SEPARATOR))
1253 dname[strlen (dname) - 1] = '\0'; 1252 dname[strlen(dname) - 1] = '\0';
1254 if (0 != stat (dname, &istat)) 1253 if (0 != stat(dname, &istat))
1255 { 1254 {
1256 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", dname); 1255 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", dname);
1257 GNUNET_free (dname); 1256 GNUNET_free(dname);
1258 return GNUNET_SYSERR; 1257 return GNUNET_SYSERR;
1259 } 1258 }
1260 if (! S_ISDIR (istat.st_mode)) 1259 if (!S_ISDIR(istat.st_mode))
1261 { 1260 {
1262 LOG (GNUNET_ERROR_TYPE_WARNING, 1261 LOG(GNUNET_ERROR_TYPE_WARNING,
1263 _ ("Expected `%s' to be a directory!\n"), 1262 _("Expected `%s' to be a directory!\n"),
1264 dir_name); 1263 dir_name);
1265 GNUNET_free (dname); 1264 GNUNET_free(dname);
1266 return GNUNET_SYSERR; 1265 return GNUNET_SYSERR;
1267 } 1266 }
1268 errno = 0; 1267 errno = 0;
1269 dinfo = opendir (dname); 1268 dinfo = opendir(dname);
1270 if ((EACCES == errno) || (NULL == dinfo)) 1269 if ((EACCES == errno) || (NULL == dinfo))
1271 { 1270 {
1272 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "opendir", dname); 1271 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "opendir", dname);
1273 if (NULL != dinfo) 1272 if (NULL != dinfo)
1274 closedir (dinfo); 1273 closedir(dinfo);
1275 GNUNET_free (dname); 1274 GNUNET_free(dname);
1276 return GNUNET_SYSERR; 1275 return GNUNET_SYSERR;
1277 } 1276 }
1278 name_len = 256; 1277 name_len = 256;
1279 n_size = strlen (dname) + name_len + strlen (DIR_SEPARATOR_STR) + 1; 1278 n_size = strlen(dname) + name_len + strlen(DIR_SEPARATOR_STR) + 1;
1280 name = GNUNET_malloc (n_size); 1279 name = GNUNET_malloc(n_size);
1281 while (NULL != (finfo = readdir (dinfo))) 1280 while (NULL != (finfo = readdir(dinfo)))
1282 {
1283 if ((0 == strcmp (finfo->d_name, ".")) ||
1284 (0 == strcmp (finfo->d_name, "..")))
1285 continue;
1286 if (NULL != callback)
1287 { 1281 {
1288 if (name_len < strlen (finfo->d_name)) 1282 if ((0 == strcmp(finfo->d_name, ".")) ||
1289 { 1283 (0 == strcmp(finfo->d_name, "..")))
1290 GNUNET_free (name); 1284 continue;
1291 name_len = strlen (finfo->d_name); 1285 if (NULL != callback)
1292 n_size = strlen (dname) + name_len + strlen (DIR_SEPARATOR_STR) + 1; 1286 {
1293 name = GNUNET_malloc (n_size); 1287 if (name_len < strlen(finfo->d_name))
1294 } 1288 {
1295 /* dname can end in "/" only if dname == "/"; 1289 GNUNET_free(name);
1296 * if dname does not end in "/", we need to add 1290 name_len = strlen(finfo->d_name);
1297 * a "/" (otherwise, we must not!) */ 1291 n_size = strlen(dname) + name_len + strlen(DIR_SEPARATOR_STR) + 1;
1298 GNUNET_snprintf (name, 1292 name = GNUNET_malloc(n_size);
1299 n_size, 1293 }
1300 "%s%s%s", 1294 /* dname can end in "/" only if dname == "/";
1301 dname, 1295 * if dname does not end in "/", we need to add
1302 (0 == strcmp (dname, DIR_SEPARATOR_STR)) 1296 * a "/" (otherwise, we must not!) */
1303 ? "" 1297 GNUNET_snprintf(name,
1304 : DIR_SEPARATOR_STR, 1298 n_size,
1305 finfo->d_name); 1299 "%s%s%s",
1306 ret = callback (callback_cls, name); 1300 dname,
1307 if (GNUNET_OK != ret) 1301 (0 == strcmp(dname, DIR_SEPARATOR_STR))
1308 { 1302 ? ""
1309 closedir (dinfo); 1303 : DIR_SEPARATOR_STR,
1310 GNUNET_free (name); 1304 finfo->d_name);
1311 GNUNET_free (dname); 1305 ret = callback(callback_cls, name);
1312 if (GNUNET_NO == ret) 1306 if (GNUNET_OK != ret)
1313 return count; 1307 {
1314 return GNUNET_SYSERR; 1308 closedir(dinfo);
1315 } 1309 GNUNET_free(name);
1310 GNUNET_free(dname);
1311 if (GNUNET_NO == ret)
1312 return count;
1313 return GNUNET_SYSERR;
1314 }
1315 }
1316 count++;
1316 } 1317 }
1317 count++; 1318 closedir(dinfo);
1318 } 1319 GNUNET_free(name);
1319 closedir (dinfo); 1320 GNUNET_free(dname);
1320 GNUNET_free (name);
1321 GNUNET_free (dname);
1322 return count; 1321 return count;
1323} 1322}
1324 1323
@@ -1332,10 +1331,10 @@ GNUNET_DISK_directory_scan (const char *dir_name,
1332 * @return #GNUNET_OK 1331 * @return #GNUNET_OK
1333 */ 1332 */
1334static int 1333static int
1335remove_helper (void *unused, const char *fn) 1334remove_helper(void *unused, const char *fn)
1336{ 1335{
1337 (void) unused; 1336 (void)unused;
1338 (void) GNUNET_DISK_directory_remove (fn); 1337 (void)GNUNET_DISK_directory_remove(fn);
1339 return GNUNET_OK; 1338 return GNUNET_OK;
1340} 1339}
1341 1340
@@ -1348,37 +1347,37 @@ remove_helper (void *unused, const char *fn)
1348 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1347 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1349 */ 1348 */
1350int 1349int
1351GNUNET_DISK_directory_remove (const char *filename) 1350GNUNET_DISK_directory_remove(const char *filename)
1352{ 1351{
1353 struct stat istat; 1352 struct stat istat;
1354 1353
1355 if (NULL == filename) 1354 if (NULL == filename)
1356 { 1355 {
1357 GNUNET_break (0); 1356 GNUNET_break(0);
1358 return GNUNET_SYSERR; 1357 return GNUNET_SYSERR;
1359 } 1358 }
1360 if (0 != lstat (filename, &istat)) 1359 if (0 != lstat(filename, &istat))
1361 return GNUNET_NO; /* file may not exist... */ 1360 return GNUNET_NO; /* file may not exist... */
1362 (void) chmod (filename, S_IWUSR | S_IRUSR | S_IXUSR); 1361 (void)chmod(filename, S_IWUSR | S_IRUSR | S_IXUSR);
1363 if (0 == unlink (filename)) 1362 if (0 == unlink(filename))
1364 return GNUNET_OK; 1363 return GNUNET_OK;
1365 if ((errno != EISDIR) && 1364 if ((errno != EISDIR) &&
1366 /* EISDIR is not sufficient in all cases, e.g. 1365 /* EISDIR is not sufficient in all cases, e.g.
1367 * sticky /tmp directory may result in EPERM on BSD. 1366 * sticky /tmp directory may result in EPERM on BSD.
1368 * So we also explicitly check "isDirectory" */ 1367 * So we also explicitly check "isDirectory" */
1369 (GNUNET_YES != GNUNET_DISK_directory_test (filename, GNUNET_YES))) 1368 (GNUNET_YES != GNUNET_DISK_directory_test(filename, GNUNET_YES)))
1370 { 1369 {
1371 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename); 1370 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1372 return GNUNET_SYSERR; 1371 return GNUNET_SYSERR;
1373 } 1372 }
1374 if (GNUNET_SYSERR == 1373 if (GNUNET_SYSERR ==
1375 GNUNET_DISK_directory_scan (filename, &remove_helper, NULL)) 1374 GNUNET_DISK_directory_scan(filename, &remove_helper, NULL))
1376 return GNUNET_SYSERR; 1375 return GNUNET_SYSERR;
1377 if (0 != rmdir (filename)) 1376 if (0 != rmdir(filename))
1378 { 1377 {
1379 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "rmdir", filename); 1378 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "rmdir", filename);
1380 return GNUNET_SYSERR; 1379 return GNUNET_SYSERR;
1381 } 1380 }
1382 return GNUNET_OK; 1381 return GNUNET_OK;
1383} 1382}
1384 1383
@@ -1391,7 +1390,7 @@ GNUNET_DISK_directory_remove (const char *filename)
1391 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1390 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1392 */ 1391 */
1393int 1392int
1394GNUNET_DISK_file_copy (const char *src, const char *dst) 1393GNUNET_DISK_file_copy(const char *src, const char *dst)
1395{ 1394{
1396 char *buf; 1395 char *buf;
1397 uint64_t pos; 1396 uint64_t pos;
@@ -1401,55 +1400,55 @@ GNUNET_DISK_file_copy (const char *src, const char *dst)
1401 struct GNUNET_DISK_FileHandle *in; 1400 struct GNUNET_DISK_FileHandle *in;
1402 struct GNUNET_DISK_FileHandle *out; 1401 struct GNUNET_DISK_FileHandle *out;
1403 1402
1404 if (GNUNET_OK != GNUNET_DISK_file_size (src, &size, GNUNET_YES, GNUNET_YES)) 1403 if (GNUNET_OK != GNUNET_DISK_file_size(src, &size, GNUNET_YES, GNUNET_YES))
1405 { 1404 {
1406 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "stat", src); 1405 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "stat", src);
1407 return GNUNET_SYSERR; 1406 return GNUNET_SYSERR;
1408 } 1407 }
1409 pos = 0; 1408 pos = 0;
1410 in = 1409 in =
1411 GNUNET_DISK_file_open (src, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE); 1410 GNUNET_DISK_file_open(src, GNUNET_DISK_OPEN_READ, GNUNET_DISK_PERM_NONE);
1412 if (! in) 1411 if (!in)
1413 { 1412 {
1414 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", src); 1413 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", src);
1415 return GNUNET_SYSERR; 1414 return GNUNET_SYSERR;
1416 } 1415 }
1417 out = 1416 out =
1418 GNUNET_DISK_file_open (dst, 1417 GNUNET_DISK_file_open(dst,
1419 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE | 1418 GNUNET_DISK_OPEN_WRITE | GNUNET_DISK_OPEN_CREATE |
1420 GNUNET_DISK_OPEN_FAILIFEXISTS, 1419 GNUNET_DISK_OPEN_FAILIFEXISTS,
1421 GNUNET_DISK_PERM_USER_READ | 1420 GNUNET_DISK_PERM_USER_READ |
1422 GNUNET_DISK_PERM_USER_WRITE | 1421 GNUNET_DISK_PERM_USER_WRITE |
1423 GNUNET_DISK_PERM_GROUP_READ | 1422 GNUNET_DISK_PERM_GROUP_READ |
1424 GNUNET_DISK_PERM_GROUP_WRITE); 1423 GNUNET_DISK_PERM_GROUP_WRITE);
1425 if (! out) 1424 if (!out)
1426 { 1425 {
1427 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", dst); 1426 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", dst);
1428 GNUNET_DISK_file_close (in); 1427 GNUNET_DISK_file_close(in);
1429 return GNUNET_SYSERR; 1428 return GNUNET_SYSERR;
1430 } 1429 }
1431 buf = GNUNET_malloc (COPY_BLK_SIZE); 1430 buf = GNUNET_malloc(COPY_BLK_SIZE);
1432 while (pos < size) 1431 while (pos < size)
1433 { 1432 {
1434 len = COPY_BLK_SIZE; 1433 len = COPY_BLK_SIZE;
1435 if (len > size - pos) 1434 if (len > size - pos)
1436 len = size - pos; 1435 len = size - pos;
1437 sret = GNUNET_DISK_file_read (in, buf, len); 1436 sret = GNUNET_DISK_file_read(in, buf, len);
1438 if ((sret < 0) || (len != (size_t) sret)) 1437 if ((sret < 0) || (len != (size_t)sret))
1439 goto FAIL; 1438 goto FAIL;
1440 sret = GNUNET_DISK_file_write (out, buf, len); 1439 sret = GNUNET_DISK_file_write(out, buf, len);
1441 if ((sret < 0) || (len != (size_t) sret)) 1440 if ((sret < 0) || (len != (size_t)sret))
1442 goto FAIL; 1441 goto FAIL;
1443 pos += len; 1442 pos += len;
1444 } 1443 }
1445 GNUNET_free (buf); 1444 GNUNET_free(buf);
1446 GNUNET_DISK_file_close (in); 1445 GNUNET_DISK_file_close(in);
1447 GNUNET_DISK_file_close (out); 1446 GNUNET_DISK_file_close(out);
1448 return GNUNET_OK; 1447 return GNUNET_OK;
1449FAIL: 1448FAIL:
1450 GNUNET_free (buf); 1449 GNUNET_free(buf);
1451 GNUNET_DISK_file_close (in); 1450 GNUNET_DISK_file_close(in);
1452 GNUNET_DISK_file_close (out); 1451 GNUNET_DISK_file_close(out);
1453 return GNUNET_SYSERR; 1452 return GNUNET_SYSERR;
1454} 1453}
1455 1454
@@ -1459,21 +1458,21 @@ FAIL:
1459 * @param fn the filename to canonicalize 1458 * @param fn the filename to canonicalize
1460 */ 1459 */
1461void 1460void
1462GNUNET_DISK_filename_canonicalize (char *fn) 1461GNUNET_DISK_filename_canonicalize(char *fn)
1463{ 1462{
1464 char *idx; 1463 char *idx;
1465 char c; 1464 char c;
1466 1465
1467 for (idx = fn; *idx; idx++) 1466 for (idx = fn; *idx; idx++)
1468 {
1469 c = *idx;
1470
1471 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' ||
1472 c == '<' || c == '>' || c == '|')
1473 { 1467 {
1474 *idx = '_'; 1468 c = *idx;
1469
1470 if (c == '/' || c == '\\' || c == ':' || c == '*' || c == '?' || c == '"' ||
1471 c == '<' || c == '>' || c == '|')
1472 {
1473 *idx = '_';
1474 }
1475 } 1475 }
1476 }
1477} 1476}
1478 1477
1479 1478
@@ -1485,25 +1484,25 @@ GNUNET_DISK_filename_canonicalize (char *fn)
1485 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 1484 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1486 */ 1485 */
1487int 1486int
1488GNUNET_DISK_file_change_owner (const char *filename, const char *user) 1487GNUNET_DISK_file_change_owner(const char *filename, const char *user)
1489{ 1488{
1490#ifndef MINGW 1489#ifndef MINGW
1491 struct passwd *pws; 1490 struct passwd *pws;
1492 1491
1493 pws = getpwnam (user); 1492 pws = getpwnam(user);
1494 if (NULL == pws) 1493 if (NULL == pws)
1495 { 1494 {
1496 LOG (GNUNET_ERROR_TYPE_ERROR, 1495 LOG(GNUNET_ERROR_TYPE_ERROR,
1497 _ ("Cannot obtain information about user `%s': %s\n"), 1496 _("Cannot obtain information about user `%s': %s\n"),
1498 user, 1497 user,
1499 strerror (errno)); 1498 strerror(errno));
1500 return GNUNET_SYSERR; 1499 return GNUNET_SYSERR;
1501 } 1500 }
1502 if (0 != chown (filename, pws->pw_uid, pws->pw_gid)) 1501 if (0 != chown(filename, pws->pw_uid, pws->pw_gid))
1503 { 1502 {
1504 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "chown", filename); 1503 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "chown", filename);
1505 return GNUNET_SYSERR; 1504 return GNUNET_SYSERR;
1506 } 1505 }
1507#endif 1506#endif
1508 return GNUNET_OK; 1507 return GNUNET_OK;
1509} 1508}
@@ -1519,51 +1518,51 @@ GNUNET_DISK_file_change_owner (const char *filename, const char *user)
1519 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1518 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1520 */ 1519 */
1521int 1520int
1522GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh, 1521GNUNET_DISK_file_lock(struct GNUNET_DISK_FileHandle *fh,
1523 off_t lock_start, 1522 off_t lock_start,
1524 off_t lock_end, 1523 off_t lock_end,
1525 int excl) 1524 int excl)
1526{ 1525{
1527 if (fh == NULL) 1526 if (fh == NULL)
1528 { 1527 {
1529 errno = EINVAL; 1528 errno = EINVAL;
1530 return GNUNET_SYSERR; 1529 return GNUNET_SYSERR;
1531 } 1530 }
1532 1531
1533#ifndef MINGW 1532#ifndef MINGW
1534 struct flock fl; 1533 struct flock fl;
1535 1534
1536 memset (&fl, 0, sizeof (struct flock)); 1535 memset(&fl, 0, sizeof(struct flock));
1537 fl.l_type = excl ? F_WRLCK : F_RDLCK; 1536 fl.l_type = excl ? F_WRLCK : F_RDLCK;
1538 fl.l_whence = SEEK_SET; 1537 fl.l_whence = SEEK_SET;
1539 fl.l_start = lock_start; 1538 fl.l_start = lock_start;
1540 fl.l_len = lock_end; 1539 fl.l_len = lock_end;
1541 1540
1542 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK; 1541 return fcntl(fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1543#else 1542#else
1544 OVERLAPPED o; 1543 OVERLAPPED o;
1545 off_t diff = lock_end - lock_start; 1544 off_t diff = lock_end - lock_start;
1546 DWORD diff_low, diff_high; 1545 DWORD diff_low, diff_high;
1547 diff_low = (DWORD) (diff & 0xFFFFFFFF); 1546 diff_low = (DWORD)(diff & 0xFFFFFFFF);
1548 diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF); 1547 diff_high = (DWORD)((diff >> (sizeof(DWORD) * 8)) & 0xFFFFFFFF);
1549 1548
1550 memset (&o, 0, sizeof (OVERLAPPED)); 1549 memset(&o, 0, sizeof(OVERLAPPED));
1551 o.Offset = (DWORD) (lock_start & 0xFFFFFFFF); 1550 o.Offset = (DWORD)(lock_start & 0xFFFFFFFF);
1552 ; 1551 ;
1553 o.OffsetHigh = 1552 o.OffsetHigh =
1554 (DWORD) (((lock_start & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF); 1553 (DWORD)(((lock_start & ~0xFFFFFFFF) >> (sizeof(DWORD) * 8)) & 0xFFFFFFFF);
1555 1554
1556 if (! LockFileEx (fh->h, 1555 if (!LockFileEx(fh->h,
1557 (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0) | 1556 (excl ? LOCKFILE_EXCLUSIVE_LOCK : 0) |
1558 LOCKFILE_FAIL_IMMEDIATELY, 1557 LOCKFILE_FAIL_IMMEDIATELY,
1559 0, 1558 0,
1560 diff_low, 1559 diff_low,
1561 diff_high, 1560 diff_high,
1562 &o)) 1561 &o))
1563 { 1562 {
1564 SetErrnoFromWinError (GetLastError ()); 1563 SetErrnoFromWinError(GetLastError());
1565 return GNUNET_SYSERR; 1564 return GNUNET_SYSERR;
1566 } 1565 }
1567 1566
1568 return GNUNET_OK; 1567 return GNUNET_OK;
1569#endif 1568#endif
@@ -1579,44 +1578,44 @@ GNUNET_DISK_file_lock (struct GNUNET_DISK_FileHandle *fh,
1579 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1578 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1580 */ 1579 */
1581int 1580int
1582GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh, 1581GNUNET_DISK_file_unlock(struct GNUNET_DISK_FileHandle *fh,
1583 off_t unlock_start, 1582 off_t unlock_start,
1584 off_t unlock_end) 1583 off_t unlock_end)
1585{ 1584{
1586 if (fh == NULL) 1585 if (fh == NULL)
1587 { 1586 {
1588 errno = EINVAL; 1587 errno = EINVAL;
1589 return GNUNET_SYSERR; 1588 return GNUNET_SYSERR;
1590 } 1589 }
1591 1590
1592#ifndef MINGW 1591#ifndef MINGW
1593 struct flock fl; 1592 struct flock fl;
1594 1593
1595 memset (&fl, 0, sizeof (struct flock)); 1594 memset(&fl, 0, sizeof(struct flock));
1596 fl.l_type = F_UNLCK; 1595 fl.l_type = F_UNLCK;
1597 fl.l_whence = SEEK_SET; 1596 fl.l_whence = SEEK_SET;
1598 fl.l_start = unlock_start; 1597 fl.l_start = unlock_start;
1599 fl.l_len = unlock_end; 1598 fl.l_len = unlock_end;
1600 1599
1601 return fcntl (fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK; 1600 return fcntl(fh->fd, F_SETLK, &fl) != 0 ? GNUNET_SYSERR : GNUNET_OK;
1602#else 1601#else
1603 OVERLAPPED o; 1602 OVERLAPPED o;
1604 off_t diff = unlock_end - unlock_start; 1603 off_t diff = unlock_end - unlock_start;
1605 DWORD diff_low, diff_high; 1604 DWORD diff_low, diff_high;
1606 diff_low = (DWORD) (diff & 0xFFFFFFFF); 1605 diff_low = (DWORD)(diff & 0xFFFFFFFF);
1607 diff_high = (DWORD) ((diff >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF); 1606 diff_high = (DWORD)((diff >> (sizeof(DWORD) * 8)) & 0xFFFFFFFF);
1608 1607
1609 memset (&o, 0, sizeof (OVERLAPPED)); 1608 memset(&o, 0, sizeof(OVERLAPPED));
1610 o.Offset = (DWORD) (unlock_start & 0xFFFFFFFF); 1609 o.Offset = (DWORD)(unlock_start & 0xFFFFFFFF);
1611 ; 1610 ;
1612 o.OffsetHigh = (DWORD) ( 1611 o.OffsetHigh = (DWORD)(
1613 ((unlock_start & ~0xFFFFFFFF) >> (sizeof (DWORD) * 8)) & 0xFFFFFFFF); 1612 ((unlock_start & ~0xFFFFFFFF) >> (sizeof(DWORD) * 8)) & 0xFFFFFFFF);
1614 1613
1615 if (! UnlockFileEx (fh->h, 0, diff_low, diff_high, &o)) 1614 if (!UnlockFileEx(fh->h, 0, diff_low, diff_high, &o))
1616 { 1615 {
1617 SetErrnoFromWinError (GetLastError ()); 1616 SetErrnoFromWinError(GetLastError());
1618 return GNUNET_SYSERR; 1617 return GNUNET_SYSERR;
1619 } 1618 }
1620 1619
1621 return GNUNET_OK; 1620 return GNUNET_OK;
1622#endif 1621#endif
@@ -1636,9 +1635,9 @@ GNUNET_DISK_file_unlock (struct GNUNET_DISK_FileHandle *fh,
1636 * @return IO handle on success, NULL on error 1635 * @return IO handle on success, NULL on error
1637 */ 1636 */
1638struct GNUNET_DISK_FileHandle * 1637struct GNUNET_DISK_FileHandle *
1639GNUNET_DISK_file_open (const char *fn, 1638GNUNET_DISK_file_open(const char *fn,
1640 enum GNUNET_DISK_OpenFlags flags, 1639 enum GNUNET_DISK_OpenFlags flags,
1641 enum GNUNET_DISK_AccessPermissions perm) 1640 enum GNUNET_DISK_AccessPermissions perm)
1642{ 1641{
1643 char *expfn; 1642 char *expfn;
1644 struct GNUNET_DISK_FileHandle *ret; 1643 struct GNUNET_DISK_FileHandle *ret;
@@ -1654,7 +1653,7 @@ GNUNET_DISK_file_open (const char *fn,
1654 int fd; 1653 int fd;
1655#endif 1654#endif
1656 1655
1657 expfn = GNUNET_STRINGS_filename_expand (fn); 1656 expfn = GNUNET_STRINGS_filename_expand(fn);
1658 if (NULL == expfn) 1657 if (NULL == expfn)
1659 return NULL; 1658 return NULL;
1660#ifndef MINGW 1659#ifndef MINGW
@@ -1666,43 +1665,43 @@ GNUNET_DISK_file_open (const char *fn,
1666 else if (flags & GNUNET_DISK_OPEN_WRITE) 1665 else if (flags & GNUNET_DISK_OPEN_WRITE)
1667 oflags = O_WRONLY; 1666 oflags = O_WRONLY;
1668 else 1667 else
1669 { 1668 {
1670 GNUNET_break (0); 1669 GNUNET_break(0);
1671 GNUNET_free (expfn); 1670 GNUNET_free(expfn);
1672 return NULL; 1671 return NULL;
1673 } 1672 }
1674 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS) 1673 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1675 oflags |= (O_CREAT | O_EXCL); 1674 oflags |= (O_CREAT | O_EXCL);
1676 if (flags & GNUNET_DISK_OPEN_TRUNCATE) 1675 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1677 oflags |= O_TRUNC; 1676 oflags |= O_TRUNC;
1678 if (flags & GNUNET_DISK_OPEN_APPEND) 1677 if (flags & GNUNET_DISK_OPEN_APPEND)
1679 oflags |= O_APPEND; 1678 oflags |= O_APPEND;
1680 if (GNUNET_NO == GNUNET_DISK_file_test (fn)) 1679 if (GNUNET_NO == GNUNET_DISK_file_test(fn))
1681 {
1682 if (flags & GNUNET_DISK_OPEN_CREATE)
1683 { 1680 {
1684 (void) GNUNET_DISK_directory_create_for_file (expfn); 1681 if (flags & GNUNET_DISK_OPEN_CREATE)
1685 oflags |= O_CREAT; 1682 {
1686 mode = translate_unix_perms (perm); 1683 (void)GNUNET_DISK_directory_create_for_file(expfn);
1684 oflags |= O_CREAT;
1685 mode = translate_unix_perms(perm);
1686 }
1687 } 1687 }
1688 }
1689 1688
1690 fd = open (expfn, 1689 fd = open(expfn,
1691 oflags 1690 oflags
1692#if O_CLOEXEC 1691#if O_CLOEXEC
1693 | O_CLOEXEC 1692 | O_CLOEXEC
1694#endif 1693#endif
1695 | O_LARGEFILE, 1694 | O_LARGEFILE,
1696 mode); 1695 mode);
1697 if (fd == -1) 1696 if (fd == -1)
1698 { 1697 {
1699 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)) 1698 if (0 == (flags & GNUNET_DISK_OPEN_FAILIFEXISTS))
1700 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", expfn); 1699 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "open", expfn);
1701 else 1700 else
1702 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_DEBUG, "open", expfn); 1701 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_DEBUG, "open", expfn);
1703 GNUNET_free (expfn); 1702 GNUNET_free(expfn);
1704 return NULL; 1703 return NULL;
1705 } 1704 }
1706#else 1705#else
1707 access = 0; 1706 access = 0;
1708 disp = OPEN_ALWAYS; 1707 disp = OPEN_ALWAYS;
@@ -1715,66 +1714,66 @@ GNUNET_DISK_file_open (const char *fn,
1715 access = FILE_WRITE_DATA; 1714 access = FILE_WRITE_DATA;
1716 1715
1717 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS) 1716 if (flags & GNUNET_DISK_OPEN_FAILIFEXISTS)
1718 { 1717 {
1719 disp = CREATE_NEW; 1718 disp = CREATE_NEW;
1720 } 1719 }
1721 else if (flags & GNUNET_DISK_OPEN_CREATE) 1720 else if (flags & GNUNET_DISK_OPEN_CREATE)
1722 { 1721 {
1723 (void) GNUNET_DISK_directory_create_for_file (expfn); 1722 (void)GNUNET_DISK_directory_create_for_file(expfn);
1724 if (flags & GNUNET_DISK_OPEN_TRUNCATE) 1723 if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1725 disp = CREATE_ALWAYS; 1724 disp = CREATE_ALWAYS;
1726 else 1725 else
1727 disp = OPEN_ALWAYS; 1726 disp = OPEN_ALWAYS;
1728 } 1727 }
1729 else if (flags & GNUNET_DISK_OPEN_TRUNCATE) 1728 else if (flags & GNUNET_DISK_OPEN_TRUNCATE)
1730 { 1729 {
1731 disp = TRUNCATE_EXISTING; 1730 disp = TRUNCATE_EXISTING;
1732 } 1731 }
1733 else 1732 else
1734 { 1733 {
1735 disp = OPEN_EXISTING; 1734 disp = OPEN_EXISTING;
1736 } 1735 }
1737 1736
1738 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv (expfn, wexpfn)) 1737 if (ERROR_SUCCESS == plibc_conv_to_win_pathwconv(expfn, wexpfn))
1739 h = CreateFileW (wexpfn, 1738 h = CreateFileW(wexpfn,
1740 access, 1739 access,
1741 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 1740 FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE,
1742 NULL, 1741 NULL,
1743 disp, 1742 disp,
1744 FILE_ATTRIBUTE_NORMAL, 1743 FILE_ATTRIBUTE_NORMAL,
1745 NULL); 1744 NULL);
1746 else 1745 else
1747 h = INVALID_HANDLE_VALUE; 1746 h = INVALID_HANDLE_VALUE;
1748 if (h == INVALID_HANDLE_VALUE) 1747 if (h == INVALID_HANDLE_VALUE)
1749 {
1750 int err;
1751 SetErrnoFromWinError (GetLastError ());
1752 err = errno;
1753 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_INFO, "open", expfn);
1754 GNUNET_free (expfn);
1755 errno = err;
1756 return NULL;
1757 }
1758
1759 if (flags & GNUNET_DISK_OPEN_APPEND)
1760 if (SetFilePointer (h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1761 { 1748 {
1762 SetErrnoFromWinError (GetLastError ()); 1749 int err;
1763 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn); 1750 SetErrnoFromWinError(GetLastError());
1764 CloseHandle (h); 1751 err = errno;
1765 GNUNET_free (expfn); 1752 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_INFO, "open", expfn);
1753 GNUNET_free(expfn);
1754 errno = err;
1766 return NULL; 1755 return NULL;
1767 } 1756 }
1757
1758 if (flags & GNUNET_DISK_OPEN_APPEND)
1759 if (SetFilePointer(h, 0, 0, FILE_END) == INVALID_SET_FILE_POINTER)
1760 {
1761 SetErrnoFromWinError(GetLastError());
1762 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "SetFilePointer", expfn);
1763 CloseHandle(h);
1764 GNUNET_free(expfn);
1765 return NULL;
1766 }
1768#endif 1767#endif
1769 1768
1770 ret = GNUNET_new (struct GNUNET_DISK_FileHandle); 1769 ret = GNUNET_new(struct GNUNET_DISK_FileHandle);
1771#ifdef MINGW 1770#ifdef MINGW
1772 ret->h = h; 1771 ret->h = h;
1773 ret->type = GNUNET_DISK_HANLDE_TYPE_FILE; 1772 ret->type = GNUNET_DISK_HANLDE_TYPE_FILE;
1774#else 1773#else
1775 ret->fd = fd; 1774 ret->fd = fd;
1776#endif 1775#endif
1777 GNUNET_free (expfn); 1776 GNUNET_free(expfn);
1778 return ret; 1777 return ret;
1779} 1778}
1780 1779
@@ -1786,52 +1785,53 @@ GNUNET_DISK_file_open (const char *fn,
1786 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 1785 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1787 */ 1786 */
1788int 1787int
1789GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h) 1788GNUNET_DISK_file_close(struct GNUNET_DISK_FileHandle *h)
1790{ 1789{
1791 int ret; 1790 int ret;
1791
1792 if (h == NULL) 1792 if (h == NULL)
1793 { 1793 {
1794 errno = EINVAL; 1794 errno = EINVAL;
1795 return GNUNET_SYSERR; 1795 return GNUNET_SYSERR;
1796 } 1796 }
1797 1797
1798 ret = GNUNET_OK; 1798 ret = GNUNET_OK;
1799 1799
1800#if MINGW 1800#if MINGW
1801 if (! CloseHandle (h->h)) 1801 if (!CloseHandle(h->h))
1802 {
1803 SetErrnoFromWinError (GetLastError ());
1804 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close");
1805 ret = GNUNET_SYSERR;
1806 }
1807 if (h->oOverlapRead)
1808 {
1809 if (! CloseHandle (h->oOverlapRead->hEvent))
1810 { 1802 {
1811 SetErrnoFromWinError (GetLastError ()); 1803 SetErrnoFromWinError(GetLastError());
1812 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close"); 1804 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "close");
1813 ret = GNUNET_SYSERR; 1805 ret = GNUNET_SYSERR;
1814 } 1806 }
1815 GNUNET_free (h->oOverlapRead); 1807 if (h->oOverlapRead)
1816 } 1808 {
1809 if (!CloseHandle(h->oOverlapRead->hEvent))
1810 {
1811 SetErrnoFromWinError(GetLastError());
1812 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "close");
1813 ret = GNUNET_SYSERR;
1814 }
1815 GNUNET_free(h->oOverlapRead);
1816 }
1817 if (h->oOverlapWrite) 1817 if (h->oOverlapWrite)
1818 {
1819 if (! CloseHandle (h->oOverlapWrite->hEvent))
1820 { 1818 {
1821 SetErrnoFromWinError (GetLastError ()); 1819 if (!CloseHandle(h->oOverlapWrite->hEvent))
1822 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close"); 1820 {
1823 ret = GNUNET_SYSERR; 1821 SetErrnoFromWinError(GetLastError());
1822 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "close");
1823 ret = GNUNET_SYSERR;
1824 }
1825 GNUNET_free(h->oOverlapWrite);
1824 } 1826 }
1825 GNUNET_free (h->oOverlapWrite);
1826 }
1827#else 1827#else
1828 if (close (h->fd) != 0) 1828 if (close(h->fd) != 0)
1829 { 1829 {
1830 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "close"); 1830 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "close");
1831 ret = GNUNET_SYSERR; 1831 ret = GNUNET_SYSERR;
1832 } 1832 }
1833#endif 1833#endif
1834 GNUNET_free (h); 1834 GNUNET_free(h);
1835 return ret; 1835 return ret;
1836} 1836}
1837 1837
@@ -1844,56 +1844,59 @@ GNUNET_DISK_file_close (struct GNUNET_DISK_FileHandle *h)
1844 * @return GNUnet file handle corresponding to the W32 handle 1844 * @return GNUnet file handle corresponding to the W32 handle
1845 */ 1845 */
1846struct GNUNET_DISK_FileHandle * 1846struct GNUNET_DISK_FileHandle *
1847GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh) 1847GNUNET_DISK_get_handle_from_w32_handle(HANDLE osfh)
1848{ 1848{
1849 struct GNUNET_DISK_FileHandle *fh; 1849 struct GNUNET_DISK_FileHandle *fh;
1850 DWORD dwret; 1850 DWORD dwret;
1851 enum GNUNET_FILE_Type ftype; 1851 enum GNUNET_FILE_Type ftype;
1852 1852
1853 dwret = GetFileType (osfh); 1853 dwret = GetFileType(osfh);
1854 switch (dwret) 1854 switch (dwret)
1855 { 1855 {
1856 case FILE_TYPE_DISK: 1856 case FILE_TYPE_DISK:
1857 ftype = GNUNET_DISK_HANLDE_TYPE_FILE; 1857 ftype = GNUNET_DISK_HANLDE_TYPE_FILE;
1858 break; 1858 break;
1859 case FILE_TYPE_PIPE: 1859
1860 ftype = GNUNET_DISK_HANLDE_TYPE_PIPE; 1860 case FILE_TYPE_PIPE:
1861 break; 1861 ftype = GNUNET_DISK_HANLDE_TYPE_PIPE;
1862 case FILE_TYPE_UNKNOWN: 1862 break;
1863 if ((GetLastError () == NO_ERROR) || 1863
1864 (GetLastError () == ERROR_INVALID_HANDLE)) 1864 case FILE_TYPE_UNKNOWN:
1865 { 1865 if ((GetLastError() == NO_ERROR) ||
1866 if (0 != ResetEvent (osfh)) 1866 (GetLastError() == ERROR_INVALID_HANDLE))
1867 ftype = GNUNET_DISK_HANLDE_TYPE_EVENT; 1867 {
1868 if (0 != ResetEvent(osfh))
1869 ftype = GNUNET_DISK_HANLDE_TYPE_EVENT;
1870 else
1871 return NULL;
1872 }
1868 else 1873 else
1869 return NULL; 1874 return NULL;
1870 } 1875 break;
1871 else 1876
1877 default:
1872 return NULL; 1878 return NULL;
1873 break; 1879 }
1874 default:
1875 return NULL;
1876 }
1877 1880
1878 fh = GNUNET_new (struct GNUNET_DISK_FileHandle); 1881 fh = GNUNET_new(struct GNUNET_DISK_FileHandle);
1879 1882
1880 fh->h = osfh; 1883 fh->h = osfh;
1881 fh->type = ftype; 1884 fh->type = ftype;
1882 if (ftype == GNUNET_DISK_HANLDE_TYPE_PIPE) 1885 if (ftype == GNUNET_DISK_HANLDE_TYPE_PIPE)
1883 { 1886 {
1884 /** 1887 /**
1885 * Note that we can't make it overlapped if it isn't already. 1888 * Note that we can't make it overlapped if it isn't already.
1886 * (ReOpenFile() is only available in 2003/Vista). 1889 * (ReOpenFile() is only available in 2003/Vista).
1887 * The process that opened this file in the first place (usually a parent 1890 * The process that opened this file in the first place (usually a parent
1888 * process, if this is stdin/stdout/stderr) must make it overlapped, 1891 * process, if this is stdin/stdout/stderr) must make it overlapped,
1889 * otherwise we're screwed, as selecting on non-overlapped handle 1892 * otherwise we're screwed, as selecting on non-overlapped handle
1890 * will block. 1893 * will block.
1891 */ 1894 */
1892 fh->oOverlapRead = GNUNET_new (OVERLAPPED); 1895 fh->oOverlapRead = GNUNET_new(OVERLAPPED);
1893 fh->oOverlapWrite = GNUNET_new (OVERLAPPED); 1896 fh->oOverlapWrite = GNUNET_new(OVERLAPPED);
1894 fh->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 1897 fh->oOverlapRead->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1895 fh->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 1898 fh->oOverlapWrite->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
1896 } 1899 }
1897 1900
1898 return fh; 1901 return fh;
1899} 1902}
@@ -1906,25 +1909,25 @@ GNUNET_DISK_get_handle_from_w32_handle (HANDLE osfh)
1906 * @return file handle corresponding to the descriptor, NULL on error 1909 * @return file handle corresponding to the descriptor, NULL on error
1907 */ 1910 */
1908struct GNUNET_DISK_FileHandle * 1911struct GNUNET_DISK_FileHandle *
1909GNUNET_DISK_get_handle_from_int_fd (int fno) 1912GNUNET_DISK_get_handle_from_int_fd(int fno)
1910{ 1913{
1911 struct GNUNET_DISK_FileHandle *fh; 1914 struct GNUNET_DISK_FileHandle *fh;
1912 1915
1913 if ((((off_t) -1) == lseek (fno, 0, SEEK_CUR)) && (EBADF == errno)) 1916 if ((((off_t)-1) == lseek(fno, 0, SEEK_CUR)) && (EBADF == errno))
1914 return NULL; /* invalid FD */ 1917 return NULL; /* invalid FD */
1915 1918
1916#ifndef WINDOWS 1919#ifndef WINDOWS
1917 fh = GNUNET_new (struct GNUNET_DISK_FileHandle); 1920 fh = GNUNET_new(struct GNUNET_DISK_FileHandle);
1918 1921
1919 fh->fd = fno; 1922 fh->fd = fno;
1920#else 1923#else
1921 intptr_t osfh; 1924 intptr_t osfh;
1922 1925
1923 osfh = _get_osfhandle (fno); 1926 osfh = _get_osfhandle(fno);
1924 if (INVALID_HANDLE_VALUE == (HANDLE) osfh) 1927 if (INVALID_HANDLE_VALUE == (HANDLE)osfh)
1925 return NULL; 1928 return NULL;
1926 1929
1927 fh = GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) osfh); 1930 fh = GNUNET_DISK_get_handle_from_w32_handle((HANDLE)osfh);
1928#endif 1931#endif
1929 1932
1930 return fh; 1933 return fh;
@@ -1938,23 +1941,22 @@ GNUNET_DISK_get_handle_from_int_fd (int fno)
1938 * @return file handle corresponding to the descriptor 1941 * @return file handle corresponding to the descriptor
1939 */ 1942 */
1940struct GNUNET_DISK_FileHandle * 1943struct GNUNET_DISK_FileHandle *
1941GNUNET_DISK_get_handle_from_native (FILE *fd) 1944GNUNET_DISK_get_handle_from_native(FILE *fd)
1942{ 1945{
1943 int fno; 1946 int fno;
1944 1947
1945 fno = fileno (fd); 1948 fno = fileno(fd);
1946 if (-1 == fno) 1949 if (-1 == fno)
1947 return NULL; 1950 return NULL;
1948 1951
1949 return GNUNET_DISK_get_handle_from_int_fd (fno); 1952 return GNUNET_DISK_get_handle_from_int_fd(fno);
1950} 1953}
1951 1954
1952 1955
1953/** 1956/**
1954 * Handle for a memory-mapping operation. 1957 * Handle for a memory-mapping operation.
1955 */ 1958 */
1956struct GNUNET_DISK_MapHandle 1959struct GNUNET_DISK_MapHandle {
1957{
1958 /** 1960 /**
1959 * Address where the map is in memory. 1961 * Address where the map is in memory.
1960 */ 1962 */
@@ -1975,7 +1977,7 @@ struct GNUNET_DISK_MapHandle
1975 1977
1976 1978
1977#ifndef MAP_FAILED 1979#ifndef MAP_FAILED
1978#define MAP_FAILED ((void *) -1) 1980#define MAP_FAILED ((void *)-1)
1979#endif 1981#endif
1980 1982
1981/** 1983/**
@@ -1988,58 +1990,58 @@ struct GNUNET_DISK_MapHandle
1988 * @return pointer to the mapped memory region, NULL on failure 1990 * @return pointer to the mapped memory region, NULL on failure
1989 */ 1991 */
1990void * 1992void *
1991GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h, 1993GNUNET_DISK_file_map(const struct GNUNET_DISK_FileHandle *h,
1992 struct GNUNET_DISK_MapHandle **m, 1994 struct GNUNET_DISK_MapHandle **m,
1993 enum GNUNET_DISK_MapType access, 1995 enum GNUNET_DISK_MapType access,
1994 size_t len) 1996 size_t len)
1995{ 1997{
1996 if (NULL == h) 1998 if (NULL == h)
1997 { 1999 {
1998 errno = EINVAL; 2000 errno = EINVAL;
1999 return NULL; 2001 return NULL;
2000 } 2002 }
2001 2003
2002#ifdef MINGW 2004#ifdef MINGW
2003 DWORD mapAccess, protect; 2005 DWORD mapAccess, protect;
2004 2006
2005 if ((access & GNUNET_DISK_MAP_TYPE_READ) && 2007 if ((access & GNUNET_DISK_MAP_TYPE_READ) &&
2006 (access & GNUNET_DISK_MAP_TYPE_WRITE)) 2008 (access & GNUNET_DISK_MAP_TYPE_WRITE))
2007 { 2009 {
2008 protect = PAGE_READWRITE; 2010 protect = PAGE_READWRITE;
2009 mapAccess = FILE_MAP_ALL_ACCESS; 2011 mapAccess = FILE_MAP_ALL_ACCESS;
2010 } 2012 }
2011 else if (access & GNUNET_DISK_MAP_TYPE_READ) 2013 else if (access & GNUNET_DISK_MAP_TYPE_READ)
2012 { 2014 {
2013 protect = PAGE_READONLY; 2015 protect = PAGE_READONLY;
2014 mapAccess = FILE_MAP_READ; 2016 mapAccess = FILE_MAP_READ;
2015 } 2017 }
2016 else if (access & GNUNET_DISK_MAP_TYPE_WRITE) 2018 else if (access & GNUNET_DISK_MAP_TYPE_WRITE)
2017 { 2019 {
2018 protect = PAGE_READWRITE; 2020 protect = PAGE_READWRITE;
2019 mapAccess = FILE_MAP_WRITE; 2021 mapAccess = FILE_MAP_WRITE;
2020 } 2022 }
2021 else 2023 else
2022 { 2024 {
2023 GNUNET_break (0); 2025 GNUNET_break(0);
2024 return NULL; 2026 return NULL;
2025 } 2027 }
2026 2028
2027 *m = GNUNET_new (struct GNUNET_DISK_MapHandle); 2029 *m = GNUNET_new(struct GNUNET_DISK_MapHandle);
2028 (*m)->h = CreateFileMapping (h->h, NULL, protect, 0, 0, NULL); 2030 (*m)->h = CreateFileMapping(h->h, NULL, protect, 0, 0, NULL);
2029 if ((*m)->h == INVALID_HANDLE_VALUE) 2031 if ((*m)->h == INVALID_HANDLE_VALUE)
2030 { 2032 {
2031 SetErrnoFromWinError (GetLastError ()); 2033 SetErrnoFromWinError(GetLastError());
2032 GNUNET_free (*m); 2034 GNUNET_free(*m);
2033 return NULL; 2035 return NULL;
2034 } 2036 }
2035 2037
2036 (*m)->addr = MapViewOfFile ((*m)->h, mapAccess, 0, 0, len); 2038 (*m)->addr = MapViewOfFile((*m)->h, mapAccess, 0, 0, len);
2037 if (! (*m)->addr) 2039 if (!(*m)->addr)
2038 { 2040 {
2039 SetErrnoFromWinError (GetLastError ()); 2041 SetErrnoFromWinError(GetLastError());
2040 CloseHandle ((*m)->h); 2042 CloseHandle((*m)->h);
2041 GNUNET_free (*m); 2043 GNUNET_free(*m);
2042 } 2044 }
2043 2045
2044 return (*m)->addr; 2046 return (*m)->addr;
2045#else 2047#else
@@ -2050,14 +2052,14 @@ GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
2050 prot = PROT_READ; 2052 prot = PROT_READ;
2051 if (access & GNUNET_DISK_MAP_TYPE_WRITE) 2053 if (access & GNUNET_DISK_MAP_TYPE_WRITE)
2052 prot |= PROT_WRITE; 2054 prot |= PROT_WRITE;
2053 *m = GNUNET_new (struct GNUNET_DISK_MapHandle); 2055 *m = GNUNET_new(struct GNUNET_DISK_MapHandle);
2054 (*m)->addr = mmap (NULL, len, prot, MAP_SHARED, h->fd, 0); 2056 (*m)->addr = mmap(NULL, len, prot, MAP_SHARED, h->fd, 0);
2055 GNUNET_assert (NULL != (*m)->addr); 2057 GNUNET_assert(NULL != (*m)->addr);
2056 if (MAP_FAILED == (*m)->addr) 2058 if (MAP_FAILED == (*m)->addr)
2057 { 2059 {
2058 GNUNET_free (*m); 2060 GNUNET_free(*m);
2059 return NULL; 2061 return NULL;
2060 } 2062 }
2061 (*m)->len = len; 2063 (*m)->len = len;
2062 return (*m)->addr; 2064 return (*m)->addr;
2063#endif 2065#endif
@@ -2069,29 +2071,29 @@ GNUNET_DISK_file_map (const struct GNUNET_DISK_FileHandle *h,
2069 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise 2071 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2070 */ 2072 */
2071int 2073int
2072GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h) 2074GNUNET_DISK_file_unmap(struct GNUNET_DISK_MapHandle *h)
2073{ 2075{
2074 int ret; 2076 int ret;
2075 2077
2076 if (h == NULL) 2078 if (h == NULL)
2077 { 2079 {
2078 errno = EINVAL; 2080 errno = EINVAL;
2079 return GNUNET_SYSERR; 2081 return GNUNET_SYSERR;
2080 } 2082 }
2081 2083
2082#ifdef MINGW 2084#ifdef MINGW
2083 ret = UnmapViewOfFile (h->addr) ? GNUNET_OK : GNUNET_SYSERR; 2085 ret = UnmapViewOfFile(h->addr) ? GNUNET_OK : GNUNET_SYSERR;
2084 if (ret != GNUNET_OK) 2086 if (ret != GNUNET_OK)
2085 SetErrnoFromWinError (GetLastError ()); 2087 SetErrnoFromWinError(GetLastError());
2086 if (! CloseHandle (h->h) && (ret == GNUNET_OK)) 2088 if (!CloseHandle(h->h) && (ret == GNUNET_OK))
2087 { 2089 {
2088 ret = GNUNET_SYSERR; 2090 ret = GNUNET_SYSERR;
2089 SetErrnoFromWinError (GetLastError ()); 2091 SetErrnoFromWinError(GetLastError());
2090 } 2092 }
2091#else 2093#else
2092 ret = munmap (h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR; 2094 ret = munmap(h->addr, h->len) != -1 ? GNUNET_OK : GNUNET_SYSERR;
2093#endif 2095#endif
2094 GNUNET_free (h); 2096 GNUNET_free(h);
2095 return ret; 2097 return ret;
2096} 2098}
2097 2099
@@ -2102,25 +2104,25 @@ GNUNET_DISK_file_unmap (struct GNUNET_DISK_MapHandle *h)
2102 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise 2104 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2103 */ 2105 */
2104int 2106int
2105GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h) 2107GNUNET_DISK_file_sync(const struct GNUNET_DISK_FileHandle *h)
2106{ 2108{
2107 if (h == NULL) 2109 if (h == NULL)
2108 { 2110 {
2109 errno = EINVAL; 2111 errno = EINVAL;
2110 return GNUNET_SYSERR; 2112 return GNUNET_SYSERR;
2111 } 2113 }
2112 2114
2113#ifdef MINGW 2115#ifdef MINGW
2114 int ret; 2116 int ret;
2115 2117
2116 ret = FlushFileBuffers (h->h) ? GNUNET_OK : GNUNET_SYSERR; 2118 ret = FlushFileBuffers(h->h) ? GNUNET_OK : GNUNET_SYSERR;
2117 if (ret != GNUNET_OK) 2119 if (ret != GNUNET_OK)
2118 SetErrnoFromWinError (GetLastError ()); 2120 SetErrnoFromWinError(GetLastError());
2119 return ret; 2121 return ret;
2120#elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN) 2122#elif defined(FREEBSD) || defined(OPENBSD) || defined(DARWIN)
2121 return fsync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK; 2123 return fsync(h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2122#else 2124#else
2123 return fdatasync (h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK; 2125 return fdatasync(h->fd) == -1 ? GNUNET_SYSERR : GNUNET_OK;
2124#endif 2126#endif
2125} 2127}
2126 2128
@@ -2131,7 +2133,7 @@ GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
2131#endif 2133#endif
2132/* Copyright Bob Byrnes <byrnes <at> curl.com> 2134/* Copyright Bob Byrnes <byrnes <at> curl.com>
2133 http://permalink.gmane.org/gmane.os.cygwin.patches/2121 2135 http://permalink.gmane.org/gmane.os.cygwin.patches/2121
2134*/ 2136 */
2135/* Create a pipe, and return handles to the read and write ends, 2137/* Create a pipe, and return handles to the read and write ends,
2136 just like CreatePipe, but ensure that the write end permits 2138 just like CreatePipe, but ensure that the write end permits
2137 FILE_READ_ATTRIBUTES access, on later versions of win32 where 2139 FILE_READ_ATTRIBUTES access, on later versions of win32 where
@@ -2140,12 +2142,12 @@ GNUNET_DISK_file_sync (const struct GNUNET_DISK_FileHandle *h)
2140 Note that the return value is either NO_ERROR or GetLastError, 2142 Note that the return value is either NO_ERROR or GetLastError,
2141 unlike CreatePipe, which returns a bool for success or failure. */ 2143 unlike CreatePipe, which returns a bool for success or failure. */
2142static int 2144static int
2143create_selectable_pipe (PHANDLE read_pipe_ptr, 2145create_selectable_pipe(PHANDLE read_pipe_ptr,
2144 PHANDLE write_pipe_ptr, 2146 PHANDLE write_pipe_ptr,
2145 LPSECURITY_ATTRIBUTES sa_ptr, 2147 LPSECURITY_ATTRIBUTES sa_ptr,
2146 DWORD psize, 2148 DWORD psize,
2147 DWORD dwReadMode, 2149 DWORD dwReadMode,
2148 DWORD dwWriteMode) 2150 DWORD dwWriteMode)
2149{ 2151{
2150 /* Default to error. */ 2152 /* Default to error. */
2151 *read_pipe_ptr = *write_pipe_ptr = INVALID_HANDLE_VALUE; 2153 *read_pipe_ptr = *write_pipe_ptr = INVALID_HANDLE_VALUE;
@@ -2163,102 +2165,105 @@ create_selectable_pipe (PHANDLE read_pipe_ptr,
2163 * Retrying will probably never be necessary, but we want 2165 * Retrying will probably never be necessary, but we want
2164 * to be as robust as possible. */ 2166 * to be as robust as possible. */
2165 while (1) 2167 while (1)
2166 { 2168 {
2167 static volatile LONG pipe_unique_id; 2169 static volatile LONG pipe_unique_id;
2168 2170
2169 snprintf (pipename, 2171 snprintf(pipename,
2170 sizeof pipename, 2172 sizeof pipename,
2171 "\\\\.\\pipe\\gnunet-%d-%ld", 2173 "\\\\.\\pipe\\gnunet-%d-%ld",
2172 getpid (), 2174 getpid(),
2173 InterlockedIncrement ((LONG *) &pipe_unique_id)); 2175 InterlockedIncrement((LONG *)&pipe_unique_id));
2174 LOG (GNUNET_ERROR_TYPE_DEBUG, 2176 LOG(GNUNET_ERROR_TYPE_DEBUG,
2175 "CreateNamedPipe: name = %s, size = %lu\n", 2177 "CreateNamedPipe: name = %s, size = %lu\n",
2176 pipename, 2178 pipename,
2177 psize); 2179 psize);
2178 /* Use CreateNamedPipe instead of CreatePipe, because the latter 2180 /* Use CreateNamedPipe instead of CreatePipe, because the latter
2179 * returns a write handle that does not permit FILE_READ_ATTRIBUTES 2181 * returns a write handle that does not permit FILE_READ_ATTRIBUTES
2180 * access, on versions of win32 earlier than WinXP SP2. 2182 * access, on versions of win32 earlier than WinXP SP2.
2181 * CreatePipe also stupidly creates a full duplex pipe, which is 2183 * CreatePipe also stupidly creates a full duplex pipe, which is
2182 * a waste, since only a single direction is actually used. 2184 * a waste, since only a single direction is actually used.
2183 * It's important to only allow a single instance, to ensure that 2185 * It's important to only allow a single instance, to ensure that
2184 * the pipe was not created earlier by some other process, even if 2186 * the pipe was not created earlier by some other process, even if
2185 * the pid has been reused. */ 2187 * the pid has been reused. */
2186 read_pipe = CreateNamedPipeA (pipename, 2188 read_pipe = CreateNamedPipeA(pipename,
2187 PIPE_ACCESS_INBOUND | 2189 PIPE_ACCESS_INBOUND |
2188 FILE_FLAG_FIRST_PIPE_INSTANCE | dwReadMode, 2190 FILE_FLAG_FIRST_PIPE_INSTANCE | dwReadMode,
2189 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 2191 PIPE_TYPE_BYTE | PIPE_READMODE_BYTE,
2190 1, /* max instances */ 2192 1, /* max instances */
2191 psize, /* output buffer size */ 2193 psize, /* output buffer size */
2192 psize, /* input buffer size */ 2194 psize, /* input buffer size */
2193 NMPWAIT_USE_DEFAULT_WAIT, 2195 NMPWAIT_USE_DEFAULT_WAIT,
2194 sa_ptr); 2196 sa_ptr);
2195 2197
2196 if (read_pipe != INVALID_HANDLE_VALUE) 2198 if (read_pipe != INVALID_HANDLE_VALUE)
2197 { 2199 {
2198 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n", read_pipe); 2200 LOG(GNUNET_ERROR_TYPE_DEBUG, "pipe read handle = %p\n", read_pipe);
2199 break; 2201 break;
2200 } 2202 }
2201 2203
2202 DWORD err = GetLastError (); 2204 DWORD err = GetLastError();
2203 2205
2204 switch (err) 2206 switch (err)
2205 { 2207 {
2206 case ERROR_PIPE_BUSY: 2208 case ERROR_PIPE_BUSY:
2207 /* The pipe is already open with compatible parameters. 2209 /* The pipe is already open with compatible parameters.
2208 * Pick a new name and retry. */ 2210 * Pick a new name and retry. */
2209 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe busy, retrying\n"); 2211 LOG(GNUNET_ERROR_TYPE_DEBUG, "pipe busy, retrying\n");
2210 continue; 2212 continue;
2211 case ERROR_ACCESS_DENIED: 2213
2212 /* The pipe is already open with incompatible parameters. 2214 case ERROR_ACCESS_DENIED:
2213 * Pick a new name and retry. */ 2215 /* The pipe is already open with incompatible parameters.
2214 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe access denied, retrying\n"); 2216 * Pick a new name and retry. */
2215 continue; 2217 LOG(GNUNET_ERROR_TYPE_DEBUG, "pipe access denied, retrying\n");
2216 case ERROR_CALL_NOT_IMPLEMENTED: 2218 continue;
2217 /* We are on an older Win9x platform without named pipes. 2219
2218 * Return an anonymous pipe as the best approximation. */ 2220 case ERROR_CALL_NOT_IMPLEMENTED:
2219 LOG (GNUNET_ERROR_TYPE_DEBUG, 2221 /* We are on an older Win9x platform without named pipes.
2220 "CreateNamedPipe not implemented, resorting to " 2222 * Return an anonymous pipe as the best approximation. */
2221 "CreatePipe: size = %lu\n", 2223 LOG(GNUNET_ERROR_TYPE_DEBUG,
2222 psize); 2224 "CreateNamedPipe not implemented, resorting to "
2223 if (CreatePipe (read_pipe_ptr, write_pipe_ptr, sa_ptr, psize)) 2225 "CreatePipe: size = %lu\n",
2224 { 2226 psize);
2225 LOG (GNUNET_ERROR_TYPE_DEBUG, 2227 if (CreatePipe(read_pipe_ptr, write_pipe_ptr, sa_ptr, psize))
2226 "pipe read handle = %p, write handle = %p\n", 2228 {
2227 *read_pipe_ptr, 2229 LOG(GNUNET_ERROR_TYPE_DEBUG,
2228 *write_pipe_ptr); 2230 "pipe read handle = %p, write handle = %p\n",
2229 return GNUNET_OK; 2231 *read_pipe_ptr,
2230 } 2232 *write_pipe_ptr);
2231 err = GetLastError (); 2233 return GNUNET_OK;
2232 LOG (GNUNET_ERROR_TYPE_ERROR, "CreatePipe failed: %d\n", err); 2234 }
2233 return err; 2235 err = GetLastError();
2234 default: 2236 LOG(GNUNET_ERROR_TYPE_ERROR, "CreatePipe failed: %d\n", err);
2235 LOG (GNUNET_ERROR_TYPE_ERROR, "CreateNamedPipe failed: %d\n", err); 2237 return err;
2236 return err; 2238
2239 default:
2240 LOG(GNUNET_ERROR_TYPE_ERROR, "CreateNamedPipe failed: %d\n", err);
2241 return err;
2242 }
2243 /* NOTREACHED */
2237 } 2244 }
2238 /* NOTREACHED */ 2245 LOG(GNUNET_ERROR_TYPE_DEBUG, "CreateFile: name = %s\n", pipename);
2239 }
2240 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile: name = %s\n", pipename);
2241 2246
2242 /* Open the named pipe for writing. 2247 /* Open the named pipe for writing.
2243 * Be sure to permit FILE_READ_ATTRIBUTES access. */ 2248 * Be sure to permit FILE_READ_ATTRIBUTES access. */
2244 write_pipe = CreateFileA (pipename, 2249 write_pipe = CreateFileA(pipename,
2245 GENERIC_WRITE | FILE_READ_ATTRIBUTES, 2250 GENERIC_WRITE | FILE_READ_ATTRIBUTES,
2246 0, /* share mode */ 2251 0, /* share mode */
2247 sa_ptr, 2252 sa_ptr,
2248 OPEN_EXISTING, 2253 OPEN_EXISTING,
2249 dwWriteMode, /* flags and attributes */ 2254 dwWriteMode, /* flags and attributes */
2250 0); /* handle to template file */ 2255 0); /* handle to template file */
2251 2256
2252 if (write_pipe == INVALID_HANDLE_VALUE) 2257 if (write_pipe == INVALID_HANDLE_VALUE)
2253 { 2258 {
2254 /* Failure. */ 2259 /* Failure. */
2255 DWORD err = GetLastError (); 2260 DWORD err = GetLastError();
2256 2261
2257 LOG (GNUNET_ERROR_TYPE_DEBUG, "CreateFile failed: %d\n", err); 2262 LOG(GNUNET_ERROR_TYPE_DEBUG, "CreateFile failed: %d\n", err);
2258 CloseHandle (read_pipe); 2263 CloseHandle(read_pipe);
2259 return err; 2264 return err;
2260 } 2265 }
2261 LOG (GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n", write_pipe); 2266 LOG(GNUNET_ERROR_TYPE_DEBUG, "pipe write handle = %p\n", write_pipe);
2262 /* Success. */ 2267 /* Success. */
2263 *read_pipe_ptr = read_pipe; 2268 *read_pipe_ptr = read_pipe;
2264 *write_pipe_ptr = write_pipe; 2269 *write_pipe_ptr = write_pipe;
@@ -2277,36 +2282,36 @@ create_selectable_pipe (PHANDLE read_pipe_ptr,
2277 * @return handle to the new pipe, NULL on error 2282 * @return handle to the new pipe, NULL on error
2278 */ 2283 */
2279struct GNUNET_DISK_PipeHandle * 2284struct GNUNET_DISK_PipeHandle *
2280GNUNET_DISK_pipe (int blocking_read, 2285GNUNET_DISK_pipe(int blocking_read,
2281 int blocking_write, 2286 int blocking_write,
2282 int inherit_read, 2287 int inherit_read,
2283 int inherit_write) 2288 int inherit_write)
2284{ 2289{
2285#ifndef MINGW 2290#ifndef MINGW
2286 int fd[2]; 2291 int fd[2];
2287 int ret; 2292 int ret;
2288 int eno; 2293 int eno;
2289 2294
2290 (void) inherit_read; 2295 (void)inherit_read;
2291 (void) inherit_write; 2296 (void)inherit_write;
2292 ret = pipe (fd); 2297 ret = pipe(fd);
2293 if (ret == -1) 2298 if (ret == -1)
2294 { 2299 {
2295 eno = errno; 2300 eno = errno;
2296 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe"); 2301 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "pipe");
2297 errno = eno; 2302 errno = eno;
2298 return NULL; 2303 return NULL;
2299 } 2304 }
2300 return GNUNET_DISK_pipe_from_fd (blocking_read, blocking_write, fd); 2305 return GNUNET_DISK_pipe_from_fd(blocking_read, blocking_write, fd);
2301#else 2306#else
2302 struct GNUNET_DISK_PipeHandle *p; 2307 struct GNUNET_DISK_PipeHandle *p;
2303 BOOL ret; 2308 BOOL ret;
2304 HANDLE tmp_handle; 2309 HANDLE tmp_handle;
2305 int save_errno; 2310 int save_errno;
2306 2311
2307 p = GNUNET_new (struct GNUNET_DISK_PipeHandle); 2312 p = GNUNET_new(struct GNUNET_DISK_PipeHandle);
2308 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle); 2313 p->fd[0] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2309 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle); 2314 p->fd[1] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2310 2315
2311 /* All pipes are overlapped. If you want them to block - just 2316 /* All pipes are overlapped. If you want them to block - just
2312 * call WriteFile() and ReadFile() with NULL overlapped pointer. 2317 * call WriteFile() and ReadFile() with NULL overlapped pointer.
@@ -2317,77 +2322,77 @@ GNUNET_DISK_pipe (int blocking_read,
2317 * Pipes are not seekable, and need no offsets, which is 2322 * Pipes are not seekable, and need no offsets, which is
2318 * probably why it works for them. 2323 * probably why it works for them.
2319 */ 2324 */
2320 ret = create_selectable_pipe (&p->fd[0]->h, 2325 ret = create_selectable_pipe(&p->fd[0]->h,
2321 &p->fd[1]->h, 2326 &p->fd[1]->h,
2322 NULL, 2327 NULL,
2323 0, 2328 0,
2324 FILE_FLAG_OVERLAPPED, 2329 FILE_FLAG_OVERLAPPED,
2325 FILE_FLAG_OVERLAPPED); 2330 FILE_FLAG_OVERLAPPED);
2326 if (! ret) 2331 if (!ret)
2327 { 2332 {
2328 SetErrnoFromWinError (GetLastError ()); 2333 SetErrnoFromWinError(GetLastError());
2329 save_errno = errno; 2334 save_errno = errno;
2330 GNUNET_free (p->fd[0]); 2335 GNUNET_free(p->fd[0]);
2331 GNUNET_free (p->fd[1]); 2336 GNUNET_free(p->fd[1]);
2332 GNUNET_free (p); 2337 GNUNET_free(p);
2333 errno = save_errno; 2338 errno = save_errno;
2334 return NULL; 2339 return NULL;
2335 } 2340 }
2336 if (! DuplicateHandle (GetCurrentProcess (), 2341 if (!DuplicateHandle(GetCurrentProcess(),
2337 p->fd[0]->h, 2342 p->fd[0]->h,
2338 GetCurrentProcess (), 2343 GetCurrentProcess(),
2339 &tmp_handle, 2344 &tmp_handle,
2340 0, 2345 0,
2341 inherit_read == GNUNET_YES ? TRUE : FALSE, 2346 inherit_read == GNUNET_YES ? TRUE : FALSE,
2342 DUPLICATE_SAME_ACCESS)) 2347 DUPLICATE_SAME_ACCESS))
2343 { 2348 {
2344 SetErrnoFromWinError (GetLastError ()); 2349 SetErrnoFromWinError(GetLastError());
2345 save_errno = errno; 2350 save_errno = errno;
2346 CloseHandle (p->fd[0]->h); 2351 CloseHandle(p->fd[0]->h);
2347 CloseHandle (p->fd[1]->h); 2352 CloseHandle(p->fd[1]->h);
2348 GNUNET_free (p->fd[0]); 2353 GNUNET_free(p->fd[0]);
2349 GNUNET_free (p->fd[1]); 2354 GNUNET_free(p->fd[1]);
2350 GNUNET_free (p); 2355 GNUNET_free(p);
2351 errno = save_errno; 2356 errno = save_errno;
2352 return NULL; 2357 return NULL;
2353 } 2358 }
2354 CloseHandle (p->fd[0]->h); 2359 CloseHandle(p->fd[0]->h);
2355 p->fd[0]->h = tmp_handle; 2360 p->fd[0]->h = tmp_handle;
2356 2361
2357 if (! DuplicateHandle (GetCurrentProcess (), 2362 if (!DuplicateHandle(GetCurrentProcess(),
2358 p->fd[1]->h, 2363 p->fd[1]->h,
2359 GetCurrentProcess (), 2364 GetCurrentProcess(),
2360 &tmp_handle, 2365 &tmp_handle,
2361 0, 2366 0,
2362 inherit_write == GNUNET_YES ? TRUE : FALSE, 2367 inherit_write == GNUNET_YES ? TRUE : FALSE,
2363 DUPLICATE_SAME_ACCESS)) 2368 DUPLICATE_SAME_ACCESS))
2364 { 2369 {
2365 SetErrnoFromWinError (GetLastError ()); 2370 SetErrnoFromWinError(GetLastError());
2366 save_errno = errno; 2371 save_errno = errno;
2367 CloseHandle (p->fd[0]->h); 2372 CloseHandle(p->fd[0]->h);
2368 CloseHandle (p->fd[1]->h); 2373 CloseHandle(p->fd[1]->h);
2369 GNUNET_free (p->fd[0]); 2374 GNUNET_free(p->fd[0]);
2370 GNUNET_free (p->fd[1]); 2375 GNUNET_free(p->fd[1]);
2371 GNUNET_free (p); 2376 GNUNET_free(p);
2372 errno = save_errno; 2377 errno = save_errno;
2373 return NULL; 2378 return NULL;
2374 } 2379 }
2375 CloseHandle (p->fd[1]->h); 2380 CloseHandle(p->fd[1]->h);
2376 p->fd[1]->h = tmp_handle; 2381 p->fd[1]->h = tmp_handle;
2377 2382
2378 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE; 2383 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2379 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE; 2384 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2380 2385
2381 p->fd[0]->oOverlapRead = GNUNET_new (OVERLAPPED); 2386 p->fd[0]->oOverlapRead = GNUNET_new(OVERLAPPED);
2382 p->fd[0]->oOverlapWrite = GNUNET_new (OVERLAPPED); 2387 p->fd[0]->oOverlapWrite = GNUNET_new(OVERLAPPED);
2383 p->fd[1]->oOverlapRead = GNUNET_new (OVERLAPPED); 2388 p->fd[1]->oOverlapRead = GNUNET_new(OVERLAPPED);
2384 p->fd[1]->oOverlapWrite = GNUNET_new (OVERLAPPED); 2389 p->fd[1]->oOverlapWrite = GNUNET_new(OVERLAPPED);
2385 2390
2386 p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 2391 p->fd[0]->oOverlapRead->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2387 p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 2392 p->fd[0]->oOverlapWrite->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2388 2393
2389 p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 2394 p->fd[1]->oOverlapRead->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2390 p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL); 2395 p->fd[1]->oOverlapWrite->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2391 2396
2392 return p; 2397 return p;
2393#endif 2398#endif
@@ -2405,11 +2410,11 @@ GNUNET_DISK_pipe (int blocking_read,
2405 * @return handle to the new pipe, NULL on error 2410 * @return handle to the new pipe, NULL on error
2406 */ 2411 */
2407struct GNUNET_DISK_PipeHandle * 2412struct GNUNET_DISK_PipeHandle *
2408GNUNET_DISK_pipe_from_fd (int blocking_read, int blocking_write, int fd[2]) 2413GNUNET_DISK_pipe_from_fd(int blocking_read, int blocking_write, int fd[2])
2409{ 2414{
2410 struct GNUNET_DISK_PipeHandle *p; 2415 struct GNUNET_DISK_PipeHandle *p;
2411 2416
2412 p = GNUNET_new (struct GNUNET_DISK_PipeHandle); 2417 p = GNUNET_new(struct GNUNET_DISK_PipeHandle);
2413 2418
2414#ifndef MINGW 2419#ifndef MINGW
2415 int ret; 2420 int ret;
@@ -2418,102 +2423,101 @@ GNUNET_DISK_pipe_from_fd (int blocking_read, int blocking_write, int fd[2])
2418 2423
2419 ret = 0; 2424 ret = 0;
2420 if (fd[0] >= 0) 2425 if (fd[0] >= 0)
2421 {
2422 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2423 p->fd[0]->fd = fd[0];
2424 if (! blocking_read)
2425 { 2426 {
2426 flags = fcntl (fd[0], F_GETFL); 2427 p->fd[0] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2427 flags |= O_NONBLOCK; 2428 p->fd[0]->fd = fd[0];
2428 if (0 > fcntl (fd[0], F_SETFL, flags)) 2429 if (!blocking_read)
2429 { 2430 {
2430 ret = -1; 2431 flags = fcntl(fd[0], F_GETFL);
2431 eno = errno; 2432 flags |= O_NONBLOCK;
2432 } 2433 if (0 > fcntl(fd[0], F_SETFL, flags))
2433 } 2434 {
2434 flags = fcntl (fd[0], F_GETFD); 2435 ret = -1;
2435 flags |= FD_CLOEXEC; 2436 eno = errno;
2436 if (0 > fcntl (fd[0], F_SETFD, flags)) 2437 }
2437 { 2438 }
2438 ret = -1; 2439 flags = fcntl(fd[0], F_GETFD);
2439 eno = errno; 2440 flags |= FD_CLOEXEC;
2441 if (0 > fcntl(fd[0], F_SETFD, flags))
2442 {
2443 ret = -1;
2444 eno = errno;
2445 }
2440 } 2446 }
2441 }
2442 2447
2443 if (fd[1] >= 0) 2448 if (fd[1] >= 0)
2444 {
2445 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2446 p->fd[1]->fd = fd[1];
2447 if (! blocking_write)
2448 { 2449 {
2449 flags = fcntl (fd[1], F_GETFL); 2450 p->fd[1] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2450 flags |= O_NONBLOCK; 2451 p->fd[1]->fd = fd[1];
2451 if (0 > fcntl (fd[1], F_SETFL, flags)) 2452 if (!blocking_write)
2452 { 2453 {
2453 ret = -1; 2454 flags = fcntl(fd[1], F_GETFL);
2454 eno = errno; 2455 flags |= O_NONBLOCK;
2455 } 2456 if (0 > fcntl(fd[1], F_SETFL, flags))
2457 {
2458 ret = -1;
2459 eno = errno;
2460 }
2461 }
2462 flags = fcntl(fd[1], F_GETFD);
2463 flags |= FD_CLOEXEC;
2464 if (0 > fcntl(fd[1], F_SETFD, flags))
2465 {
2466 ret = -1;
2467 eno = errno;
2468 }
2456 } 2469 }
2457 flags = fcntl (fd[1], F_GETFD); 2470 if (ret == -1)
2458 flags |= FD_CLOEXEC;
2459 if (0 > fcntl (fd[1], F_SETFD, flags))
2460 { 2471 {
2461 ret = -1; 2472 errno = eno;
2462 eno = errno; 2473 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "fcntl");
2474 if (p->fd[0]->fd >= 0)
2475 GNUNET_break(0 == close(p->fd[0]->fd));
2476 if (p->fd[1]->fd >= 0)
2477 GNUNET_break(0 == close(p->fd[1]->fd));
2478 GNUNET_free_non_null(p->fd[0]);
2479 GNUNET_free_non_null(p->fd[1]);
2480 GNUNET_free(p);
2481 errno = eno;
2482 return NULL;
2463 } 2483 }
2464 }
2465 if (ret == -1)
2466 {
2467 errno = eno;
2468 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fcntl");
2469 if (p->fd[0]->fd >= 0)
2470 GNUNET_break (0 == close (p->fd[0]->fd));
2471 if (p->fd[1]->fd >= 0)
2472 GNUNET_break (0 == close (p->fd[1]->fd));
2473 GNUNET_free_non_null (p->fd[0]);
2474 GNUNET_free_non_null (p->fd[1]);
2475 GNUNET_free (p);
2476 errno = eno;
2477 return NULL;
2478 }
2479#else 2484#else
2480 if (fd[0] >= 0) 2485 if (fd[0] >= 0)
2481 {
2482 p->fd[0] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2483 p->fd[0]->h = (HANDLE) _get_osfhandle (fd[0]);
2484 if (p->fd[0]->h != INVALID_HANDLE_VALUE)
2485 {
2486 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2487 p->fd[0]->oOverlapRead = GNUNET_new (OVERLAPPED);
2488 p->fd[0]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2489 p->fd[0]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2490 p->fd[0]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2491 }
2492 else
2493 { 2486 {
2494 GNUNET_free (p->fd[0]); 2487 p->fd[0] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2495 p->fd[0] = NULL; 2488 p->fd[0]->h = (HANDLE)_get_osfhandle(fd[0]);
2489 if (p->fd[0]->h != INVALID_HANDLE_VALUE)
2490 {
2491 p->fd[0]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2492 p->fd[0]->oOverlapRead = GNUNET_new(OVERLAPPED);
2493 p->fd[0]->oOverlapWrite = GNUNET_new(OVERLAPPED);
2494 p->fd[0]->oOverlapRead->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2495 p->fd[0]->oOverlapWrite->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2496 }
2497 else
2498 {
2499 GNUNET_free(p->fd[0]);
2500 p->fd[0] = NULL;
2501 }
2496 } 2502 }
2497 }
2498 if (fd[1] >= 0) 2503 if (fd[1] >= 0)
2499 {
2500 p->fd[1] = GNUNET_new (struct GNUNET_DISK_FileHandle);
2501 p->fd[1]->h = (HANDLE) _get_osfhandle (fd[1]);
2502 if (p->fd[1]->h != INVALID_HANDLE_VALUE)
2503 {
2504 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2505 p->fd[1]->oOverlapRead = GNUNET_new (OVERLAPPED);
2506 p->fd[1]->oOverlapWrite = GNUNET_new (OVERLAPPED);
2507 p->fd[1]->oOverlapRead->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2508 p->fd[1]->oOverlapWrite->hEvent = CreateEvent (NULL, FALSE, FALSE, NULL);
2509 }
2510 else
2511 { 2504 {
2512 GNUNET_free (p->fd[1]); 2505 p->fd[1] = GNUNET_new(struct GNUNET_DISK_FileHandle);
2513 p->fd[1] = NULL; 2506 p->fd[1]->h = (HANDLE)_get_osfhandle(fd[1]);
2507 if (p->fd[1]->h != INVALID_HANDLE_VALUE)
2508 {
2509 p->fd[1]->type = GNUNET_DISK_HANLDE_TYPE_PIPE;
2510 p->fd[1]->oOverlapRead = GNUNET_new(OVERLAPPED);
2511 p->fd[1]->oOverlapWrite = GNUNET_new(OVERLAPPED);
2512 p->fd[1]->oOverlapRead->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2513 p->fd[1]->oOverlapWrite->hEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
2514 }
2515 else
2516 {
2517 GNUNET_free(p->fd[1]);
2518 p->fd[1] = NULL;
2519 }
2514 } 2520 }
2515 }
2516
2517#endif 2521#endif
2518 return p; 2522 return p;
2519} 2523}
@@ -2527,27 +2531,27 @@ GNUNET_DISK_pipe_from_fd (int blocking_read, int blocking_write, int fd[2])
2527 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise 2531 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2528 */ 2532 */
2529int 2533int
2530GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p, 2534GNUNET_DISK_pipe_close_end(struct GNUNET_DISK_PipeHandle *p,
2531 enum GNUNET_DISK_PipeEnd end) 2535 enum GNUNET_DISK_PipeEnd end)
2532{ 2536{
2533 int ret = GNUNET_OK; 2537 int ret = GNUNET_OK;
2534 2538
2535 if (end == GNUNET_DISK_PIPE_END_READ) 2539 if (end == GNUNET_DISK_PIPE_END_READ)
2536 {
2537 if (p->fd[0])
2538 { 2540 {
2539 ret = GNUNET_DISK_file_close (p->fd[0]); 2541 if (p->fd[0])
2540 p->fd[0] = NULL; 2542 {
2543 ret = GNUNET_DISK_file_close(p->fd[0]);
2544 p->fd[0] = NULL;
2545 }
2541 } 2546 }
2542 }
2543 else if (end == GNUNET_DISK_PIPE_END_WRITE) 2547 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2544 {
2545 if (p->fd[1])
2546 { 2548 {
2547 ret = GNUNET_DISK_file_close (p->fd[1]); 2549 if (p->fd[1])
2548 p->fd[1] = NULL; 2550 {
2551 ret = GNUNET_DISK_file_close(p->fd[1]);
2552 p->fd[1] = NULL;
2553 }
2549 } 2554 }
2550 }
2551 2555
2552 return ret; 2556 return ret;
2553} 2557}
@@ -2565,27 +2569,27 @@ GNUNET_DISK_pipe_close_end (struct GNUNET_DISK_PipeHandle *p,
2565 * (or if that end is not present or is closed). 2569 * (or if that end is not present or is closed).
2566 */ 2570 */
2567struct GNUNET_DISK_FileHandle * 2571struct GNUNET_DISK_FileHandle *
2568GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p, 2572GNUNET_DISK_pipe_detach_end(struct GNUNET_DISK_PipeHandle *p,
2569 enum GNUNET_DISK_PipeEnd end) 2573 enum GNUNET_DISK_PipeEnd end)
2570{ 2574{
2571 struct GNUNET_DISK_FileHandle *ret = NULL; 2575 struct GNUNET_DISK_FileHandle *ret = NULL;
2572 2576
2573 if (end == GNUNET_DISK_PIPE_END_READ) 2577 if (end == GNUNET_DISK_PIPE_END_READ)
2574 {
2575 if (p->fd[0])
2576 { 2578 {
2577 ret = p->fd[0]; 2579 if (p->fd[0])
2578 p->fd[0] = NULL; 2580 {
2581 ret = p->fd[0];
2582 p->fd[0] = NULL;
2583 }
2579 } 2584 }
2580 }
2581 else if (end == GNUNET_DISK_PIPE_END_WRITE) 2585 else if (end == GNUNET_DISK_PIPE_END_WRITE)
2582 {
2583 if (p->fd[1])
2584 { 2586 {
2585 ret = p->fd[1]; 2587 if (p->fd[1])
2586 p->fd[1] = NULL; 2588 {
2589 ret = p->fd[1];
2590 p->fd[1] = NULL;
2591 }
2587 } 2592 }
2588 }
2589 2593
2590 return ret; 2594 return ret;
2591} 2595}
@@ -2598,7 +2602,7 @@ GNUNET_DISK_pipe_detach_end (struct GNUNET_DISK_PipeHandle *p,
2598 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise 2602 * @return GNUNET_OK on success, GNUNET_SYSERR otherwise
2599 */ 2603 */
2600int 2604int
2601GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p) 2605GNUNET_DISK_pipe_close(struct GNUNET_DISK_PipeHandle *p)
2602{ 2606{
2603 int ret = GNUNET_OK; 2607 int ret = GNUNET_OK;
2604 2608
@@ -2607,22 +2611,22 @@ GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
2607 int read_end_close_errno; 2611 int read_end_close_errno;
2608 int write_end_close_errno; 2612 int write_end_close_errno;
2609 2613
2610 read_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_READ); 2614 read_end_close = GNUNET_DISK_pipe_close_end(p, GNUNET_DISK_PIPE_END_READ);
2611 read_end_close_errno = errno; 2615 read_end_close_errno = errno;
2612 write_end_close = GNUNET_DISK_pipe_close_end (p, GNUNET_DISK_PIPE_END_WRITE); 2616 write_end_close = GNUNET_DISK_pipe_close_end(p, GNUNET_DISK_PIPE_END_WRITE);
2613 write_end_close_errno = errno; 2617 write_end_close_errno = errno;
2614 GNUNET_free (p); 2618 GNUNET_free(p);
2615 2619
2616 if (GNUNET_OK != read_end_close) 2620 if (GNUNET_OK != read_end_close)
2617 { 2621 {
2618 errno = read_end_close_errno; 2622 errno = read_end_close_errno;
2619 ret = read_end_close; 2623 ret = read_end_close;
2620 } 2624 }
2621 else if (GNUNET_OK != write_end_close) 2625 else if (GNUNET_OK != write_end_close)
2622 { 2626 {
2623 errno = write_end_close_errno; 2627 errno = write_end_close_errno;
2624 ret = write_end_close; 2628 ret = write_end_close;
2625 } 2629 }
2626 2630
2627 return ret; 2631 return ret;
2628} 2632}
@@ -2636,18 +2640,19 @@ GNUNET_DISK_pipe_close (struct GNUNET_DISK_PipeHandle *p)
2636 * @return handle for the respective end 2640 * @return handle for the respective end
2637 */ 2641 */
2638const struct GNUNET_DISK_FileHandle * 2642const struct GNUNET_DISK_FileHandle *
2639GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p, 2643GNUNET_DISK_pipe_handle(const struct GNUNET_DISK_PipeHandle *p,
2640 enum GNUNET_DISK_PipeEnd n) 2644 enum GNUNET_DISK_PipeEnd n)
2641{ 2645{
2642 switch (n) 2646 switch (n)
2643 { 2647 {
2644 case GNUNET_DISK_PIPE_END_READ: 2648 case GNUNET_DISK_PIPE_END_READ:
2645 case GNUNET_DISK_PIPE_END_WRITE: 2649 case GNUNET_DISK_PIPE_END_WRITE:
2646 return p->fd[n]; 2650 return p->fd[n];
2647 default: 2651
2648 GNUNET_break (0); 2652 default:
2649 return NULL; 2653 GNUNET_break(0);
2650 } 2654 return NULL;
2655 }
2651} 2656}
2652 2657
2653 2658
@@ -2660,20 +2665,20 @@ GNUNET_DISK_pipe_handle (const struct GNUNET_DISK_PipeHandle *p,
2660 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 2665 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
2661 */ 2666 */
2662int 2667int
2663GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh, 2668GNUNET_DISK_internal_file_handle_(const struct GNUNET_DISK_FileHandle *fh,
2664 void *dst, 2669 void *dst,
2665 size_t dst_len) 2670 size_t dst_len)
2666{ 2671{
2667 if (NULL == fh) 2672 if (NULL == fh)
2668 return GNUNET_SYSERR; 2673 return GNUNET_SYSERR;
2669#ifdef MINGW 2674#ifdef MINGW
2670 if (dst_len < sizeof (HANDLE)) 2675 if (dst_len < sizeof(HANDLE))
2671 return GNUNET_SYSERR; 2676 return GNUNET_SYSERR;
2672 *((HANDLE *) dst) = fh->h; 2677 *((HANDLE *)dst) = fh->h;
2673#else 2678#else
2674 if (dst_len < sizeof (int)) 2679 if (dst_len < sizeof(int))
2675 return GNUNET_SYSERR; 2680 return GNUNET_SYSERR;
2676 *((int *) dst) = fh->fd; 2681 *((int *)dst) = fh->fd;
2677#endif 2682#endif
2678 2683
2679 return GNUNET_OK; 2684 return GNUNET_OK;
@@ -2688,24 +2693,24 @@ GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh,
2688 * @return #GNUNET_OK on success 2693 * @return #GNUNET_OK on success
2689 */ 2694 */
2690static int 2695static int
2691purge_cfg_dir (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg) 2696purge_cfg_dir(void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
2692{ 2697{
2693 const char *option = cls; 2698 const char *option = cls;
2694 char *tmpname; 2699 char *tmpname;
2695 2700
2696 if (GNUNET_OK != 2701 if (GNUNET_OK !=
2697 GNUNET_CONFIGURATION_get_value_filename (cfg, "PATHS", option, &tmpname)) 2702 GNUNET_CONFIGURATION_get_value_filename(cfg, "PATHS", option, &tmpname))
2698 { 2703 {
2699 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "PATHS", option); 2704 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "PATHS", option);
2700 return GNUNET_NO; 2705 return GNUNET_NO;
2701 } 2706 }
2702 if (GNUNET_SYSERR == GNUNET_DISK_directory_remove (tmpname)) 2707 if (GNUNET_SYSERR == GNUNET_DISK_directory_remove(tmpname))
2703 { 2708 {
2704 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "remove", tmpname); 2709 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "remove", tmpname);
2705 GNUNET_free (tmpname); 2710 GNUNET_free(tmpname);
2706 return GNUNET_OK; 2711 return GNUNET_OK;
2707 } 2712 }
2708 GNUNET_free (tmpname); 2713 GNUNET_free(tmpname);
2709 return GNUNET_OK; 2714 return GNUNET_OK;
2710} 2715}
2711 2716
@@ -2718,12 +2723,12 @@ purge_cfg_dir (void *cls, const struct GNUNET_CONFIGURATION_Handle *cfg)
2718 * @param option option with the dir name to purge 2723 * @param option option with the dir name to purge
2719 */ 2724 */
2720void 2725void
2721GNUNET_DISK_purge_cfg_dir (const char *cfg_filename, const char *option) 2726GNUNET_DISK_purge_cfg_dir(const char *cfg_filename, const char *option)
2722{ 2727{
2723 GNUNET_break (GNUNET_OK == 2728 GNUNET_break(GNUNET_OK ==
2724 GNUNET_CONFIGURATION_parse_and_run (cfg_filename, 2729 GNUNET_CONFIGURATION_parse_and_run(cfg_filename,
2725 &purge_cfg_dir, 2730 &purge_cfg_dir,
2726 (void *) option)); 2731 (void *)option));
2727} 2732}
2728 2733
2729 2734
diff --git a/src/util/disk.h b/src/util/disk.h
index aee028ade..c6014617c 100644
--- a/src/util/disk.h
+++ b/src/util/disk.h
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/disk.h 22 * @file util/disk.h
@@ -39,7 +39,7 @@
39 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 39 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
40 */ 40 */
41int 41int
42GNUNET_DISK_internal_file_handle_ (const struct GNUNET_DISK_FileHandle *fh, 42GNUNET_DISK_internal_file_handle_(const struct GNUNET_DISK_FileHandle *fh,
43 void *dst, size_t dst_len); 43 void *dst, size_t dst_len);
44 44
45#endif /* GNUNET_DISK_H_ */ 45#endif /* GNUNET_DISK_H_ */
diff --git a/src/util/dnsparser.c b/src/util/dnsparser.c
index ec10e3ec3..fcec0d4f1 100644
--- a/src/util/dnsparser.c
+++ b/src/util/dnsparser.c
@@ -53,22 +53,22 @@
53 * #GNUNET_SYSERR if the label is not valid for DNS names 53 * #GNUNET_SYSERR if the label is not valid for DNS names
54 */ 54 */
55int 55int
56GNUNET_DNSPARSER_check_label (const char *label) 56GNUNET_DNSPARSER_check_label(const char *label)
57{ 57{
58 char *output; 58 char *output;
59 size_t slen; 59 size_t slen;
60 60
61 if (NULL != strchr (label, '.')) 61 if (NULL != strchr(label, '.'))
62 return GNUNET_SYSERR; /* not a label! Did you mean GNUNET_DNSPARSER_check_name? */ 62 return GNUNET_SYSERR; /* not a label! Did you mean GNUNET_DNSPARSER_check_name? */
63 if (0 == strcmp (label, "@")) /* '@' is reserved for the empty label, see #GNUNET_GNS_EMPTY_LABEL_AT */ 63 if (0 == strcmp(label, "@")) /* '@' is reserved for the empty label, see #GNUNET_GNS_EMPTY_LABEL_AT */
64 return GNUNET_SYSERR; 64 return GNUNET_SYSERR;
65 if (IDNA_SUCCESS != idna_to_ascii_8z (label, &output, IDNA_ALLOW_UNASSIGNED)) 65 if (IDNA_SUCCESS != idna_to_ascii_8z(label, &output, IDNA_ALLOW_UNASSIGNED))
66 return GNUNET_SYSERR; 66 return GNUNET_SYSERR;
67 slen = strlen (output); 67 slen = strlen(output);
68#if WINDOWS 68#if WINDOWS
69 idn_free (output); 69 idn_free(output);
70#else 70#else
71 free (output); 71 free(output);
72#endif 72#endif
73 return (slen > 63) ? GNUNET_SYSERR : GNUNET_OK; 73 return (slen > 63) ? GNUNET_SYSERR : GNUNET_OK;
74} 74}
@@ -83,28 +83,28 @@ GNUNET_DNSPARSER_check_label (const char *label)
83 * #GNUNET_SYSERR if the label is not valid for DNS names 83 * #GNUNET_SYSERR if the label is not valid for DNS names
84 */ 84 */
85int 85int
86GNUNET_DNSPARSER_check_name (const char *name) 86GNUNET_DNSPARSER_check_name(const char *name)
87{ 87{
88 char *ldup; 88 char *ldup;
89 char *output; 89 char *output;
90 size_t slen; 90 size_t slen;
91 char *tok; 91 char *tok;
92 92
93 ldup = GNUNET_strdup (name); 93 ldup = GNUNET_strdup(name);
94 for (tok = strtok (ldup, "."); NULL != tok; tok = strtok (NULL, ".")) 94 for (tok = strtok(ldup, "."); NULL != tok; tok = strtok(NULL, "."))
95 if (GNUNET_OK != GNUNET_DNSPARSER_check_label (tok)) 95 if (GNUNET_OK != GNUNET_DNSPARSER_check_label(tok))
96 { 96 {
97 GNUNET_free (ldup); 97 GNUNET_free(ldup);
98 return GNUNET_SYSERR; 98 return GNUNET_SYSERR;
99 } 99 }
100 GNUNET_free (ldup); 100 GNUNET_free(ldup);
101 if (IDNA_SUCCESS != idna_to_ascii_8z (name, &output, IDNA_ALLOW_UNASSIGNED)) 101 if (IDNA_SUCCESS != idna_to_ascii_8z(name, &output, IDNA_ALLOW_UNASSIGNED))
102 return GNUNET_SYSERR; 102 return GNUNET_SYSERR;
103 slen = strlen (output); 103 slen = strlen(output);
104#if WINDOWS 104#if WINDOWS
105 idn_free (output); 105 idn_free(output);
106#else 106#else
107 free (output); 107 free(output);
108#endif 108#endif
109 return (slen > 253) ? GNUNET_SYSERR : GNUNET_OK; 109 return (slen > 253) ? GNUNET_SYSERR : GNUNET_OK;
110} 110}
@@ -116,13 +116,13 @@ GNUNET_DNSPARSER_check_name (const char *name)
116 * @param soa record to free 116 * @param soa record to free
117 */ 117 */
118void 118void
119GNUNET_DNSPARSER_free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa) 119GNUNET_DNSPARSER_free_soa(struct GNUNET_DNSPARSER_SoaRecord *soa)
120{ 120{
121 if (NULL == soa) 121 if (NULL == soa)
122 return; 122 return;
123 GNUNET_free_non_null (soa->mname); 123 GNUNET_free_non_null(soa->mname);
124 GNUNET_free_non_null (soa->rname); 124 GNUNET_free_non_null(soa->rname);
125 GNUNET_free (soa); 125 GNUNET_free(soa);
126} 126}
127 127
128 128
@@ -132,12 +132,12 @@ GNUNET_DNSPARSER_free_soa (struct GNUNET_DNSPARSER_SoaRecord *soa)
132 * @param cert record to free 132 * @param cert record to free
133 */ 133 */
134void 134void
135GNUNET_DNSPARSER_free_cert (struct GNUNET_DNSPARSER_CertRecord *cert) 135GNUNET_DNSPARSER_free_cert(struct GNUNET_DNSPARSER_CertRecord *cert)
136{ 136{
137 if (NULL == cert) 137 if (NULL == cert)
138 return; 138 return;
139 GNUNET_free_non_null (cert->certificate_data); 139 GNUNET_free_non_null(cert->certificate_data);
140 GNUNET_free (cert); 140 GNUNET_free(cert);
141} 141}
142 142
143 143
@@ -147,12 +147,12 @@ GNUNET_DNSPARSER_free_cert (struct GNUNET_DNSPARSER_CertRecord *cert)
147 * @param srv record to free 147 * @param srv record to free
148 */ 148 */
149void 149void
150GNUNET_DNSPARSER_free_srv (struct GNUNET_DNSPARSER_SrvRecord *srv) 150GNUNET_DNSPARSER_free_srv(struct GNUNET_DNSPARSER_SrvRecord *srv)
151{ 151{
152 if (NULL == srv) 152 if (NULL == srv)
153 return; 153 return;
154 GNUNET_free_non_null (srv->target); 154 GNUNET_free_non_null(srv->target);
155 GNUNET_free (srv); 155 GNUNET_free(srv);
156} 156}
157 157
158 158
@@ -162,12 +162,12 @@ GNUNET_DNSPARSER_free_srv (struct GNUNET_DNSPARSER_SrvRecord *srv)
162 * @param mx record to free 162 * @param mx record to free
163 */ 163 */
164void 164void
165GNUNET_DNSPARSER_free_mx (struct GNUNET_DNSPARSER_MxRecord *mx) 165GNUNET_DNSPARSER_free_mx(struct GNUNET_DNSPARSER_MxRecord *mx)
166{ 166{
167 if (NULL == mx) 167 if (NULL == mx)
168 return; 168 return;
169 GNUNET_free_non_null (mx->mxhost); 169 GNUNET_free_non_null(mx->mxhost);
170 GNUNET_free (mx); 170 GNUNET_free(mx);
171} 171}
172 172
173 173
@@ -177,32 +177,37 @@ GNUNET_DNSPARSER_free_mx (struct GNUNET_DNSPARSER_MxRecord *mx)
177 * @param r record to free 177 * @param r record to free
178 */ 178 */
179void 179void
180GNUNET_DNSPARSER_free_record (struct GNUNET_DNSPARSER_Record *r) 180GNUNET_DNSPARSER_free_record(struct GNUNET_DNSPARSER_Record *r)
181{ 181{
182 GNUNET_free_non_null (r->name); 182 GNUNET_free_non_null(r->name);
183 switch (r->type) 183 switch (r->type)
184 { 184 {
185 case GNUNET_DNSPARSER_TYPE_MX: 185 case GNUNET_DNSPARSER_TYPE_MX:
186 GNUNET_DNSPARSER_free_mx (r->data.mx); 186 GNUNET_DNSPARSER_free_mx(r->data.mx);
187 break; 187 break;
188 case GNUNET_DNSPARSER_TYPE_SOA: 188
189 GNUNET_DNSPARSER_free_soa (r->data.soa); 189 case GNUNET_DNSPARSER_TYPE_SOA:
190 break; 190 GNUNET_DNSPARSER_free_soa(r->data.soa);
191 case GNUNET_DNSPARSER_TYPE_SRV: 191 break;
192 GNUNET_DNSPARSER_free_srv (r->data.srv); 192
193 break; 193 case GNUNET_DNSPARSER_TYPE_SRV:
194 case GNUNET_DNSPARSER_TYPE_CERT: 194 GNUNET_DNSPARSER_free_srv(r->data.srv);
195 GNUNET_DNSPARSER_free_cert (r->data.cert); 195 break;
196 break; 196
197 case GNUNET_DNSPARSER_TYPE_NS: 197 case GNUNET_DNSPARSER_TYPE_CERT:
198 case GNUNET_DNSPARSER_TYPE_CNAME: 198 GNUNET_DNSPARSER_free_cert(r->data.cert);
199 case GNUNET_DNSPARSER_TYPE_PTR: 199 break;
200 GNUNET_free_non_null (r->data.hostname); 200
201 break; 201 case GNUNET_DNSPARSER_TYPE_NS:
202 default: 202 case GNUNET_DNSPARSER_TYPE_CNAME:
203 GNUNET_free_non_null (r->data.raw.data); 203 case GNUNET_DNSPARSER_TYPE_PTR:
204 break; 204 GNUNET_free_non_null(r->data.hostname);
205 } 205 break;
206
207 default:
208 GNUNET_free_non_null(r->data.raw.data);
209 break;
210 }
206} 211}
207 212
208 213
@@ -217,12 +222,12 @@ GNUNET_DNSPARSER_free_record (struct GNUNET_DNSPARSER_Record *r)
217 * @return name as 0-terminated C string on success, NULL if the payload is malformed 222 * @return name as 0-terminated C string on success, NULL if the payload is malformed
218 */ 223 */
219static char * 224static char *
220parse_name (const char *udp_payload, 225parse_name(const char *udp_payload,
221 size_t udp_payload_length, 226 size_t udp_payload_length,
222 size_t *off, 227 size_t *off,
223 unsigned int depth) 228 unsigned int depth)
224{ 229{
225 const uint8_t *input = (const uint8_t *) udp_payload; 230 const uint8_t *input = (const uint8_t *)udp_payload;
226 char *ret; 231 char *ret;
227 char *tmp; 232 char *tmp;
228 char *xstr; 233 char *xstr;
@@ -231,102 +236,102 @@ parse_name (const char *udp_payload,
231 char *utf8; 236 char *utf8;
232 Idna_rc rc; 237 Idna_rc rc;
233 238
234 ret = GNUNET_strdup (""); 239 ret = GNUNET_strdup("");
235 while (1) 240 while (1)
236 {
237 if (*off >= udp_payload_length)
238 {
239 GNUNET_break_op (0);
240 goto error;
241 }
242 len = input[*off];
243 if (0 == len)
244 {
245 (*off)++;
246 break;
247 }
248 if (len < 64)
249 { 241 {
250 if (*off + 1 + len > udp_payload_length) 242 if (*off >= udp_payload_length)
251 { 243 {
252 GNUNET_break_op (0); 244 GNUNET_break_op(0);
253 goto error; 245 goto error;
254 } 246 }
255 GNUNET_asprintf (&tmp, "%.*s", (int) len, &udp_payload[*off + 1]); 247 len = input[*off];
256 if (IDNA_SUCCESS != 248 if (0 == len)
257 (rc = idna_to_unicode_8z8z (tmp, &utf8, IDNA_ALLOW_UNASSIGNED))) 249 {
258 { 250 (*off)++;
259 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 251 break;
260 _ ("Failed to convert DNS IDNA name `%s' to UTF-8: %s\n"), 252 }
261 tmp, 253 if (len < 64)
262 idna_strerror (rc)); 254 {
263 GNUNET_free (tmp); 255 if (*off + 1 + len > udp_payload_length)
264 GNUNET_asprintf (&tmp, 256 {
265 "%s%.*s.", 257 GNUNET_break_op(0);
266 ret, 258 goto error;
267 (int) len, 259 }
268 &udp_payload[*off + 1]); 260 GNUNET_asprintf(&tmp, "%.*s", (int)len, &udp_payload[*off + 1]);
269 } 261 if (IDNA_SUCCESS !=
270 else 262 (rc = idna_to_unicode_8z8z(tmp, &utf8, IDNA_ALLOW_UNASSIGNED)))
271 { 263 {
272 GNUNET_free (tmp); 264 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
273 GNUNET_asprintf (&tmp, "%s%s.", ret, utf8); 265 _("Failed to convert DNS IDNA name `%s' to UTF-8: %s\n"),
266 tmp,
267 idna_strerror(rc));
268 GNUNET_free(tmp);
269 GNUNET_asprintf(&tmp,
270 "%s%.*s.",
271 ret,
272 (int)len,
273 &udp_payload[*off + 1]);
274 }
275 else
276 {
277 GNUNET_free(tmp);
278 GNUNET_asprintf(&tmp, "%s%s.", ret, utf8);
274#if WINDOWS 279#if WINDOWS
275 idn_free (utf8); 280 idn_free(utf8);
276#else 281#else
277 free (utf8); 282 free(utf8);
278#endif 283#endif
279 } 284 }
280 GNUNET_free (ret); 285 GNUNET_free(ret);
281 ret = tmp; 286 ret = tmp;
282 *off += 1 + len; 287 *off += 1 + len;
283 } 288 }
284 else if ((64 | 128) == (len & (64 | 128))) 289 else if ((64 | 128) == (len & (64 | 128)))
285 { 290 {
286 if (depth > 32) 291 if (depth > 32)
287 { 292 {
288 GNUNET_break_op (0); 293 GNUNET_break_op(0);
289 goto error; /* hard bound on stack to prevent "infinite" recursion, disallow! */ 294 goto error; /* hard bound on stack to prevent "infinite" recursion, disallow! */
290 } 295 }
291 /* pointer to string */ 296 /* pointer to string */
292 if (*off + 1 > udp_payload_length) 297 if (*off + 1 > udp_payload_length)
293 { 298 {
294 GNUNET_break_op (0); 299 GNUNET_break_op(0);
295 goto error; 300 goto error;
296 } 301 }
297 xoff = ((len - (64 | 128)) << 8) + input[*off + 1]; 302 xoff = ((len - (64 | 128)) << 8) + input[*off + 1];
298 xstr = parse_name (udp_payload, udp_payload_length, &xoff, depth + 1); 303 xstr = parse_name(udp_payload, udp_payload_length, &xoff, depth + 1);
299 if (NULL == xstr) 304 if (NULL == xstr)
300 { 305 {
301 GNUNET_break_op (0); 306 GNUNET_break_op(0);
302 goto error; 307 goto error;
303 } 308 }
304 GNUNET_asprintf (&tmp, "%s%s.", ret, xstr); 309 GNUNET_asprintf(&tmp, "%s%s.", ret, xstr);
305 GNUNET_free (ret); 310 GNUNET_free(ret);
306 GNUNET_free (xstr); 311 GNUNET_free(xstr);
307 ret = tmp; 312 ret = tmp;
308 if (strlen (ret) > udp_payload_length) 313 if (strlen(ret) > udp_payload_length)
309 { 314 {
310 GNUNET_break_op (0); 315 GNUNET_break_op(0);
311 goto error; /* we are looping (building an infinite string) */ 316 goto error; /* we are looping (building an infinite string) */
312 } 317 }
313 *off += 2; 318 *off += 2;
314 /* pointers always terminate names */ 319 /* pointers always terminate names */
315 break; 320 break;
316 } 321 }
317 else 322 else
318 { 323 {
319 /* neither pointer nor inline string, not supported... */ 324 /* neither pointer nor inline string, not supported... */
320 GNUNET_break_op (0); 325 GNUNET_break_op(0);
321 goto error; 326 goto error;
327 }
322 } 328 }
323 } 329 if (0 < strlen(ret))
324 if (0 < strlen (ret)) 330 ret[strlen(ret) - 1] = '\0'; /* eat tailing '.' */
325 ret[strlen (ret) - 1] = '\0'; /* eat tailing '.' */
326 return ret; 331 return ret;
327error: 332error:
328 GNUNET_break_op (0); 333 GNUNET_break_op(0);
329 GNUNET_free (ret); 334 GNUNET_free(ret);
330 return NULL; 335 return NULL;
331} 336}
332 337
@@ -341,11 +346,11 @@ error:
341 * @return name as 0-terminated C string on success, NULL if the payload is malformed 346 * @return name as 0-terminated C string on success, NULL if the payload is malformed
342 */ 347 */
343char * 348char *
344GNUNET_DNSPARSER_parse_name (const char *udp_payload, 349GNUNET_DNSPARSER_parse_name(const char *udp_payload,
345 size_t udp_payload_length, 350 size_t udp_payload_length,
346 size_t *off) 351 size_t *off)
347{ 352{
348 return parse_name (udp_payload, udp_payload_length, off, 0); 353 return parse_name(udp_payload, udp_payload_length, off, 0);
349} 354}
350 355
351 356
@@ -360,30 +365,30 @@ GNUNET_DNSPARSER_parse_name (const char *udp_payload,
360 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the query is malformed 365 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the query is malformed
361 */ 366 */
362int 367int
363GNUNET_DNSPARSER_parse_query (const char *udp_payload, 368GNUNET_DNSPARSER_parse_query(const char *udp_payload,
364 size_t udp_payload_length, 369 size_t udp_payload_length,
365 size_t *off, 370 size_t *off,
366 struct GNUNET_DNSPARSER_Query *q) 371 struct GNUNET_DNSPARSER_Query *q)
367{ 372{
368 char *name; 373 char *name;
369 struct GNUNET_TUN_DnsQueryLine ql; 374 struct GNUNET_TUN_DnsQueryLine ql;
370 375
371 name = GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 376 name = GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
372 if (NULL == name) 377 if (NULL == name)
373 { 378 {
374 GNUNET_break_op (0); 379 GNUNET_break_op(0);
375 return GNUNET_SYSERR; 380 return GNUNET_SYSERR;
376 } 381 }
377 q->name = name; 382 q->name = name;
378 if (*off + sizeof (struct GNUNET_TUN_DnsQueryLine) > udp_payload_length) 383 if (*off + sizeof(struct GNUNET_TUN_DnsQueryLine) > udp_payload_length)
379 { 384 {
380 GNUNET_break_op (0); 385 GNUNET_break_op(0);
381 return GNUNET_SYSERR; 386 return GNUNET_SYSERR;
382 } 387 }
383 GNUNET_memcpy (&ql, &udp_payload[*off], sizeof (ql)); 388 GNUNET_memcpy(&ql, &udp_payload[*off], sizeof(ql));
384 *off += sizeof (ql); 389 *off += sizeof(ql);
385 q->type = ntohs (ql.type); 390 q->type = ntohs(ql.type);
386 q->dns_traffic_class = ntohs (ql.dns_traffic_class); 391 q->dns_traffic_class = ntohs(ql.dns_traffic_class);
387 return GNUNET_OK; 392 return GNUNET_OK;
388} 393}
389 394
@@ -398,37 +403,37 @@ GNUNET_DNSPARSER_parse_query (const char *udp_payload,
398 * @return the parsed SOA record, NULL on error 403 * @return the parsed SOA record, NULL on error
399 */ 404 */
400struct GNUNET_DNSPARSER_SoaRecord * 405struct GNUNET_DNSPARSER_SoaRecord *
401GNUNET_DNSPARSER_parse_soa (const char *udp_payload, 406GNUNET_DNSPARSER_parse_soa(const char *udp_payload,
402 size_t udp_payload_length, 407 size_t udp_payload_length,
403 size_t *off) 408 size_t *off)
404{ 409{
405 struct GNUNET_DNSPARSER_SoaRecord *soa; 410 struct GNUNET_DNSPARSER_SoaRecord *soa;
406 struct GNUNET_TUN_DnsSoaRecord soa_bin; 411 struct GNUNET_TUN_DnsSoaRecord soa_bin;
407 size_t old_off; 412 size_t old_off;
408 413
409 old_off = *off; 414 old_off = *off;
410 soa = GNUNET_new (struct GNUNET_DNSPARSER_SoaRecord); 415 soa = GNUNET_new(struct GNUNET_DNSPARSER_SoaRecord);
411 soa->mname = 416 soa->mname =
412 GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 417 GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
413 soa->rname = 418 soa->rname =
414 GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 419 GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
415 if ((NULL == soa->mname) || (NULL == soa->rname) || 420 if ((NULL == soa->mname) || (NULL == soa->rname) ||
416 (*off + sizeof (struct GNUNET_TUN_DnsSoaRecord) > udp_payload_length)) 421 (*off + sizeof(struct GNUNET_TUN_DnsSoaRecord) > udp_payload_length))
417 { 422 {
418 GNUNET_break_op (0); 423 GNUNET_break_op(0);
419 GNUNET_DNSPARSER_free_soa (soa); 424 GNUNET_DNSPARSER_free_soa(soa);
420 *off = old_off; 425 *off = old_off;
421 return NULL; 426 return NULL;
422 } 427 }
423 GNUNET_memcpy (&soa_bin, 428 GNUNET_memcpy(&soa_bin,
424 &udp_payload[*off], 429 &udp_payload[*off],
425 sizeof (struct GNUNET_TUN_DnsSoaRecord)); 430 sizeof(struct GNUNET_TUN_DnsSoaRecord));
426 soa->serial = ntohl (soa_bin.serial); 431 soa->serial = ntohl(soa_bin.serial);
427 soa->refresh = ntohl (soa_bin.refresh); 432 soa->refresh = ntohl(soa_bin.refresh);
428 soa->retry = ntohl (soa_bin.retry); 433 soa->retry = ntohl(soa_bin.retry);
429 soa->expire = ntohl (soa_bin.expire); 434 soa->expire = ntohl(soa_bin.expire);
430 soa->minimum_ttl = ntohl (soa_bin.minimum); 435 soa->minimum_ttl = ntohl(soa_bin.minimum);
431 (*off) += sizeof (struct GNUNET_TUN_DnsSoaRecord); 436 (*off) += sizeof(struct GNUNET_TUN_DnsSoaRecord);
432 return soa; 437 return soa;
433} 438}
434 439
@@ -443,33 +448,33 @@ GNUNET_DNSPARSER_parse_soa (const char *udp_payload,
443 * @return the parsed MX record, NULL on error 448 * @return the parsed MX record, NULL on error
444 */ 449 */
445struct GNUNET_DNSPARSER_MxRecord * 450struct GNUNET_DNSPARSER_MxRecord *
446GNUNET_DNSPARSER_parse_mx (const char *udp_payload, 451GNUNET_DNSPARSER_parse_mx(const char *udp_payload,
447 size_t udp_payload_length, 452 size_t udp_payload_length,
448 size_t *off) 453 size_t *off)
449{ 454{
450 struct GNUNET_DNSPARSER_MxRecord *mx; 455 struct GNUNET_DNSPARSER_MxRecord *mx;
451 uint16_t mxpref; 456 uint16_t mxpref;
452 size_t old_off; 457 size_t old_off;
453 458
454 old_off = *off; 459 old_off = *off;
455 if (*off + sizeof (uint16_t) > udp_payload_length) 460 if (*off + sizeof(uint16_t) > udp_payload_length)
456 { 461 {
457 GNUNET_break_op (0); 462 GNUNET_break_op(0);
458 return NULL; 463 return NULL;
459 } 464 }
460 GNUNET_memcpy (&mxpref, &udp_payload[*off], sizeof (uint16_t)); 465 GNUNET_memcpy(&mxpref, &udp_payload[*off], sizeof(uint16_t));
461 (*off) += sizeof (uint16_t); 466 (*off) += sizeof(uint16_t);
462 mx = GNUNET_new (struct GNUNET_DNSPARSER_MxRecord); 467 mx = GNUNET_new(struct GNUNET_DNSPARSER_MxRecord);
463 mx->preference = ntohs (mxpref); 468 mx->preference = ntohs(mxpref);
464 mx->mxhost = 469 mx->mxhost =
465 GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 470 GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
466 if (NULL == mx->mxhost) 471 if (NULL == mx->mxhost)
467 { 472 {
468 GNUNET_break_op (0); 473 GNUNET_break_op(0);
469 GNUNET_DNSPARSER_free_mx (mx); 474 GNUNET_DNSPARSER_free_mx(mx);
470 *off = old_off; 475 *off = old_off;
471 return NULL; 476 return NULL;
472 } 477 }
473 return mx; 478 return mx;
474} 479}
475 480
@@ -484,33 +489,33 @@ GNUNET_DNSPARSER_parse_mx (const char *udp_payload,
484 * @return the parsed SRV record, NULL on error 489 * @return the parsed SRV record, NULL on error
485 */ 490 */
486struct GNUNET_DNSPARSER_SrvRecord * 491struct GNUNET_DNSPARSER_SrvRecord *
487GNUNET_DNSPARSER_parse_srv (const char *udp_payload, 492GNUNET_DNSPARSER_parse_srv(const char *udp_payload,
488 size_t udp_payload_length, 493 size_t udp_payload_length,
489 size_t *off) 494 size_t *off)
490{ 495{
491 struct GNUNET_DNSPARSER_SrvRecord *srv; 496 struct GNUNET_DNSPARSER_SrvRecord *srv;
492 struct GNUNET_TUN_DnsSrvRecord srv_bin; 497 struct GNUNET_TUN_DnsSrvRecord srv_bin;
493 size_t old_off; 498 size_t old_off;
494 499
495 old_off = *off; 500 old_off = *off;
496 if (*off + sizeof (struct GNUNET_TUN_DnsSrvRecord) > udp_payload_length) 501 if (*off + sizeof(struct GNUNET_TUN_DnsSrvRecord) > udp_payload_length)
497 return NULL; 502 return NULL;
498 GNUNET_memcpy (&srv_bin, 503 GNUNET_memcpy(&srv_bin,
499 &udp_payload[*off], 504 &udp_payload[*off],
500 sizeof (struct GNUNET_TUN_DnsSrvRecord)); 505 sizeof(struct GNUNET_TUN_DnsSrvRecord));
501 (*off) += sizeof (struct GNUNET_TUN_DnsSrvRecord); 506 (*off) += sizeof(struct GNUNET_TUN_DnsSrvRecord);
502 srv = GNUNET_new (struct GNUNET_DNSPARSER_SrvRecord); 507 srv = GNUNET_new(struct GNUNET_DNSPARSER_SrvRecord);
503 srv->priority = ntohs (srv_bin.prio); 508 srv->priority = ntohs(srv_bin.prio);
504 srv->weight = ntohs (srv_bin.weight); 509 srv->weight = ntohs(srv_bin.weight);
505 srv->port = ntohs (srv_bin.port); 510 srv->port = ntohs(srv_bin.port);
506 srv->target = 511 srv->target =
507 GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 512 GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
508 if (NULL == srv->target) 513 if (NULL == srv->target)
509 { 514 {
510 GNUNET_DNSPARSER_free_srv (srv); 515 GNUNET_DNSPARSER_free_srv(srv);
511 *off = old_off; 516 *off = old_off;
512 return NULL; 517 return NULL;
513 } 518 }
514 return srv; 519 return srv;
515} 520}
516 521
@@ -525,31 +530,31 @@ GNUNET_DNSPARSER_parse_srv (const char *udp_payload,
525 * @return the parsed CERT record, NULL on error 530 * @return the parsed CERT record, NULL on error
526 */ 531 */
527struct GNUNET_DNSPARSER_CertRecord * 532struct GNUNET_DNSPARSER_CertRecord *
528GNUNET_DNSPARSER_parse_cert (const char *udp_payload, 533GNUNET_DNSPARSER_parse_cert(const char *udp_payload,
529 size_t udp_payload_length, 534 size_t udp_payload_length,
530 size_t *off) 535 size_t *off)
531{ 536{
532 struct GNUNET_DNSPARSER_CertRecord *cert; 537 struct GNUNET_DNSPARSER_CertRecord *cert;
533 struct GNUNET_TUN_DnsCertRecord dcert; 538 struct GNUNET_TUN_DnsCertRecord dcert;
534 539
535 if (*off + sizeof (struct GNUNET_TUN_DnsCertRecord) >= udp_payload_length) 540 if (*off + sizeof(struct GNUNET_TUN_DnsCertRecord) >= udp_payload_length)
536 { 541 {
537 GNUNET_break_op (0); 542 GNUNET_break_op(0);
538 return NULL; 543 return NULL;
539 } 544 }
540 GNUNET_memcpy (&dcert, 545 GNUNET_memcpy(&dcert,
541 &udp_payload[*off], 546 &udp_payload[*off],
542 sizeof (struct GNUNET_TUN_DnsCertRecord)); 547 sizeof(struct GNUNET_TUN_DnsCertRecord));
543 (*off) += sizeof (struct GNUNET_TUN_DnsCertRecord); 548 (*off) += sizeof(struct GNUNET_TUN_DnsCertRecord);
544 cert = GNUNET_new (struct GNUNET_DNSPARSER_CertRecord); 549 cert = GNUNET_new(struct GNUNET_DNSPARSER_CertRecord);
545 cert->cert_type = ntohs (dcert.cert_type); 550 cert->cert_type = ntohs(dcert.cert_type);
546 cert->cert_tag = ntohs (dcert.cert_tag); 551 cert->cert_tag = ntohs(dcert.cert_tag);
547 cert->algorithm = dcert.algorithm; 552 cert->algorithm = dcert.algorithm;
548 cert->certificate_size = udp_payload_length - (*off); 553 cert->certificate_size = udp_payload_length - (*off);
549 cert->certificate_data = GNUNET_malloc (cert->certificate_size); 554 cert->certificate_data = GNUNET_malloc(cert->certificate_size);
550 GNUNET_memcpy (cert->certificate_data, 555 GNUNET_memcpy(cert->certificate_data,
551 &udp_payload[*off], 556 &udp_payload[*off],
552 cert->certificate_size); 557 cert->certificate_size);
553 (*off) += cert->certificate_size; 558 (*off) += cert->certificate_size;
554 return cert; 559 return cert;
555} 560}
@@ -566,85 +571,89 @@ GNUNET_DNSPARSER_parse_cert (const char *udp_payload,
566 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the record is malformed 571 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the record is malformed
567 */ 572 */
568int 573int
569GNUNET_DNSPARSER_parse_record (const char *udp_payload, 574GNUNET_DNSPARSER_parse_record(const char *udp_payload,
570 size_t udp_payload_length, 575 size_t udp_payload_length,
571 size_t *off, 576 size_t *off,
572 struct GNUNET_DNSPARSER_Record *r) 577 struct GNUNET_DNSPARSER_Record *r)
573{ 578{
574 char *name; 579 char *name;
575 struct GNUNET_TUN_DnsRecordLine rl; 580 struct GNUNET_TUN_DnsRecordLine rl;
576 size_t old_off; 581 size_t old_off;
577 uint16_t data_len; 582 uint16_t data_len;
578 583
579 name = GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off); 584 name = GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
580 if (NULL == name) 585 if (NULL == name)
581 {
582 GNUNET_break_op (0);
583 return GNUNET_SYSERR;
584 }
585 r->name = name;
586 if (*off + sizeof (struct GNUNET_TUN_DnsRecordLine) > udp_payload_length)
587 {
588 GNUNET_break_op (0);
589 return GNUNET_SYSERR;
590 }
591 GNUNET_memcpy (&rl, &udp_payload[*off], sizeof (rl));
592 (*off) += sizeof (rl);
593 r->type = ntohs (rl.type);
594 r->dns_traffic_class = ntohs (rl.dns_traffic_class);
595 r->expiration_time = GNUNET_TIME_relative_to_absolute (
596 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, ntohl (rl.ttl)));
597 data_len = ntohs (rl.data_len);
598 if (*off + data_len > udp_payload_length)
599 {
600 GNUNET_break_op (0);
601 return GNUNET_SYSERR;
602 }
603 old_off = *off;
604 switch (r->type)
605 {
606 case GNUNET_DNSPARSER_TYPE_NS:
607 case GNUNET_DNSPARSER_TYPE_CNAME:
608 case GNUNET_DNSPARSER_TYPE_DNAME:
609 case GNUNET_DNSPARSER_TYPE_PTR:
610 r->data.hostname =
611 GNUNET_DNSPARSER_parse_name (udp_payload, udp_payload_length, off);
612 if ((NULL == r->data.hostname) || (old_off + data_len != *off))
613 return GNUNET_SYSERR;
614 return GNUNET_OK;
615 case GNUNET_DNSPARSER_TYPE_SOA:
616 r->data.soa =
617 GNUNET_DNSPARSER_parse_soa (udp_payload, udp_payload_length, off);
618 if ((NULL == r->data.soa) || (old_off + data_len != *off))
619 { 586 {
620 GNUNET_break_op (0); 587 GNUNET_break_op(0);
621 return GNUNET_SYSERR; 588 return GNUNET_SYSERR;
622 } 589 }
623 return GNUNET_OK; 590 r->name = name;
624 case GNUNET_DNSPARSER_TYPE_MX: 591 if (*off + sizeof(struct GNUNET_TUN_DnsRecordLine) > udp_payload_length)
625 r->data.mx =
626 GNUNET_DNSPARSER_parse_mx (udp_payload, udp_payload_length, off);
627 if ((NULL == r->data.mx) || (old_off + data_len != *off))
628 { 592 {
629 GNUNET_break_op (0); 593 GNUNET_break_op(0);
630 return GNUNET_SYSERR; 594 return GNUNET_SYSERR;
631 } 595 }
632 return GNUNET_OK; 596 GNUNET_memcpy(&rl, &udp_payload[*off], sizeof(rl));
633 case GNUNET_DNSPARSER_TYPE_SRV: 597 (*off) += sizeof(rl);
634 r->data.srv = 598 r->type = ntohs(rl.type);
635 GNUNET_DNSPARSER_parse_srv (udp_payload, udp_payload_length, off); 599 r->dns_traffic_class = ntohs(rl.dns_traffic_class);
636 if ((NULL == r->data.srv) || (old_off + data_len != *off)) 600 r->expiration_time = GNUNET_TIME_relative_to_absolute(
601 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, ntohl(rl.ttl)));
602 data_len = ntohs(rl.data_len);
603 if (*off + data_len > udp_payload_length)
637 { 604 {
638 GNUNET_break_op (0); 605 GNUNET_break_op(0);
639 return GNUNET_SYSERR; 606 return GNUNET_SYSERR;
640 } 607 }
641 return GNUNET_OK; 608 old_off = *off;
642 default: 609 switch (r->type)
643 r->data.raw.data = GNUNET_malloc (data_len); 610 {
644 r->data.raw.data_len = data_len; 611 case GNUNET_DNSPARSER_TYPE_NS:
645 GNUNET_memcpy (r->data.raw.data, &udp_payload[*off], data_len); 612 case GNUNET_DNSPARSER_TYPE_CNAME:
646 break; 613 case GNUNET_DNSPARSER_TYPE_DNAME:
647 } 614 case GNUNET_DNSPARSER_TYPE_PTR:
615 r->data.hostname =
616 GNUNET_DNSPARSER_parse_name(udp_payload, udp_payload_length, off);
617 if ((NULL == r->data.hostname) || (old_off + data_len != *off))
618 return GNUNET_SYSERR;
619 return GNUNET_OK;
620
621 case GNUNET_DNSPARSER_TYPE_SOA:
622 r->data.soa =
623 GNUNET_DNSPARSER_parse_soa(udp_payload, udp_payload_length, off);
624 if ((NULL == r->data.soa) || (old_off + data_len != *off))
625 {
626 GNUNET_break_op(0);
627 return GNUNET_SYSERR;
628 }
629 return GNUNET_OK;
630
631 case GNUNET_DNSPARSER_TYPE_MX:
632 r->data.mx =
633 GNUNET_DNSPARSER_parse_mx(udp_payload, udp_payload_length, off);
634 if ((NULL == r->data.mx) || (old_off + data_len != *off))
635 {
636 GNUNET_break_op(0);
637 return GNUNET_SYSERR;
638 }
639 return GNUNET_OK;
640
641 case GNUNET_DNSPARSER_TYPE_SRV:
642 r->data.srv =
643 GNUNET_DNSPARSER_parse_srv(udp_payload, udp_payload_length, off);
644 if ((NULL == r->data.srv) || (old_off + data_len != *off))
645 {
646 GNUNET_break_op(0);
647 return GNUNET_SYSERR;
648 }
649 return GNUNET_OK;
650
651 default:
652 r->data.raw.data = GNUNET_malloc(data_len);
653 r->data.raw.data_len = data_len;
654 GNUNET_memcpy(r->data.raw.data, &udp_payload[*off], data_len);
655 break;
656 }
648 (*off) += data_len; 657 (*off) += data_len;
649 return GNUNET_OK; 658 return GNUNET_OK;
650} 659}
@@ -659,76 +668,76 @@ GNUNET_DNSPARSER_parse_record (const char *udp_payload,
659 * @return NULL on error, otherwise the parsed packet 668 * @return NULL on error, otherwise the parsed packet
660 */ 669 */
661struct GNUNET_DNSPARSER_Packet * 670struct GNUNET_DNSPARSER_Packet *
662GNUNET_DNSPARSER_parse (const char *udp_payload, size_t udp_payload_length) 671GNUNET_DNSPARSER_parse(const char *udp_payload, size_t udp_payload_length)
663{ 672{
664 struct GNUNET_DNSPARSER_Packet *p; 673 struct GNUNET_DNSPARSER_Packet *p;
665 const struct GNUNET_TUN_DnsHeader *dns; 674 const struct GNUNET_TUN_DnsHeader *dns;
666 size_t off; 675 size_t off;
667 unsigned int n; 676 unsigned int n;
668 677
669 if (udp_payload_length < sizeof (struct GNUNET_TUN_DnsHeader)) 678 if (udp_payload_length < sizeof(struct GNUNET_TUN_DnsHeader))
670 return NULL; 679 return NULL;
671 dns = (const struct GNUNET_TUN_DnsHeader *) udp_payload; 680 dns = (const struct GNUNET_TUN_DnsHeader *)udp_payload;
672 off = sizeof (struct GNUNET_TUN_DnsHeader); 681 off = sizeof(struct GNUNET_TUN_DnsHeader);
673 p = GNUNET_new (struct GNUNET_DNSPARSER_Packet); 682 p = GNUNET_new(struct GNUNET_DNSPARSER_Packet);
674 p->flags = dns->flags; 683 p->flags = dns->flags;
675 p->id = dns->id; 684 p->id = dns->id;
676 n = ntohs (dns->query_count); 685 n = ntohs(dns->query_count);
677 if (n > 0) 686 if (n > 0)
678 { 687 {
679 p->queries = GNUNET_new_array (n, struct GNUNET_DNSPARSER_Query); 688 p->queries = GNUNET_new_array(n, struct GNUNET_DNSPARSER_Query);
680 p->num_queries = n; 689 p->num_queries = n;
681 for (unsigned int i = 0; i < n; i++) 690 for (unsigned int i = 0; i < n; i++)
682 if (GNUNET_OK != GNUNET_DNSPARSER_parse_query (udp_payload, 691 if (GNUNET_OK != GNUNET_DNSPARSER_parse_query(udp_payload,
683 udp_payload_length,
684 &off,
685 &p->queries[i]))
686 goto error;
687 }
688 n = ntohs (dns->answer_rcount);
689 if (n > 0)
690 {
691 p->answers = GNUNET_new_array (n, struct GNUNET_DNSPARSER_Record);
692 p->num_answers = n;
693 for (unsigned int i = 0; i < n; i++)
694 if (GNUNET_OK != GNUNET_DNSPARSER_parse_record (udp_payload,
695 udp_payload_length, 692 udp_payload_length,
696 &off, 693 &off,
697 &p->answers[i])) 694 &p->queries[i]))
698 goto error; 695 goto error;
699 } 696 }
700 n = ntohs (dns->authority_rcount); 697 n = ntohs(dns->answer_rcount);
701 if (n > 0) 698 if (n > 0)
702 { 699 {
703 p->authority_records = GNUNET_new_array (n, struct GNUNET_DNSPARSER_Record); 700 p->answers = GNUNET_new_array(n, struct GNUNET_DNSPARSER_Record);
704 p->num_authority_records = n; 701 p->num_answers = n;
705 for (unsigned int i = 0; i < n; i++) 702 for (unsigned int i = 0; i < n; i++)
706 if (GNUNET_OK != GNUNET_DNSPARSER_parse_record (udp_payload, 703 if (GNUNET_OK != GNUNET_DNSPARSER_parse_record(udp_payload,
707 udp_payload_length, 704 udp_payload_length,
708 &off, 705 &off,
709 &p->authority_records[i])) 706 &p->answers[i]))
710 goto error; 707 goto error;
711 } 708 }
712 n = ntohs (dns->additional_rcount); 709 n = ntohs(dns->authority_rcount);
713 if (n > 0) 710 if (n > 0)
714 {
715 p->additional_records =
716 GNUNET_new_array (n, struct GNUNET_DNSPARSER_Record);
717 p->num_additional_records = n;
718 for (unsigned int i = 0; i < n; i++)
719 { 711 {
720 if (GNUNET_OK != 712 p->authority_records = GNUNET_new_array(n, struct GNUNET_DNSPARSER_Record);
721 GNUNET_DNSPARSER_parse_record (udp_payload, 713 p->num_authority_records = n;
722 udp_payload_length, 714 for (unsigned int i = 0; i < n; i++)
723 &off, 715 if (GNUNET_OK != GNUNET_DNSPARSER_parse_record(udp_payload,
724 &p->additional_records[i])) 716 udp_payload_length,
725 goto error; 717 &off,
718 &p->authority_records[i]))
719 goto error;
720 }
721 n = ntohs(dns->additional_rcount);
722 if (n > 0)
723 {
724 p->additional_records =
725 GNUNET_new_array(n, struct GNUNET_DNSPARSER_Record);
726 p->num_additional_records = n;
727 for (unsigned int i = 0; i < n; i++)
728 {
729 if (GNUNET_OK !=
730 GNUNET_DNSPARSER_parse_record(udp_payload,
731 udp_payload_length,
732 &off,
733 &p->additional_records[i]))
734 goto error;
735 }
726 } 736 }
727 }
728 return p; 737 return p;
729error: 738error:
730 GNUNET_break_op (0); 739 GNUNET_break_op(0);
731 GNUNET_DNSPARSER_free_packet (p); 740 GNUNET_DNSPARSER_free_packet(p);
732 return NULL; 741 return NULL;
733} 742}
734 743
@@ -740,39 +749,44 @@ error:
740 * @return the newly allocated record 749 * @return the newly allocated record
741 */ 750 */
742struct GNUNET_DNSPARSER_Record * 751struct GNUNET_DNSPARSER_Record *
743GNUNET_DNSPARSER_duplicate_record (const struct GNUNET_DNSPARSER_Record *r) 752GNUNET_DNSPARSER_duplicate_record(const struct GNUNET_DNSPARSER_Record *r)
744{ 753{
745 struct GNUNET_DNSPARSER_Record *dup = GNUNET_memdup (r, sizeof (*r)); 754 struct GNUNET_DNSPARSER_Record *dup = GNUNET_memdup(r, sizeof(*r));
746 755
747 dup->name = GNUNET_strdup (r->name); 756 dup->name = GNUNET_strdup(r->name);
748 switch (r->type) 757 switch (r->type)
749 { 758 {
750 case GNUNET_DNSPARSER_TYPE_NS: 759 case GNUNET_DNSPARSER_TYPE_NS:
751 case GNUNET_DNSPARSER_TYPE_CNAME: 760 case GNUNET_DNSPARSER_TYPE_CNAME:
752 case GNUNET_DNSPARSER_TYPE_PTR: { 761 case GNUNET_DNSPARSER_TYPE_PTR: {
753 dup->data.hostname = GNUNET_strdup (r->data.hostname); 762 dup->data.hostname = GNUNET_strdup(r->data.hostname);
754 break; 763 break;
755 } 764 }
756 case GNUNET_DNSPARSER_TYPE_SOA: { 765
757 dup->data.soa = GNUNET_DNSPARSER_duplicate_soa_record (r->data.soa); 766 case GNUNET_DNSPARSER_TYPE_SOA: {
758 break; 767 dup->data.soa = GNUNET_DNSPARSER_duplicate_soa_record(r->data.soa);
759 } 768 break;
760 case GNUNET_DNSPARSER_TYPE_CERT: { 769 }
761 dup->data.cert = GNUNET_DNSPARSER_duplicate_cert_record (r->data.cert); 770
762 break; 771 case GNUNET_DNSPARSER_TYPE_CERT: {
763 } 772 dup->data.cert = GNUNET_DNSPARSER_duplicate_cert_record(r->data.cert);
764 case GNUNET_DNSPARSER_TYPE_MX: { 773 break;
765 dup->data.mx = GNUNET_DNSPARSER_duplicate_mx_record (r->data.mx); 774 }
766 break; 775
767 } 776 case GNUNET_DNSPARSER_TYPE_MX: {
768 case GNUNET_DNSPARSER_TYPE_SRV: { 777 dup->data.mx = GNUNET_DNSPARSER_duplicate_mx_record(r->data.mx);
769 dup->data.srv = GNUNET_DNSPARSER_duplicate_srv_record (r->data.srv); 778 break;
770 break; 779 }
771 } 780
772 default: { 781 case GNUNET_DNSPARSER_TYPE_SRV: {
773 dup->data.raw.data = GNUNET_memdup (r->data.raw.data, r->data.raw.data_len); 782 dup->data.srv = GNUNET_DNSPARSER_duplicate_srv_record(r->data.srv);
774 } 783 break;
775 } 784 }
785
786 default: {
787 dup->data.raw.data = GNUNET_memdup(r->data.raw.data, r->data.raw.data_len);
788 }
789 }
776 return dup; 790 return dup;
777} 791}
778 792
@@ -784,13 +798,13 @@ GNUNET_DNSPARSER_duplicate_record (const struct GNUNET_DNSPARSER_Record *r)
784 * @return the newly allocated record 798 * @return the newly allocated record
785 */ 799 */
786struct GNUNET_DNSPARSER_SoaRecord * 800struct GNUNET_DNSPARSER_SoaRecord *
787GNUNET_DNSPARSER_duplicate_soa_record ( 801GNUNET_DNSPARSER_duplicate_soa_record(
788 const struct GNUNET_DNSPARSER_SoaRecord *r) 802 const struct GNUNET_DNSPARSER_SoaRecord *r)
789{ 803{
790 struct GNUNET_DNSPARSER_SoaRecord *dup = GNUNET_memdup (r, sizeof (*r)); 804 struct GNUNET_DNSPARSER_SoaRecord *dup = GNUNET_memdup(r, sizeof(*r));
791 805
792 dup->mname = GNUNET_strdup (r->mname); 806 dup->mname = GNUNET_strdup(r->mname);
793 dup->rname = GNUNET_strdup (r->rname); 807 dup->rname = GNUNET_strdup(r->rname);
794 return dup; 808 return dup;
795} 809}
796 810
@@ -802,12 +816,12 @@ GNUNET_DNSPARSER_duplicate_soa_record (
802 * @return the newly allocated record 816 * @return the newly allocated record
803 */ 817 */
804struct GNUNET_DNSPARSER_CertRecord * 818struct GNUNET_DNSPARSER_CertRecord *
805GNUNET_DNSPARSER_duplicate_cert_record ( 819GNUNET_DNSPARSER_duplicate_cert_record(
806 const struct GNUNET_DNSPARSER_CertRecord *r) 820 const struct GNUNET_DNSPARSER_CertRecord *r)
807{ 821{
808 struct GNUNET_DNSPARSER_CertRecord *dup = GNUNET_memdup (r, sizeof (*r)); 822 struct GNUNET_DNSPARSER_CertRecord *dup = GNUNET_memdup(r, sizeof(*r));
809 823
810 dup->certificate_data = GNUNET_strdup (r->certificate_data); 824 dup->certificate_data = GNUNET_strdup(r->certificate_data);
811 return dup; 825 return dup;
812} 826}
813 827
@@ -819,11 +833,11 @@ GNUNET_DNSPARSER_duplicate_cert_record (
819 * @return the newly allocated record 833 * @return the newly allocated record
820 */ 834 */
821struct GNUNET_DNSPARSER_MxRecord * 835struct GNUNET_DNSPARSER_MxRecord *
822GNUNET_DNSPARSER_duplicate_mx_record (const struct GNUNET_DNSPARSER_MxRecord *r) 836GNUNET_DNSPARSER_duplicate_mx_record(const struct GNUNET_DNSPARSER_MxRecord *r)
823{ 837{
824 struct GNUNET_DNSPARSER_MxRecord *dup = GNUNET_memdup (r, sizeof (*r)); 838 struct GNUNET_DNSPARSER_MxRecord *dup = GNUNET_memdup(r, sizeof(*r));
825 839
826 dup->mxhost = GNUNET_strdup (r->mxhost); 840 dup->mxhost = GNUNET_strdup(r->mxhost);
827 return dup; 841 return dup;
828} 842}
829 843
@@ -835,12 +849,12 @@ GNUNET_DNSPARSER_duplicate_mx_record (const struct GNUNET_DNSPARSER_MxRecord *r)
835 * @return the newly allocated record 849 * @return the newly allocated record
836 */ 850 */
837struct GNUNET_DNSPARSER_SrvRecord * 851struct GNUNET_DNSPARSER_SrvRecord *
838GNUNET_DNSPARSER_duplicate_srv_record ( 852GNUNET_DNSPARSER_duplicate_srv_record(
839 const struct GNUNET_DNSPARSER_SrvRecord *r) 853 const struct GNUNET_DNSPARSER_SrvRecord *r)
840{ 854{
841 struct GNUNET_DNSPARSER_SrvRecord *dup = GNUNET_memdup (r, sizeof (*r)); 855 struct GNUNET_DNSPARSER_SrvRecord *dup = GNUNET_memdup(r, sizeof(*r));
842 856
843 dup->target = GNUNET_strdup (r->target); 857 dup->target = GNUNET_strdup(r->target);
844 return dup; 858 return dup;
845} 859}
846 860
@@ -851,21 +865,21 @@ GNUNET_DNSPARSER_duplicate_srv_record (
851 * @param p packet to free 865 * @param p packet to free
852 */ 866 */
853void 867void
854GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p) 868GNUNET_DNSPARSER_free_packet(struct GNUNET_DNSPARSER_Packet *p)
855{ 869{
856 for (unsigned int i = 0; i < p->num_queries; i++) 870 for (unsigned int i = 0; i < p->num_queries; i++)
857 GNUNET_free_non_null (p->queries[i].name); 871 GNUNET_free_non_null(p->queries[i].name);
858 GNUNET_free_non_null (p->queries); 872 GNUNET_free_non_null(p->queries);
859 for (unsigned int i = 0; i < p->num_answers; i++) 873 for (unsigned int i = 0; i < p->num_answers; i++)
860 GNUNET_DNSPARSER_free_record (&p->answers[i]); 874 GNUNET_DNSPARSER_free_record(&p->answers[i]);
861 GNUNET_free_non_null (p->answers); 875 GNUNET_free_non_null(p->answers);
862 for (unsigned int i = 0; i < p->num_authority_records; i++) 876 for (unsigned int i = 0; i < p->num_authority_records; i++)
863 GNUNET_DNSPARSER_free_record (&p->authority_records[i]); 877 GNUNET_DNSPARSER_free_record(&p->authority_records[i]);
864 GNUNET_free_non_null (p->authority_records); 878 GNUNET_free_non_null(p->authority_records);
865 for (unsigned int i = 0; i < p->num_additional_records; i++) 879 for (unsigned int i = 0; i < p->num_additional_records; i++)
866 GNUNET_DNSPARSER_free_record (&p->additional_records[i]); 880 GNUNET_DNSPARSER_free_record(&p->additional_records[i]);
867 GNUNET_free_non_null (p->additional_records); 881 GNUNET_free_non_null(p->additional_records);
868 GNUNET_free (p); 882 GNUNET_free(p);
869} 883}
870 884
871 885
@@ -886,10 +900,10 @@ GNUNET_DNSPARSER_free_packet (struct GNUNET_DNSPARSER_Packet *p)
886 * #GNUNET_OK if @a name was added to @a dst 900 * #GNUNET_OK if @a name was added to @a dst
887 */ 901 */
888int 902int
889GNUNET_DNSPARSER_builder_add_name (char *dst, 903GNUNET_DNSPARSER_builder_add_name(char *dst,
890 size_t dst_len, 904 size_t dst_len,
891 size_t *off, 905 size_t *off,
892 const char *name) 906 const char *name)
893{ 907{
894 const char *dot; 908 const char *dot;
895 const char *idna_name; 909 const char *idna_name;
@@ -903,53 +917,54 @@ GNUNET_DNSPARSER_builder_add_name (char *dst,
903 return GNUNET_SYSERR; 917 return GNUNET_SYSERR;
904 918
905 if (IDNA_SUCCESS != 919 if (IDNA_SUCCESS !=
906 (rc = idna_to_ascii_8z (name, &idna_start, IDNA_ALLOW_UNASSIGNED))) 920 (rc = idna_to_ascii_8z(name, &idna_start, IDNA_ALLOW_UNASSIGNED)))
907 { 921 {
908 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 922 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
909 _ ( 923 _(
910 "Failed to convert UTF-8 name `%s' to DNS IDNA format: %s\n"), 924 "Failed to convert UTF-8 name `%s' to DNS IDNA format: %s\n"),
911 name, 925 name,
912 idna_strerror (rc)); 926 idna_strerror(rc));
913 return GNUNET_NO; 927 return GNUNET_NO;
914 } 928 }
915 idna_name = idna_start; 929 idna_name = idna_start;
916 start = *off; 930 start = *off;
917 if (start + strlen (idna_name) + 2 > dst_len) 931 if (start + strlen(idna_name) + 2 > dst_len)
918 goto fail; 932 goto fail;
919 pos = start; 933 pos = start;
920 do 934 do
921 {
922 dot = strchr (idna_name, '.');
923 if (NULL == dot)
924 len = strlen (idna_name);
925 else
926 len = dot - idna_name;
927 if ((len >= 64) || (0 == len))
928 { 935 {
929 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 936 dot = strchr(idna_name, '.');
930 "Invalid DNS name `%s': label with %u characters encountered\n", 937 if (NULL == dot)
931 name, 938 len = strlen(idna_name);
932 (unsigned int) len); 939 else
933 goto fail; /* label too long or empty */ 940 len = dot - idna_name;
941 if ((len >= 64) || (0 == len))
942 {
943 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
944 "Invalid DNS name `%s': label with %u characters encountered\n",
945 name,
946 (unsigned int)len);
947 goto fail; /* label too long or empty */
948 }
949 dst[pos++] = (char)(uint8_t)len;
950 GNUNET_memcpy(&dst[pos], idna_name, len);
951 pos += len;
952 idna_name += len + 1; /* also skip dot */
934 } 953 }
935 dst[pos++] = (char) (uint8_t) len; 954 while (NULL != dot);
936 GNUNET_memcpy (&dst[pos], idna_name, len);
937 pos += len;
938 idna_name += len + 1; /* also skip dot */
939 } while (NULL != dot);
940 dst[pos++] = '\0'; /* terminator */ 955 dst[pos++] = '\0'; /* terminator */
941 *off = pos; 956 *off = pos;
942#if WINDOWS 957#if WINDOWS
943 idn_free (idna_start); 958 idn_free(idna_start);
944#else 959#else
945 free (idna_start); 960 free(idna_start);
946#endif 961#endif
947 return GNUNET_OK; 962 return GNUNET_OK;
948fail: 963fail:
949#if WINDOWS 964#if WINDOWS
950 idn_free (idna_start); 965 idn_free(idna_start);
951#else 966#else
952 free (idna_start); 967 free(idna_start);
953#endif 968#endif
954 return GNUNET_NO; 969 return GNUNET_NO;
955} 970}
@@ -968,26 +983,26 @@ fail:
968 * #GNUNET_OK if @a query was added to @a dst 983 * #GNUNET_OK if @a query was added to @a dst
969 */ 984 */
970int 985int
971GNUNET_DNSPARSER_builder_add_query (char *dst, 986GNUNET_DNSPARSER_builder_add_query(char *dst,
972 size_t dst_len, 987 size_t dst_len,
973 size_t *off, 988 size_t *off,
974 const struct GNUNET_DNSPARSER_Query *query) 989 const struct GNUNET_DNSPARSER_Query *query)
975{ 990{
976 int ret; 991 int ret;
977 struct GNUNET_TUN_DnsQueryLine ql; 992 struct GNUNET_TUN_DnsQueryLine ql;
978 993
979 ret = GNUNET_DNSPARSER_builder_add_name (dst, 994 ret = GNUNET_DNSPARSER_builder_add_name(dst,
980 dst_len - 995 dst_len -
981 sizeof ( 996 sizeof(
982 struct GNUNET_TUN_DnsQueryLine), 997 struct GNUNET_TUN_DnsQueryLine),
983 off, 998 off,
984 query->name); 999 query->name);
985 if (ret != GNUNET_OK) 1000 if (ret != GNUNET_OK)
986 return ret; 1001 return ret;
987 ql.type = htons (query->type); 1002 ql.type = htons(query->type);
988 ql.dns_traffic_class = htons (query->dns_traffic_class); 1003 ql.dns_traffic_class = htons(query->dns_traffic_class);
989 GNUNET_memcpy (&dst[*off], &ql, sizeof (ql)); 1004 GNUNET_memcpy(&dst[*off], &ql, sizeof(ql));
990 (*off) += sizeof (ql); 1005 (*off) += sizeof(ql);
991 return GNUNET_OK; 1006 return GNUNET_OK;
992} 1007}
993 1008
@@ -1005,19 +1020,19 @@ GNUNET_DNSPARSER_builder_add_query (char *dst,
1005 * #GNUNET_OK if @a mx was added to @a dst 1020 * #GNUNET_OK if @a mx was added to @a dst
1006 */ 1021 */
1007int 1022int
1008GNUNET_DNSPARSER_builder_add_mx (char *dst, 1023GNUNET_DNSPARSER_builder_add_mx(char *dst,
1009 size_t dst_len, 1024 size_t dst_len,
1010 size_t *off, 1025 size_t *off,
1011 const struct GNUNET_DNSPARSER_MxRecord *mx) 1026 const struct GNUNET_DNSPARSER_MxRecord *mx)
1012{ 1027{
1013 uint16_t mxpref; 1028 uint16_t mxpref;
1014 1029
1015 if (*off + sizeof (uint16_t) > dst_len) 1030 if (*off + sizeof(uint16_t) > dst_len)
1016 return GNUNET_NO; 1031 return GNUNET_NO;
1017 mxpref = htons (mx->preference); 1032 mxpref = htons(mx->preference);
1018 GNUNET_memcpy (&dst[*off], &mxpref, sizeof (mxpref)); 1033 GNUNET_memcpy(&dst[*off], &mxpref, sizeof(mxpref));
1019 (*off) += sizeof (mxpref); 1034 (*off) += sizeof(mxpref);
1020 return GNUNET_DNSPARSER_builder_add_name (dst, dst_len, off, mx->mxhost); 1035 return GNUNET_DNSPARSER_builder_add_name(dst, dst_len, off, mx->mxhost);
1021} 1036}
1022 1037
1023 1038
@@ -1034,7 +1049,7 @@ GNUNET_DNSPARSER_builder_add_mx (char *dst,
1034 * #GNUNET_OK if @a cert was added to @a dst 1049 * #GNUNET_OK if @a cert was added to @a dst
1035 */ 1050 */
1036int 1051int
1037GNUNET_DNSPARSER_builder_add_cert ( 1052GNUNET_DNSPARSER_builder_add_cert(
1038 char *dst, 1053 char *dst,
1039 size_t dst_len, 1054 size_t dst_len,
1040 size_t *off, 1055 size_t *off,
@@ -1047,22 +1062,22 @@ GNUNET_DNSPARSER_builder_add_cert (
1047#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" 1062#pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare"
1048#endif 1063#endif
1049 if ((cert->cert_type > UINT16_MAX) || (cert->algorithm > UINT8_MAX)) 1064 if ((cert->cert_type > UINT16_MAX) || (cert->algorithm > UINT8_MAX))
1050 { 1065 {
1051 GNUNET_break (0); 1066 GNUNET_break(0);
1052 return GNUNET_SYSERR; 1067 return GNUNET_SYSERR;
1053 } 1068 }
1054#ifdef __clang__ 1069#ifdef __clang__
1055#pragma clang diagnostic pop 1070#pragma clang diagnostic pop
1056#endif 1071#endif
1057 if (*off + sizeof (struct GNUNET_TUN_DnsCertRecord) + cert->certificate_size > 1072 if (*off + sizeof(struct GNUNET_TUN_DnsCertRecord) + cert->certificate_size >
1058 dst_len) 1073 dst_len)
1059 return GNUNET_NO; 1074 return GNUNET_NO;
1060 dcert.cert_type = htons ((uint16_t) cert->cert_type); 1075 dcert.cert_type = htons((uint16_t)cert->cert_type);
1061 dcert.cert_tag = htons ((uint16_t) cert->cert_tag); 1076 dcert.cert_tag = htons((uint16_t)cert->cert_tag);
1062 dcert.algorithm = (uint8_t) cert->algorithm; 1077 dcert.algorithm = (uint8_t)cert->algorithm;
1063 GNUNET_memcpy (&dst[*off], &dcert, sizeof (dcert)); 1078 GNUNET_memcpy(&dst[*off], &dcert, sizeof(dcert));
1064 (*off) += sizeof (dcert); 1079 (*off) += sizeof(dcert);
1065 GNUNET_memcpy (&dst[*off], cert->certificate_data, cert->certificate_size); 1080 GNUNET_memcpy(&dst[*off], cert->certificate_data, cert->certificate_size);
1066 (*off) += cert->certificate_size; 1081 (*off) += cert->certificate_size;
1067 return GNUNET_OK; 1082 return GNUNET_OK;
1068} 1083}
@@ -1081,30 +1096,30 @@ GNUNET_DNSPARSER_builder_add_cert (
1081 * #GNUNET_OK if @a soa was added to @a dst 1096 * #GNUNET_OK if @a soa was added to @a dst
1082 */ 1097 */
1083int 1098int
1084GNUNET_DNSPARSER_builder_add_soa (char *dst, 1099GNUNET_DNSPARSER_builder_add_soa(char *dst,
1085 size_t dst_len, 1100 size_t dst_len,
1086 size_t *off, 1101 size_t *off,
1087 const struct GNUNET_DNSPARSER_SoaRecord *soa) 1102 const struct GNUNET_DNSPARSER_SoaRecord *soa)
1088{ 1103{
1089 struct GNUNET_TUN_DnsSoaRecord sd; 1104 struct GNUNET_TUN_DnsSoaRecord sd;
1090 int ret; 1105 int ret;
1091 1106
1092 if ((GNUNET_OK != 1107 if ((GNUNET_OK !=
1093 (ret = 1108 (ret =
1094 GNUNET_DNSPARSER_builder_add_name (dst, dst_len, off, soa->mname))) || 1109 GNUNET_DNSPARSER_builder_add_name(dst, dst_len, off, soa->mname))) ||
1095 (GNUNET_OK != 1110 (GNUNET_OK !=
1096 (ret = 1111 (ret =
1097 GNUNET_DNSPARSER_builder_add_name (dst, dst_len, off, soa->rname)))) 1112 GNUNET_DNSPARSER_builder_add_name(dst, dst_len, off, soa->rname))))
1098 return ret; 1113 return ret;
1099 if (*off + sizeof (struct GNUNET_TUN_DnsSoaRecord) > dst_len) 1114 if (*off + sizeof(struct GNUNET_TUN_DnsSoaRecord) > dst_len)
1100 return GNUNET_NO; 1115 return GNUNET_NO;
1101 sd.serial = htonl (soa->serial); 1116 sd.serial = htonl(soa->serial);
1102 sd.refresh = htonl (soa->refresh); 1117 sd.refresh = htonl(soa->refresh);
1103 sd.retry = htonl (soa->retry); 1118 sd.retry = htonl(soa->retry);
1104 sd.expire = htonl (soa->expire); 1119 sd.expire = htonl(soa->expire);
1105 sd.minimum = htonl (soa->minimum_ttl); 1120 sd.minimum = htonl(soa->minimum_ttl);
1106 GNUNET_memcpy (&dst[*off], &sd, sizeof (sd)); 1121 GNUNET_memcpy(&dst[*off], &sd, sizeof(sd));
1107 (*off) += sizeof (sd); 1122 (*off) += sizeof(sd);
1108 return GNUNET_OK; 1123 return GNUNET_OK;
1109} 1124}
1110 1125
@@ -1122,24 +1137,24 @@ GNUNET_DNSPARSER_builder_add_soa (char *dst,
1122 * #GNUNET_OK if @a srv was added to @a dst 1137 * #GNUNET_OK if @a srv was added to @a dst
1123 */ 1138 */
1124int 1139int
1125GNUNET_DNSPARSER_builder_add_srv (char *dst, 1140GNUNET_DNSPARSER_builder_add_srv(char *dst,
1126 size_t dst_len, 1141 size_t dst_len,
1127 size_t *off, 1142 size_t *off,
1128 const struct GNUNET_DNSPARSER_SrvRecord *srv) 1143 const struct GNUNET_DNSPARSER_SrvRecord *srv)
1129{ 1144{
1130 struct GNUNET_TUN_DnsSrvRecord sd; 1145 struct GNUNET_TUN_DnsSrvRecord sd;
1131 int ret; 1146 int ret;
1132 1147
1133 if (*off + sizeof (struct GNUNET_TUN_DnsSrvRecord) > dst_len) 1148 if (*off + sizeof(struct GNUNET_TUN_DnsSrvRecord) > dst_len)
1134 return GNUNET_NO; 1149 return GNUNET_NO;
1135 sd.prio = htons (srv->priority); 1150 sd.prio = htons(srv->priority);
1136 sd.weight = htons (srv->weight); 1151 sd.weight = htons(srv->weight);
1137 sd.port = htons (srv->port); 1152 sd.port = htons(srv->port);
1138 GNUNET_memcpy (&dst[*off], &sd, sizeof (sd)); 1153 GNUNET_memcpy(&dst[*off], &sd, sizeof(sd));
1139 (*off) += sizeof (sd); 1154 (*off) += sizeof(sd);
1140 if (GNUNET_OK != 1155 if (GNUNET_OK !=
1141 (ret = 1156 (ret =
1142 GNUNET_DNSPARSER_builder_add_name (dst, dst_len, off, srv->target))) 1157 GNUNET_DNSPARSER_builder_add_name(dst, dst_len, off, srv->target)))
1143 return ret; 1158 return ret;
1144 return GNUNET_OK; 1159 return GNUNET_OK;
1145} 1160}
@@ -1158,10 +1173,10 @@ GNUNET_DNSPARSER_builder_add_srv (char *dst,
1158 * #GNUNET_OK if @a record was added to @a dst 1173 * #GNUNET_OK if @a record was added to @a dst
1159 */ 1174 */
1160static int 1175static int
1161add_record (char *dst, 1176add_record(char *dst,
1162 size_t dst_len, 1177 size_t dst_len,
1163 size_t *off, 1178 size_t *off,
1164 const struct GNUNET_DNSPARSER_Record *record) 1179 const struct GNUNET_DNSPARSER_Record *record)
1165{ 1180{
1166 int ret; 1181 int ret;
1167 size_t start; 1182 size_t start;
@@ -1169,73 +1184,78 @@ add_record (char *dst,
1169 struct GNUNET_TUN_DnsRecordLine rl; 1184 struct GNUNET_TUN_DnsRecordLine rl;
1170 1185
1171 start = *off; 1186 start = *off;
1172 ret = GNUNET_DNSPARSER_builder_add_name (dst, 1187 ret = GNUNET_DNSPARSER_builder_add_name(dst,
1173 dst_len - 1188 dst_len -
1174 sizeof ( 1189 sizeof(
1175 struct GNUNET_TUN_DnsRecordLine), 1190 struct GNUNET_TUN_DnsRecordLine),
1176 off, 1191 off,
1177 record->name); 1192 record->name);
1178 if (GNUNET_OK != ret) 1193 if (GNUNET_OK != ret)
1179 return ret; 1194 return ret;
1180 /* '*off' is now the position where we will need to write the record line */ 1195 /* '*off' is now the position where we will need to write the record line */
1181 1196
1182 pos = *off + sizeof (struct GNUNET_TUN_DnsRecordLine); 1197 pos = *off + sizeof(struct GNUNET_TUN_DnsRecordLine);
1183 switch (record->type) 1198 switch (record->type)
1184 {
1185 case GNUNET_DNSPARSER_TYPE_MX:
1186 ret = GNUNET_DNSPARSER_builder_add_mx (dst, dst_len, &pos, record->data.mx);
1187 break;
1188 case GNUNET_DNSPARSER_TYPE_CERT:
1189 ret =
1190 GNUNET_DNSPARSER_builder_add_cert (dst, dst_len, &pos, record->data.cert);
1191 break;
1192 case GNUNET_DNSPARSER_TYPE_SOA:
1193 ret =
1194 GNUNET_DNSPARSER_builder_add_soa (dst, dst_len, &pos, record->data.soa);
1195 break;
1196 case GNUNET_DNSPARSER_TYPE_NS:
1197 case GNUNET_DNSPARSER_TYPE_CNAME:
1198 case GNUNET_DNSPARSER_TYPE_PTR:
1199 ret = GNUNET_DNSPARSER_builder_add_name (dst,
1200 dst_len,
1201 &pos,
1202 record->data.hostname);
1203 break;
1204 case GNUNET_DNSPARSER_TYPE_SRV:
1205 ret =
1206 GNUNET_DNSPARSER_builder_add_srv (dst, dst_len, &pos, record->data.srv);
1207 break;
1208 default:
1209 if (pos + record->data.raw.data_len > dst_len)
1210 { 1199 {
1211 ret = GNUNET_NO; 1200 case GNUNET_DNSPARSER_TYPE_MX:
1201 ret = GNUNET_DNSPARSER_builder_add_mx(dst, dst_len, &pos, record->data.mx);
1202 break;
1203
1204 case GNUNET_DNSPARSER_TYPE_CERT:
1205 ret =
1206 GNUNET_DNSPARSER_builder_add_cert(dst, dst_len, &pos, record->data.cert);
1207 break;
1208
1209 case GNUNET_DNSPARSER_TYPE_SOA:
1210 ret =
1211 GNUNET_DNSPARSER_builder_add_soa(dst, dst_len, &pos, record->data.soa);
1212 break;
1213
1214 case GNUNET_DNSPARSER_TYPE_NS:
1215 case GNUNET_DNSPARSER_TYPE_CNAME:
1216 case GNUNET_DNSPARSER_TYPE_PTR:
1217 ret = GNUNET_DNSPARSER_builder_add_name(dst,
1218 dst_len,
1219 &pos,
1220 record->data.hostname);
1221 break;
1222
1223 case GNUNET_DNSPARSER_TYPE_SRV:
1224 ret =
1225 GNUNET_DNSPARSER_builder_add_srv(dst, dst_len, &pos, record->data.srv);
1226 break;
1227
1228 default:
1229 if (pos + record->data.raw.data_len > dst_len)
1230 {
1231 ret = GNUNET_NO;
1232 break;
1233 }
1234 GNUNET_memcpy(&dst[pos], record->data.raw.data, record->data.raw.data_len);
1235 pos += record->data.raw.data_len;
1236 ret = GNUNET_OK;
1212 break; 1237 break;
1213 } 1238 }
1214 GNUNET_memcpy (&dst[pos], record->data.raw.data, record->data.raw.data_len);
1215 pos += record->data.raw.data_len;
1216 ret = GNUNET_OK;
1217 break;
1218 }
1219 if (GNUNET_OK != ret) 1239 if (GNUNET_OK != ret)
1220 { 1240 {
1221 *off = start; 1241 *off = start;
1222 return GNUNET_NO; 1242 return GNUNET_NO;
1223 } 1243 }
1224 1244
1225 if (pos - (*off + sizeof (struct GNUNET_TUN_DnsRecordLine)) > UINT16_MAX) 1245 if (pos - (*off + sizeof(struct GNUNET_TUN_DnsRecordLine)) > UINT16_MAX)
1226 { 1246 {
1227 /* record data too long */ 1247 /* record data too long */
1228 *off = start; 1248 *off = start;
1229 return GNUNET_NO; 1249 return GNUNET_NO;
1230 } 1250 }
1231 rl.type = htons (record->type); 1251 rl.type = htons(record->type);
1232 rl.dns_traffic_class = htons (record->dns_traffic_class); 1252 rl.dns_traffic_class = htons(record->dns_traffic_class);
1233 rl.ttl = htonl ( 1253 rl.ttl = htonl(
1234 GNUNET_TIME_absolute_get_remaining (record->expiration_time).rel_value_us / 1254 GNUNET_TIME_absolute_get_remaining(record->expiration_time).rel_value_us /
1235 1000LL / 1000LL); /* in seconds */ 1255 1000LL / 1000LL); /* in seconds */
1236 rl.data_len = htons ( 1256 rl.data_len = htons(
1237 (uint16_t) (pos - (*off + sizeof (struct GNUNET_TUN_DnsRecordLine)))); 1257 (uint16_t)(pos - (*off + sizeof(struct GNUNET_TUN_DnsRecordLine))));
1238 GNUNET_memcpy (&dst[*off], &rl, sizeof (struct GNUNET_TUN_DnsRecordLine)); 1258 GNUNET_memcpy(&dst[*off], &rl, sizeof(struct GNUNET_TUN_DnsRecordLine));
1239 *off = pos; 1259 *off = pos;
1240 return GNUNET_OK; 1260 return GNUNET_OK;
1241} 1261}
@@ -1256,10 +1276,10 @@ add_record (char *dst,
1256 * #GNUNET_OK if @a p was packed completely into @a buf 1276 * #GNUNET_OK if @a p was packed completely into @a buf
1257 */ 1277 */
1258int 1278int
1259GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p, 1279GNUNET_DNSPARSER_pack(const struct GNUNET_DNSPARSER_Packet *p,
1260 uint16_t max, 1280 uint16_t max,
1261 char **buf, 1281 char **buf,
1262 size_t *buf_length) 1282 size_t *buf_length)
1263{ 1283{
1264 struct GNUNET_TUN_DnsHeader dns; 1284 struct GNUNET_TUN_DnsHeader dns;
1265 size_t off; 1285 size_t off;
@@ -1273,72 +1293,72 @@ GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p,
1273 return GNUNET_SYSERR; 1293 return GNUNET_SYSERR;
1274 dns.id = p->id; 1294 dns.id = p->id;
1275 dns.flags = p->flags; 1295 dns.flags = p->flags;
1276 dns.query_count = htons (p->num_queries); 1296 dns.query_count = htons(p->num_queries);
1277 dns.answer_rcount = htons (p->num_answers); 1297 dns.answer_rcount = htons(p->num_answers);
1278 dns.authority_rcount = htons (p->num_authority_records); 1298 dns.authority_rcount = htons(p->num_authority_records);
1279 dns.additional_rcount = htons (p->num_additional_records); 1299 dns.additional_rcount = htons(p->num_additional_records);
1280 1300
1281 off = sizeof (struct GNUNET_TUN_DnsHeader); 1301 off = sizeof(struct GNUNET_TUN_DnsHeader);
1282 trc = GNUNET_NO; 1302 trc = GNUNET_NO;
1283 for (unsigned int i = 0; i < p->num_queries; i++) 1303 for (unsigned int i = 0; i < p->num_queries; i++)
1284 {
1285 ret = GNUNET_DNSPARSER_builder_add_query (tmp,
1286 sizeof (tmp),
1287 &off,
1288 &p->queries[i]);
1289 if (GNUNET_SYSERR == ret)
1290 return GNUNET_SYSERR;
1291 if (GNUNET_NO == ret)
1292 { 1304 {
1293 dns.query_count = htons ((uint16_t) (i - 1)); 1305 ret = GNUNET_DNSPARSER_builder_add_query(tmp,
1294 trc = GNUNET_YES; 1306 sizeof(tmp),
1295 break; 1307 &off,
1308 &p->queries[i]);
1309 if (GNUNET_SYSERR == ret)
1310 return GNUNET_SYSERR;
1311 if (GNUNET_NO == ret)
1312 {
1313 dns.query_count = htons((uint16_t)(i - 1));
1314 trc = GNUNET_YES;
1315 break;
1316 }
1296 } 1317 }
1297 }
1298 for (unsigned int i = 0; i < p->num_answers; i++) 1318 for (unsigned int i = 0; i < p->num_answers; i++)
1299 {
1300 ret = add_record (tmp, sizeof (tmp), &off, &p->answers[i]);
1301 if (GNUNET_SYSERR == ret)
1302 return GNUNET_SYSERR;
1303 if (GNUNET_NO == ret)
1304 { 1319 {
1305 dns.answer_rcount = htons ((uint16_t) (i - 1)); 1320 ret = add_record(tmp, sizeof(tmp), &off, &p->answers[i]);
1306 trc = GNUNET_YES; 1321 if (GNUNET_SYSERR == ret)
1307 break; 1322 return GNUNET_SYSERR;
1323 if (GNUNET_NO == ret)
1324 {
1325 dns.answer_rcount = htons((uint16_t)(i - 1));
1326 trc = GNUNET_YES;
1327 break;
1328 }
1308 } 1329 }
1309 }
1310 for (unsigned int i = 0; i < p->num_authority_records; i++) 1330 for (unsigned int i = 0; i < p->num_authority_records; i++)
1311 {
1312 ret = add_record (tmp, sizeof (tmp), &off, &p->authority_records[i]);
1313 if (GNUNET_SYSERR == ret)
1314 return GNUNET_SYSERR;
1315 if (GNUNET_NO == ret)
1316 { 1331 {
1317 dns.authority_rcount = htons ((uint16_t) (i - 1)); 1332 ret = add_record(tmp, sizeof(tmp), &off, &p->authority_records[i]);
1318 trc = GNUNET_YES; 1333 if (GNUNET_SYSERR == ret)
1319 break; 1334 return GNUNET_SYSERR;
1335 if (GNUNET_NO == ret)
1336 {
1337 dns.authority_rcount = htons((uint16_t)(i - 1));
1338 trc = GNUNET_YES;
1339 break;
1340 }
1320 } 1341 }
1321 }
1322 for (unsigned int i = 0; i < p->num_additional_records; i++) 1342 for (unsigned int i = 0; i < p->num_additional_records; i++)
1323 {
1324 ret = add_record (tmp, sizeof (tmp), &off, &p->additional_records[i]);
1325 if (GNUNET_SYSERR == ret)
1326 return GNUNET_SYSERR;
1327 if (GNUNET_NO == ret)
1328 { 1343 {
1329 dns.additional_rcount = htons (i - 1); 1344 ret = add_record(tmp, sizeof(tmp), &off, &p->additional_records[i]);
1330 trc = GNUNET_YES; 1345 if (GNUNET_SYSERR == ret)
1331 break; 1346 return GNUNET_SYSERR;
1347 if (GNUNET_NO == ret)
1348 {
1349 dns.additional_rcount = htons(i - 1);
1350 trc = GNUNET_YES;
1351 break;
1352 }
1332 } 1353 }
1333 }
1334 1354
1335 if (GNUNET_YES == trc) 1355 if (GNUNET_YES == trc)
1336 dns.flags.message_truncated = 1; 1356 dns.flags.message_truncated = 1;
1337 GNUNET_memcpy (tmp, &dns, sizeof (struct GNUNET_TUN_DnsHeader)); 1357 GNUNET_memcpy(tmp, &dns, sizeof(struct GNUNET_TUN_DnsHeader));
1338 1358
1339 *buf = GNUNET_malloc (off); 1359 *buf = GNUNET_malloc(off);
1340 *buf_length = off; 1360 *buf_length = off;
1341 GNUNET_memcpy (*buf, tmp, off); 1361 GNUNET_memcpy(*buf, tmp, off);
1342 if (GNUNET_YES == trc) 1362 if (GNUNET_YES == trc)
1343 return GNUNET_NO; 1363 return GNUNET_NO;
1344 return GNUNET_OK; 1364 return GNUNET_OK;
@@ -1353,16 +1373,16 @@ GNUNET_DNSPARSER_pack (const struct GNUNET_DNSPARSER_Packet *p,
1353 * @return HEX string (lower case) 1373 * @return HEX string (lower case)
1354 */ 1374 */
1355char * 1375char *
1356GNUNET_DNSPARSER_bin_to_hex (const void *data, size_t data_size) 1376GNUNET_DNSPARSER_bin_to_hex(const void *data, size_t data_size)
1357{ 1377{
1358 char *ret; 1378 char *ret;
1359 size_t off; 1379 size_t off;
1360 const uint8_t *idata; 1380 const uint8_t *idata;
1361 1381
1362 idata = data; 1382 idata = data;
1363 ret = GNUNET_malloc (data_size * 2 + 1); 1383 ret = GNUNET_malloc(data_size * 2 + 1);
1364 for (off = 0; off < data_size; off++) 1384 for (off = 0; off < data_size; off++)
1365 sprintf (&ret[off * 2], "%02x", idata[off]); 1385 sprintf(&ret[off * 2], "%02x", idata[off]);
1366 return ret; 1386 return ret;
1367} 1387}
1368 1388
@@ -1376,7 +1396,7 @@ GNUNET_DNSPARSER_bin_to_hex (const void *data, size_t data_size)
1376 * @return number of bytes written to data 1396 * @return number of bytes written to data
1377 */ 1397 */
1378size_t 1398size_t
1379GNUNET_DNSPARSER_hex_to_bin (const char *hex, void *data) 1399GNUNET_DNSPARSER_hex_to_bin(const char *hex, void *data)
1380{ 1400{
1381 size_t data_size; 1401 size_t data_size;
1382 size_t off; 1402 size_t off;
@@ -1384,17 +1404,17 @@ GNUNET_DNSPARSER_hex_to_bin (const char *hex, void *data)
1384 unsigned int h; 1404 unsigned int h;
1385 char in[3]; 1405 char in[3];
1386 1406
1387 data_size = strlen (hex) / 2; 1407 data_size = strlen(hex) / 2;
1388 idata = data; 1408 idata = data;
1389 in[2] = '\0'; 1409 in[2] = '\0';
1390 for (off = 0; off < data_size; off++) 1410 for (off = 0; off < data_size; off++)
1391 { 1411 {
1392 in[0] = tolower ((unsigned char) hex[off * 2]); 1412 in[0] = tolower((unsigned char)hex[off * 2]);
1393 in[1] = tolower ((unsigned char) hex[off * 2 + 1]); 1413 in[1] = tolower((unsigned char)hex[off * 2 + 1]);
1394 if (1 != sscanf (in, "%x", &h)) 1414 if (1 != sscanf(in, "%x", &h))
1395 return off; 1415 return off;
1396 idata[off] = (uint8_t) h; 1416 idata[off] = (uint8_t)h;
1397 } 1417 }
1398 return off; 1418 return off;
1399} 1419}
1400 1420
diff --git a/src/util/dnsstub.c b/src/util/dnsstub.c
index aa0c2191a..ab7a08318 100644
--- a/src/util/dnsstub.c
+++ b/src/util/dnsstub.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file dns/dnsstub.c 21 * @file dns/dnsstub.c
22 * @brief DNS stub resolver which sends DNS requests to an actual resolver 22 * @brief DNS stub resolver which sends DNS requests to an actual resolver
@@ -29,7 +29,7 @@
29 * Timeout for retrying DNS queries. 29 * Timeout for retrying DNS queries.
30 */ 30 */
31#define DNS_RETRANSMIT_DELAY \ 31#define DNS_RETRANSMIT_DELAY \
32 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 250) 32 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 250)
33 33
34 34
35/** 35/**
@@ -41,9 +41,7 @@ struct DnsServer;
41/** 41/**
42 * UDP socket we are using for sending DNS requests to the Internet. 42 * UDP socket we are using for sending DNS requests to the Internet.
43 */ 43 */
44struct GNUNET_DNSSTUB_RequestSocket 44struct GNUNET_DNSSTUB_RequestSocket {
45{
46
47 /** 45 /**
48 * UDP socket we use for this request for IPv4 46 * UDP socket we use for this request for IPv4
49 */ 47 */
@@ -99,9 +97,7 @@ struct GNUNET_DNSSTUB_RequestSocket
99/** 97/**
100 * DNS Server used for resolution. 98 * DNS Server used for resolution.
101 */ 99 */
102struct DnsServer 100struct DnsServer {
103{
104
105 /** 101 /**
106 * Kept in a DLL. 102 * Kept in a DLL.
107 */ 103 */
@@ -122,9 +118,7 @@ struct DnsServer
122/** 118/**
123 * Handle to the stub resolver. 119 * Handle to the stub resolver.
124 */ 120 */
125struct GNUNET_DNSSTUB_Context 121struct GNUNET_DNSSTUB_Context {
126{
127
128 /** 122 /**
129 * Array of all open sockets for DNS requests. 123 * Array of all open sockets for DNS requests.
130 */ 124 */
@@ -158,33 +152,33 @@ struct GNUNET_DNSSTUB_Context
158 * @param rs request socket to clean up 152 * @param rs request socket to clean up
159 */ 153 */
160static void 154static void
161cleanup_rs (struct GNUNET_DNSSTUB_RequestSocket *rs) 155cleanup_rs(struct GNUNET_DNSSTUB_RequestSocket *rs)
162{ 156{
163 if (NULL != rs->dnsout4) 157 if (NULL != rs->dnsout4)
164 { 158 {
165 GNUNET_NETWORK_socket_close (rs->dnsout4); 159 GNUNET_NETWORK_socket_close(rs->dnsout4);
166 rs->dnsout4 = NULL; 160 rs->dnsout4 = NULL;
167 } 161 }
168 if (NULL != rs->dnsout6) 162 if (NULL != rs->dnsout6)
169 { 163 {
170 GNUNET_NETWORK_socket_close (rs->dnsout6); 164 GNUNET_NETWORK_socket_close(rs->dnsout6);
171 rs->dnsout6 = NULL; 165 rs->dnsout6 = NULL;
172 } 166 }
173 if (NULL != rs->read_task) 167 if (NULL != rs->read_task)
174 { 168 {
175 GNUNET_SCHEDULER_cancel (rs->read_task); 169 GNUNET_SCHEDULER_cancel(rs->read_task);
176 rs->read_task = NULL; 170 rs->read_task = NULL;
177 } 171 }
178 if (NULL != rs->retry_task) 172 if (NULL != rs->retry_task)
179 { 173 {
180 GNUNET_SCHEDULER_cancel (rs->retry_task); 174 GNUNET_SCHEDULER_cancel(rs->retry_task);
181 rs->retry_task = NULL; 175 rs->retry_task = NULL;
182 } 176 }
183 if (NULL != rs->request) 177 if (NULL != rs->request)
184 { 178 {
185 GNUNET_free (rs->request); 179 GNUNET_free(rs->request);
186 rs->request = NULL; 180 rs->request = NULL;
187 } 181 }
188} 182}
189 183
190 184
@@ -195,7 +189,7 @@ cleanup_rs (struct GNUNET_DNSSTUB_RequestSocket *rs)
195 * @return #GNUNET_OK on success 189 * @return #GNUNET_OK on success
196 */ 190 */
197static struct GNUNET_NETWORK_Handle * 191static struct GNUNET_NETWORK_Handle *
198open_socket (int af) 192open_socket(int af)
199{ 193{
200 struct sockaddr_in a4; 194 struct sockaddr_in a4;
201 struct sockaddr_in6 a6; 195 struct sockaddr_in6 a6;
@@ -203,33 +197,35 @@ open_socket (int af)
203 socklen_t alen; 197 socklen_t alen;
204 struct GNUNET_NETWORK_Handle *ret; 198 struct GNUNET_NETWORK_Handle *ret;
205 199
206 ret = GNUNET_NETWORK_socket_create (af, SOCK_DGRAM, 0); 200 ret = GNUNET_NETWORK_socket_create(af, SOCK_DGRAM, 0);
207 if (NULL == ret) 201 if (NULL == ret)
208 return NULL; 202 return NULL;
209 switch (af) 203 switch (af)
210 { 204 {
211 case AF_INET: 205 case AF_INET:
212 memset (&a4, 0, alen = sizeof (struct sockaddr_in)); 206 memset(&a4, 0, alen = sizeof(struct sockaddr_in));
213 sa = (struct sockaddr *) &a4; 207 sa = (struct sockaddr *)&a4;
214 break; 208 break;
215 case AF_INET6: 209
216 memset (&a6, 0, alen = sizeof (struct sockaddr_in6)); 210 case AF_INET6:
217 sa = (struct sockaddr *) &a6; 211 memset(&a6, 0, alen = sizeof(struct sockaddr_in6));
218 break; 212 sa = (struct sockaddr *)&a6;
219 default: 213 break;
220 GNUNET_break (0); 214
221 GNUNET_NETWORK_socket_close (ret); 215 default:
222 return NULL; 216 GNUNET_break(0);
223 } 217 GNUNET_NETWORK_socket_close(ret);
218 return NULL;
219 }
224 sa->sa_family = af; 220 sa->sa_family = af;
225 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (ret, sa, alen)) 221 if (GNUNET_OK != GNUNET_NETWORK_socket_bind(ret, sa, alen))
226 { 222 {
227 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 223 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
228 _ ("Could not bind to any port: %s\n"), 224 _("Could not bind to any port: %s\n"),
229 strerror (errno)); 225 strerror(errno));
230 GNUNET_NETWORK_socket_close (ret); 226 GNUNET_NETWORK_socket_close(ret);
231 return NULL; 227 return NULL;
232 } 228 }
233 return ret; 229 return ret;
234} 230}
235 231
@@ -242,38 +238,38 @@ open_socket (int af)
242 * @return NULL on error 238 * @return NULL on error
243 */ 239 */
244static struct GNUNET_DNSSTUB_RequestSocket * 240static struct GNUNET_DNSSTUB_RequestSocket *
245get_request_socket (struct GNUNET_DNSSTUB_Context *ctx) 241get_request_socket(struct GNUNET_DNSSTUB_Context *ctx)
246{ 242{
247 struct GNUNET_DNSSTUB_RequestSocket *rs; 243 struct GNUNET_DNSSTUB_RequestSocket *rs;
248 244
249 for (unsigned int i = 0; i < 256; i++) 245 for (unsigned int i = 0; i < 256; i++)
250 { 246 {
251 rs = &ctx->sockets[GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, 247 rs = &ctx->sockets[GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE,
252 ctx->num_sockets)]; 248 ctx->num_sockets)];
253 if (NULL == rs->rc) 249 if (NULL == rs->rc)
254 break; 250 break;
255 } 251 }
256 if (NULL != rs->rc) 252 if (NULL != rs->rc)
257 { 253 {
258 /* signal "failure" */ 254 /* signal "failure" */
259 rs->rc (rs->rc_cls, NULL, 0); 255 rs->rc(rs->rc_cls, NULL, 0);
260 rs->rc = NULL; 256 rs->rc = NULL;
261 } 257 }
262 if (NULL != rs->read_task) 258 if (NULL != rs->read_task)
263 { 259 {
264 GNUNET_SCHEDULER_cancel (rs->read_task); 260 GNUNET_SCHEDULER_cancel(rs->read_task);
265 rs->read_task = NULL; 261 rs->read_task = NULL;
266 } 262 }
267 if (NULL != rs->retry_task) 263 if (NULL != rs->retry_task)
268 { 264 {
269 GNUNET_SCHEDULER_cancel (rs->retry_task); 265 GNUNET_SCHEDULER_cancel(rs->retry_task);
270 rs->retry_task = NULL; 266 rs->retry_task = NULL;
271 } 267 }
272 if (NULL != rs->request) 268 if (NULL != rs->request)
273 { 269 {
274 GNUNET_free (rs->request); 270 GNUNET_free(rs->request);
275 rs->request = NULL; 271 rs->request = NULL;
276 } 272 }
277 rs->ctx = ctx; 273 rs->ctx = ctx;
278 return rs; 274 return rs;
279} 275}
@@ -288,24 +284,24 @@ get_request_socket (struct GNUNET_DNSSTUB_Context *ctx)
288 * @return #GNUNET_OK on success, #GNUNET_NO on drop, #GNUNET_SYSERR on IO-errors (closed socket) 284 * @return #GNUNET_OK on success, #GNUNET_NO on drop, #GNUNET_SYSERR on IO-errors (closed socket)
289 */ 285 */
290static int 286static int
291do_dns_read (struct GNUNET_DNSSTUB_RequestSocket *rs, 287do_dns_read(struct GNUNET_DNSSTUB_RequestSocket *rs,
292 struct GNUNET_NETWORK_Handle *dnsout) 288 struct GNUNET_NETWORK_Handle *dnsout)
293{ 289{
294 struct GNUNET_DNSSTUB_Context *ctx = rs->ctx; 290 struct GNUNET_DNSSTUB_Context *ctx = rs->ctx;
295 ssize_t r; 291 ssize_t r;
296 int len; 292 int len;
297 293
298#ifndef MINGW 294#ifndef MINGW
299 if (0 != ioctl (GNUNET_NETWORK_get_fd (dnsout), FIONREAD, &len)) 295 if (0 != ioctl(GNUNET_NETWORK_get_fd(dnsout), FIONREAD, &len))
300 { 296 {
301 /* conservative choice: */ 297 /* conservative choice: */
302 len = UINT16_MAX; 298 len = UINT16_MAX;
303 } 299 }
304#else 300#else
305 /* port the code above? */ 301 /* port the code above? */
306 len = UINT16_MAX; 302 len = UINT16_MAX;
307#endif 303#endif
308 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Receiving %d byte DNS reply\n", len); 304 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Receiving %d byte DNS reply\n", len);
309 { 305 {
310 unsigned char buf[len] GNUNET_ALIGN; 306 unsigned char buf[len] GNUNET_ALIGN;
311 int found; 307 int found;
@@ -313,51 +309,51 @@ do_dns_read (struct GNUNET_DNSSTUB_RequestSocket *rs,
313 socklen_t addrlen; 309 socklen_t addrlen;
314 struct GNUNET_TUN_DnsHeader *dns; 310 struct GNUNET_TUN_DnsHeader *dns;
315 311
316 addrlen = sizeof (addr); 312 addrlen = sizeof(addr);
317 memset (&addr, 0, sizeof (addr)); 313 memset(&addr, 0, sizeof(addr));
318 r = GNUNET_NETWORK_socket_recvfrom (dnsout, 314 r = GNUNET_NETWORK_socket_recvfrom(dnsout,
319 buf, 315 buf,
320 sizeof (buf), 316 sizeof(buf),
321 (struct sockaddr *) &addr, 317 (struct sockaddr *)&addr,
322 &addrlen); 318 &addrlen);
323 if (-1 == r) 319 if (-1 == r)
324 { 320 {
325 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "recvfrom"); 321 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "recvfrom");
326 GNUNET_NETWORK_socket_close (dnsout); 322 GNUNET_NETWORK_socket_close(dnsout);
327 return GNUNET_SYSERR; 323 return GNUNET_SYSERR;
328 } 324 }
329 found = GNUNET_NO; 325 found = GNUNET_NO;
330 for (struct DnsServer *ds = ctx->dns_head; NULL != ds; ds = ds->next) 326 for (struct DnsServer *ds = ctx->dns_head; NULL != ds; ds = ds->next)
331 {
332 if (0 == memcmp (&addr,
333 &ds->ss,
334 GNUNET_MIN (sizeof (struct sockaddr_storage), addrlen)))
335 { 327 {
336 found = GNUNET_YES; 328 if (0 == memcmp(&addr,
337 break; 329 &ds->ss,
330 GNUNET_MIN(sizeof(struct sockaddr_storage), addrlen)))
331 {
332 found = GNUNET_YES;
333 break;
334 }
338 } 335 }
339 }
340 if (GNUNET_NO == found) 336 if (GNUNET_NO == found)
341 { 337 {
342 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 338 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
343 "Received DNS response from server we never asked (ignored)"); 339 "Received DNS response from server we never asked (ignored)");
344 return GNUNET_NO; 340 return GNUNET_NO;
345 } 341 }
346 if (sizeof (struct GNUNET_TUN_DnsHeader) > (size_t) r) 342 if (sizeof(struct GNUNET_TUN_DnsHeader) > (size_t)r)
347 { 343 {
348 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 344 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
349 _ ("Received DNS response that is too small (%u bytes)"), 345 _("Received DNS response that is too small (%u bytes)"),
350 (unsigned int) r); 346 (unsigned int)r);
351 return GNUNET_NO; 347 return GNUNET_NO;
352 } 348 }
353 dns = (struct GNUNET_TUN_DnsHeader *) buf; 349 dns = (struct GNUNET_TUN_DnsHeader *)buf;
354 if (NULL == rs->rc) 350 if (NULL == rs->rc)
355 { 351 {
356 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 352 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
357 "Request timeout or cancelled; ignoring reply\n"); 353 "Request timeout or cancelled; ignoring reply\n");
358 return GNUNET_NO; 354 return GNUNET_NO;
359 } 355 }
360 rs->rc (rs->rc_cls, dns, r); 356 rs->rc(rs->rc_cls, dns, r);
361 } 357 }
362 return GNUNET_OK; 358 return GNUNET_OK;
363} 359}
@@ -369,7 +365,7 @@ do_dns_read (struct GNUNET_DNSSTUB_RequestSocket *rs,
369 * @param cls socket to read from 365 * @param cls socket to read from
370 */ 366 */
371static void 367static void
372read_response (void *cls); 368read_response(void *cls);
373 369
374 370
375/** 371/**
@@ -378,25 +374,25 @@ read_response (void *cls);
378 * @param rs request to schedule read operation for 374 * @param rs request to schedule read operation for
379 */ 375 */
380static void 376static void
381schedule_read (struct GNUNET_DNSSTUB_RequestSocket *rs) 377schedule_read(struct GNUNET_DNSSTUB_RequestSocket *rs)
382{ 378{
383 struct GNUNET_NETWORK_FDSet *rset; 379 struct GNUNET_NETWORK_FDSet *rset;
384 380
385 if (NULL != rs->read_task) 381 if (NULL != rs->read_task)
386 GNUNET_SCHEDULER_cancel (rs->read_task); 382 GNUNET_SCHEDULER_cancel(rs->read_task);
387 rset = GNUNET_NETWORK_fdset_create (); 383 rset = GNUNET_NETWORK_fdset_create();
388 if (NULL != rs->dnsout4) 384 if (NULL != rs->dnsout4)
389 GNUNET_NETWORK_fdset_set (rset, rs->dnsout4); 385 GNUNET_NETWORK_fdset_set(rset, rs->dnsout4);
390 if (NULL != rs->dnsout6) 386 if (NULL != rs->dnsout6)
391 GNUNET_NETWORK_fdset_set (rset, rs->dnsout6); 387 GNUNET_NETWORK_fdset_set(rset, rs->dnsout6);
392 rs->read_task = 388 rs->read_task =
393 GNUNET_SCHEDULER_add_select (GNUNET_SCHEDULER_PRIORITY_DEFAULT, 389 GNUNET_SCHEDULER_add_select(GNUNET_SCHEDULER_PRIORITY_DEFAULT,
394 GNUNET_TIME_UNIT_FOREVER_REL, 390 GNUNET_TIME_UNIT_FOREVER_REL,
395 rset, 391 rset,
396 NULL, 392 NULL,
397 &read_response, 393 &read_response,
398 rs); 394 rs);
399 GNUNET_NETWORK_fdset_destroy (rset); 395 GNUNET_NETWORK_fdset_destroy(rset);
400} 396}
401 397
402 398
@@ -406,24 +402,24 @@ schedule_read (struct GNUNET_DNSSTUB_RequestSocket *rs)
406 * @param cls `struct GNUNET_DNSSTUB_RequestSocket` to read from 402 * @param cls `struct GNUNET_DNSSTUB_RequestSocket` to read from
407 */ 403 */
408static void 404static void
409read_response (void *cls) 405read_response(void *cls)
410{ 406{
411 struct GNUNET_DNSSTUB_RequestSocket *rs = cls; 407 struct GNUNET_DNSSTUB_RequestSocket *rs = cls;
412 const struct GNUNET_SCHEDULER_TaskContext *tc; 408 const struct GNUNET_SCHEDULER_TaskContext *tc;
413 409
414 rs->read_task = NULL; 410 rs->read_task = NULL;
415 tc = GNUNET_SCHEDULER_get_task_context (); 411 tc = GNUNET_SCHEDULER_get_task_context();
416 /* read and process ready sockets */ 412 /* read and process ready sockets */
417 if ((NULL != rs->dnsout4) && 413 if ((NULL != rs->dnsout4) &&
418 (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout4)) && 414 (GNUNET_NETWORK_fdset_isset(tc->read_ready, rs->dnsout4)) &&
419 (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout4))) 415 (GNUNET_SYSERR == do_dns_read(rs, rs->dnsout4)))
420 rs->dnsout4 = NULL; 416 rs->dnsout4 = NULL;
421 if ((NULL != rs->dnsout6) && 417 if ((NULL != rs->dnsout6) &&
422 (GNUNET_NETWORK_fdset_isset (tc->read_ready, rs->dnsout6)) && 418 (GNUNET_NETWORK_fdset_isset(tc->read_ready, rs->dnsout6)) &&
423 (GNUNET_SYSERR == do_dns_read (rs, rs->dnsout6))) 419 (GNUNET_SYSERR == do_dns_read(rs, rs->dnsout6)))
424 rs->dnsout6 = NULL; 420 rs->dnsout6 = NULL;
425 /* re-schedule read task */ 421 /* re-schedule read task */
426 schedule_read (rs); 422 schedule_read(rs);
427} 423}
428 424
429 425
@@ -434,7 +430,7 @@ read_response (void *cls)
434 * @param cls our `struct GNUNET_DNSSTUB_RequestSocket *` 430 * @param cls our `struct GNUNET_DNSSTUB_RequestSocket *`
435 */ 431 */
436static void 432static void
437transmit_query (void *cls) 433transmit_query(void *cls)
438{ 434{
439 struct GNUNET_DNSSTUB_RequestSocket *rs = cls; 435 struct GNUNET_DNSSTUB_RequestSocket *rs = cls;
440 struct GNUNET_DNSSTUB_Context *ctx = rs->ctx; 436 struct GNUNET_DNSSTUB_Context *ctx = rs->ctx;
@@ -444,52 +440,54 @@ transmit_query (void *cls)
444 struct GNUNET_NETWORK_Handle *dnsout; 440 struct GNUNET_NETWORK_Handle *dnsout;
445 441
446 rs->retry_task = 442 rs->retry_task =
447 GNUNET_SCHEDULER_add_delayed (ctx->retry_freq, &transmit_query, rs); 443 GNUNET_SCHEDULER_add_delayed(ctx->retry_freq, &transmit_query, rs);
448 ds = rs->ds_pos; 444 ds = rs->ds_pos;
449 rs->ds_pos = ds->next; 445 rs->ds_pos = ds->next;
450 if (NULL == rs->ds_pos) 446 if (NULL == rs->ds_pos)
451 rs->ds_pos = ctx->dns_head; 447 rs->ds_pos = ctx->dns_head;
452 GNUNET_assert (NULL != ds); 448 GNUNET_assert(NULL != ds);
453 dnsout = NULL; 449 dnsout = NULL;
454 switch (ds->ss.ss_family) 450 switch (ds->ss.ss_family)
455 { 451 {
456 case AF_INET: 452 case AF_INET:
457 if (NULL == rs->dnsout4) 453 if (NULL == rs->dnsout4)
458 rs->dnsout4 = open_socket (AF_INET); 454 rs->dnsout4 = open_socket(AF_INET);
459 dnsout = rs->dnsout4; 455 dnsout = rs->dnsout4;
460 sa = (const struct sockaddr *) &ds->ss; 456 sa = (const struct sockaddr *)&ds->ss;
461 salen = sizeof (struct sockaddr_in); 457 salen = sizeof(struct sockaddr_in);
462 break; 458 break;
463 case AF_INET6: 459
464 if (NULL == rs->dnsout6) 460 case AF_INET6:
465 rs->dnsout6 = open_socket (AF_INET6); 461 if (NULL == rs->dnsout6)
466 dnsout = rs->dnsout6; 462 rs->dnsout6 = open_socket(AF_INET6);
467 sa = (const struct sockaddr *) &ds->ss; 463 dnsout = rs->dnsout6;
468 salen = sizeof (struct sockaddr_in6); 464 sa = (const struct sockaddr *)&ds->ss;
469 break; 465 salen = sizeof(struct sockaddr_in6);
470 default: 466 break;
471 return; 467
472 } 468 default:
469 return;
470 }
473 if (NULL == dnsout) 471 if (NULL == dnsout)
474 { 472 {
475 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 473 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
476 "Unable to use configure DNS server, skipping\n"); 474 "Unable to use configure DNS server, skipping\n");
477 return; 475 return;
478 } 476 }
479 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_sendto (dnsout, 477 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_sendto(dnsout,
480 rs->request, 478 rs->request,
481 rs->request_len, 479 rs->request_len,
482 sa, 480 sa,
483 salen)) 481 salen))
484 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 482 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
485 _ ("Failed to send DNS request to %s: %s\n"), 483 _("Failed to send DNS request to %s: %s\n"),
486 GNUNET_a2s (sa, salen), 484 GNUNET_a2s(sa, salen),
487 strerror (errno)); 485 strerror(errno));
488 else 486 else
489 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 487 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
490 _ ("Sent DNS request to %s\n"), 488 _("Sent DNS request to %s\n"),
491 GNUNET_a2s (sa, salen)); 489 GNUNET_a2s(sa, salen));
492 schedule_read (rs); 490 schedule_read(rs);
493} 491}
494 492
495 493
@@ -504,32 +502,32 @@ transmit_query (void *cls)
504 * @return socket used for the request, NULL on error 502 * @return socket used for the request, NULL on error
505 */ 503 */
506struct GNUNET_DNSSTUB_RequestSocket * 504struct GNUNET_DNSSTUB_RequestSocket *
507GNUNET_DNSSTUB_resolve (struct GNUNET_DNSSTUB_Context *ctx, 505GNUNET_DNSSTUB_resolve(struct GNUNET_DNSSTUB_Context *ctx,
508 const void *request, 506 const void *request,
509 size_t request_len, 507 size_t request_len,
510 GNUNET_DNSSTUB_ResultCallback rc, 508 GNUNET_DNSSTUB_ResultCallback rc,
511 void *rc_cls) 509 void *rc_cls)
512{ 510{
513 struct GNUNET_DNSSTUB_RequestSocket *rs; 511 struct GNUNET_DNSSTUB_RequestSocket *rs;
514 512
515 if (NULL == ctx->dns_head) 513 if (NULL == ctx->dns_head)
516 { 514 {
517 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 515 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
518 "No DNS server configured for resolution\n"); 516 "No DNS server configured for resolution\n");
519 return NULL; 517 return NULL;
520 } 518 }
521 if (NULL == (rs = get_request_socket (ctx))) 519 if (NULL == (rs = get_request_socket(ctx)))
522 { 520 {
523 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 521 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
524 "No request socket available for DNS resolution\n"); 522 "No request socket available for DNS resolution\n");
525 return NULL; 523 return NULL;
526 } 524 }
527 rs->ds_pos = ctx->dns_head; 525 rs->ds_pos = ctx->dns_head;
528 rs->rc = rc; 526 rs->rc = rc;
529 rs->rc_cls = rc_cls; 527 rs->rc_cls = rc_cls;
530 rs->request = GNUNET_memdup (request, request_len); 528 rs->request = GNUNET_memdup(request, request_len);
531 rs->request_len = request_len; 529 rs->request_len = request_len;
532 rs->retry_task = GNUNET_SCHEDULER_add_now (&transmit_query, rs); 530 rs->retry_task = GNUNET_SCHEDULER_add_now(&transmit_query, rs);
533 return rs; 531 return rs;
534} 532}
535 533
@@ -540,19 +538,19 @@ GNUNET_DNSSTUB_resolve (struct GNUNET_DNSSTUB_Context *ctx,
540 * @param rs resolution to cancel 538 * @param rs resolution to cancel
541 */ 539 */
542void 540void
543GNUNET_DNSSTUB_resolve_cancel (struct GNUNET_DNSSTUB_RequestSocket *rs) 541GNUNET_DNSSTUB_resolve_cancel(struct GNUNET_DNSSTUB_RequestSocket *rs)
544{ 542{
545 rs->rc = NULL; 543 rs->rc = NULL;
546 if (NULL != rs->retry_task) 544 if (NULL != rs->retry_task)
547 { 545 {
548 GNUNET_SCHEDULER_cancel (rs->retry_task); 546 GNUNET_SCHEDULER_cancel(rs->retry_task);
549 rs->retry_task = NULL; 547 rs->retry_task = NULL;
550 } 548 }
551 if (NULL != rs->read_task) 549 if (NULL != rs->read_task)
552 { 550 {
553 GNUNET_SCHEDULER_cancel (rs->read_task); 551 GNUNET_SCHEDULER_cancel(rs->read_task);
554 rs->read_task = NULL; 552 rs->read_task = NULL;
555 } 553 }
556} 554}
557 555
558 556
@@ -564,19 +562,19 @@ GNUNET_DNSSTUB_resolve_cancel (struct GNUNET_DNSSTUB_RequestSocket *rs)
564 * @return NULL on error 562 * @return NULL on error
565 */ 563 */
566struct GNUNET_DNSSTUB_Context * 564struct GNUNET_DNSSTUB_Context *
567GNUNET_DNSSTUB_start (unsigned int num_sockets) 565GNUNET_DNSSTUB_start(unsigned int num_sockets)
568{ 566{
569 struct GNUNET_DNSSTUB_Context *ctx; 567 struct GNUNET_DNSSTUB_Context *ctx;
570 568
571 if (0 == num_sockets) 569 if (0 == num_sockets)
572 { 570 {
573 GNUNET_break (0); 571 GNUNET_break(0);
574 return NULL; 572 return NULL;
575 } 573 }
576 ctx = GNUNET_new (struct GNUNET_DNSSTUB_Context); 574 ctx = GNUNET_new(struct GNUNET_DNSSTUB_Context);
577 ctx->num_sockets = num_sockets; 575 ctx->num_sockets = num_sockets;
578 ctx->sockets = 576 ctx->sockets =
579 GNUNET_new_array (num_sockets, struct GNUNET_DNSSTUB_RequestSocket); 577 GNUNET_new_array(num_sockets, struct GNUNET_DNSSTUB_RequestSocket);
580 ctx->retry_freq = DNS_RETRANSMIT_DELAY; 578 ctx->retry_freq = DNS_RETRANSMIT_DELAY;
581 return ctx; 579 return ctx;
582} 580}
@@ -591,45 +589,45 @@ GNUNET_DNSSTUB_start (unsigned int num_sockets)
591 * @return #GNUNET_OK on success 589 * @return #GNUNET_OK on success
592 */ 590 */
593int 591int
594GNUNET_DNSSTUB_add_dns_ip (struct GNUNET_DNSSTUB_Context *ctx, 592GNUNET_DNSSTUB_add_dns_ip(struct GNUNET_DNSSTUB_Context *ctx,
595 const char *dns_ip) 593 const char *dns_ip)
596{ 594{
597 struct DnsServer *ds; 595 struct DnsServer *ds;
598 struct in_addr i4; 596 struct in_addr i4;
599 struct in6_addr i6; 597 struct in6_addr i6;
600 598
601 ds = GNUNET_new (struct DnsServer); 599 ds = GNUNET_new(struct DnsServer);
602 if (1 == inet_pton (AF_INET, dns_ip, &i4)) 600 if (1 == inet_pton(AF_INET, dns_ip, &i4))
603 { 601 {
604 struct sockaddr_in *s4 = (struct sockaddr_in *) &ds->ss; 602 struct sockaddr_in *s4 = (struct sockaddr_in *)&ds->ss;
605 603
606 s4->sin_family = AF_INET; 604 s4->sin_family = AF_INET;
607 s4->sin_port = htons (53); 605 s4->sin_port = htons(53);
608 s4->sin_addr = i4; 606 s4->sin_addr = i4;
609#if HAVE_SOCKADDR_IN_SIN_LEN 607#if HAVE_SOCKADDR_IN_SIN_LEN
610 s4->sin_len = (u_char) sizeof (struct sockaddr_in); 608 s4->sin_len = (u_char)sizeof(struct sockaddr_in);
611#endif 609#endif
612 } 610 }
613 else if (1 == inet_pton (AF_INET6, dns_ip, &i6)) 611 else if (1 == inet_pton(AF_INET6, dns_ip, &i6))
614 { 612 {
615 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *) &ds->ss; 613 struct sockaddr_in6 *s6 = (struct sockaddr_in6 *)&ds->ss;
616 614
617 s6->sin6_family = AF_INET6; 615 s6->sin6_family = AF_INET6;
618 s6->sin6_port = htons (53); 616 s6->sin6_port = htons(53);
619 s6->sin6_addr = i6; 617 s6->sin6_addr = i6;
620#if HAVE_SOCKADDR_IN_SIN_LEN 618#if HAVE_SOCKADDR_IN_SIN_LEN
621 s6->sin6_len = (u_char) sizeof (struct sockaddr_in6); 619 s6->sin6_len = (u_char)sizeof(struct sockaddr_in6);
622#endif 620#endif
623 } 621 }
624 else 622 else
625 { 623 {
626 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 624 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
627 "Malformed IP address `%s' for DNS server\n", 625 "Malformed IP address `%s' for DNS server\n",
628 dns_ip); 626 dns_ip);
629 GNUNET_free (ds); 627 GNUNET_free(ds);
630 return GNUNET_SYSERR; 628 return GNUNET_SYSERR;
631 } 629 }
632 GNUNET_CONTAINER_DLL_insert (ctx->dns_head, ctx->dns_tail, ds); 630 GNUNET_CONTAINER_DLL_insert(ctx->dns_head, ctx->dns_tail, ds);
633 return GNUNET_OK; 631 return GNUNET_OK;
634} 632}
635 633
@@ -643,26 +641,28 @@ GNUNET_DNSSTUB_add_dns_ip (struct GNUNET_DNSSTUB_Context *ctx,
643 * @return #GNUNET_OK on success 641 * @return #GNUNET_OK on success
644 */ 642 */
645int 643int
646GNUNET_DNSSTUB_add_dns_sa (struct GNUNET_DNSSTUB_Context *ctx, 644GNUNET_DNSSTUB_add_dns_sa(struct GNUNET_DNSSTUB_Context *ctx,
647 const struct sockaddr *sa) 645 const struct sockaddr *sa)
648{ 646{
649 struct DnsServer *ds; 647 struct DnsServer *ds;
650 648
651 ds = GNUNET_new (struct DnsServer); 649 ds = GNUNET_new(struct DnsServer);
652 switch (sa->sa_family) 650 switch (sa->sa_family)
653 { 651 {
654 case AF_INET: 652 case AF_INET:
655 GNUNET_memcpy (&ds->ss, sa, sizeof (struct sockaddr_in)); 653 GNUNET_memcpy(&ds->ss, sa, sizeof(struct sockaddr_in));
656 break; 654 break;
657 case AF_INET6: 655
658 GNUNET_memcpy (&ds->ss, sa, sizeof (struct sockaddr_in6)); 656 case AF_INET6:
659 break; 657 GNUNET_memcpy(&ds->ss, sa, sizeof(struct sockaddr_in6));
660 default: 658 break;
661 GNUNET_break (0); 659
662 GNUNET_free (ds); 660 default:
663 return GNUNET_SYSERR; 661 GNUNET_break(0);
664 } 662 GNUNET_free(ds);
665 GNUNET_CONTAINER_DLL_insert (ctx->dns_head, ctx->dns_tail, ds); 663 return GNUNET_SYSERR;
664 }
665 GNUNET_CONTAINER_DLL_insert(ctx->dns_head, ctx->dns_tail, ds);
666 return GNUNET_OK; 666 return GNUNET_OK;
667} 667}
668 668
@@ -675,8 +675,8 @@ GNUNET_DNSSTUB_add_dns_sa (struct GNUNET_DNSSTUB_Context *ctx,
675 * @param retry_freq how long to wait between retries 675 * @param retry_freq how long to wait between retries
676 */ 676 */
677void 677void
678GNUNET_DNSSTUB_set_retry (struct GNUNET_DNSSTUB_Context *ctx, 678GNUNET_DNSSTUB_set_retry(struct GNUNET_DNSSTUB_Context *ctx,
679 struct GNUNET_TIME_Relative retry_freq) 679 struct GNUNET_TIME_Relative retry_freq)
680{ 680{
681 ctx->retry_freq = retry_freq; 681 ctx->retry_freq = retry_freq;
682} 682}
@@ -688,19 +688,19 @@ GNUNET_DNSSTUB_set_retry (struct GNUNET_DNSSTUB_Context *ctx,
688 * @param ctx stub resolver to clean up 688 * @param ctx stub resolver to clean up
689 */ 689 */
690void 690void
691GNUNET_DNSSTUB_stop (struct GNUNET_DNSSTUB_Context *ctx) 691GNUNET_DNSSTUB_stop(struct GNUNET_DNSSTUB_Context *ctx)
692{ 692{
693 struct DnsServer *ds; 693 struct DnsServer *ds;
694 694
695 while (NULL != (ds = ctx->dns_head)) 695 while (NULL != (ds = ctx->dns_head))
696 { 696 {
697 GNUNET_CONTAINER_DLL_remove (ctx->dns_head, ctx->dns_tail, ds); 697 GNUNET_CONTAINER_DLL_remove(ctx->dns_head, ctx->dns_tail, ds);
698 GNUNET_free (ds); 698 GNUNET_free(ds);
699 } 699 }
700 for (unsigned int i = 0; i < ctx->num_sockets; i++) 700 for (unsigned int i = 0; i < ctx->num_sockets; i++)
701 cleanup_rs (&ctx->sockets[i]); 701 cleanup_rs(&ctx->sockets[i]);
702 GNUNET_free (ctx->sockets); 702 GNUNET_free(ctx->sockets);
703 GNUNET_free (ctx); 703 GNUNET_free(ctx);
704} 704}
705 705
706 706
diff --git a/src/util/getopt.c b/src/util/getopt.c
index 678e2a61f..19b160cc9 100644
--- a/src/util/getopt.c
+++ b/src/util/getopt.c
@@ -6,28 +6,28 @@
6 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97 6 Copyright (C) 1987, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97
7 Free Software Foundation, Inc. 7 Free Software Foundation, Inc.
8 8
9NOTE: The canonical source of this file is maintained with the GNU C Library. 9 NOTE: The canonical source of this file is maintained with the GNU C Library.
10Bugs can be reported to bug-glibc@prep.ai.mit.edu. 10 Bugs can be reported to bug-glibc@prep.ai.mit.edu.
11 11
12This program is free software; you can redistribute it and/or modify it 12 This program is free software; you can redistribute it and/or modify it
13under the terms of the GNU General Public License as published by the 13 under the terms of the GNU General Public License as published by the
14Free Software Foundation; either version 3, or (at your option) any 14 Free Software Foundation; either version 3, or (at your option) any
15later version. 15 later version.
16 16
17This program is distributed in the hope that it will be useful, 17 This program is distributed in the hope that it will be useful,
18but WITHOUT ANY WARRANTY; without even the implied warranty of 18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20GNU General Public License for more details. 20 GNU General Public License for more details.
21 21
22You should have received a copy of the GNU General Public License 22 You should have received a copy of the GNU General Public License
23along with this program; if not, write to the Free Software 23 along with this program; if not, write to the Free Software
24Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
25USA. 25 USA.
26 26
27 27
28This code was heavily modified for GNUnet. 28 This code was heavily modified for GNUnet.
29Copyright (C) 2006, 2017 Christian Grothoff 29 Copyright (C) 2006, 2017 Christian Grothoff
30*/ 30 */
31 31
32/** 32/**
33 * @file util/getopt.c 33 * @file util/getopt.c
@@ -47,15 +47,15 @@ Copyright (C) 2006, 2017 Christian Grothoff
47#endif 47#endif
48#endif 48#endif
49 49
50#define LOG(kind, ...) GNUNET_log_from (kind, "util-getopt", __VA_ARGS__) 50#define LOG(kind, ...) GNUNET_log_from(kind, "util-getopt", __VA_ARGS__)
51 51
52#define LOG_STRERROR(kind, syscall) \ 52#define LOG_STRERROR(kind, syscall) \
53 GNUNET_log_from_strerror (kind, "util-getopt", syscall) 53 GNUNET_log_from_strerror(kind, "util-getopt", syscall)
54 54
55#if defined(WIN32) && ! defined(__CYGWIN32__) 55#if defined(WIN32) && !defined(__CYGWIN32__)
56/* It's not Unix, really. See? Capital letters. */ 56/* It's not Unix, really. See? Capital letters. */
57#include <windows.h> 57#include <windows.h>
58#define getpid() GetCurrentProcessId () 58#define getpid() GetCurrentProcessId()
59#endif 59#endif
60 60
61#ifndef _ 61#ifndef _
@@ -63,7 +63,7 @@ Copyright (C) 2006, 2017 Christian Grothoff
63 When compiling libc, the _ macro is predefined. */ 63 When compiling libc, the _ macro is predefined. */
64#ifdef HAVE_LIBINTL_H 64#ifdef HAVE_LIBINTL_H
65#include <libintl.h> 65#include <libintl.h>
66#define _(msgid) gettext (msgid) 66#define _(msgid) gettext(msgid)
67#else 67#else
68#define _(msgid) (msgid) 68#define _(msgid) (msgid)
69#endif 69#endif
@@ -75,7 +75,7 @@ Copyright (C) 2006, 2017 Christian Grothoff
75 zero. 75 zero.
76 76
77 The field `has_arg' is: 77 The field `has_arg' is:
78 no_argument (or 0) if the option does not take an argument, 78 no_argument (or 0) if the option does not take an argument,
79 required_argument (or 1) if the option requires an argument, 79 required_argument (or 1) if the option requires an argument,
80 optional_argument (or 2) if the option takes an optional argument. 80 optional_argument (or 2) if the option takes an optional argument.
81 81
@@ -90,8 +90,7 @@ Copyright (C) 2006, 2017 Christian Grothoff
90 one). For long options that have a zero `flag' field, `getopt' 90 one). For long options that have a zero `flag' field, `getopt'
91 returns the contents of the `val' field. */ 91 returns the contents of the `val' field. */
92 92
93struct GNoption 93struct GNoption {
94{
95 const char *name; 94 const char *name;
96 /* has_arg can't be an enum because some compilers complain about 95 /* has_arg can't be an enum because some compilers complain about
97 * type mismatches in all the code that assumes it is an int. */ 96 * type mismatches in all the code that assumes it is an int. */
@@ -195,17 +194,17 @@ static char *posixly_correct;
195 whose names are inconsistent. */ 194 whose names are inconsistent. */
196 195
197char * 196char *
198getenv (); 197getenv();
199 198
200static char * 199static char *
201my_index (const char *str, int chr) 200my_index(const char *str, int chr)
202{ 201{
203 while (*str) 202 while (*str)
204 { 203 {
205 if (*str == chr) 204 if (*str == chr)
206 return (char *) str; 205 return (char *)str;
207 str++; 206 str++;
208 } 207 }
209 return 0; 208 return 0;
210} 209}
211 210
@@ -214,11 +213,11 @@ my_index (const char *str, int chr)
214#ifdef __GNUC__ 213#ifdef __GNUC__
215/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. 214/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h.
216 That was relevant to code that was here before. */ 215 That was relevant to code that was here before. */
217#if ! defined(__STDC__) || ! __STDC__ 216#if !defined(__STDC__) || !__STDC__
218/* gcc with -traditional declares the built-in strlen to return int, 217/* gcc with -traditional declares the built-in strlen to return int,
219 and has done so at least since version 2.4.5. -- rms. */ 218 and has done so at least since version 2.4.5. -- rms. */
220extern int 219extern int
221strlen (const char *); 220strlen(const char *);
222#endif /* not __STDC__ */ 221#endif /* not __STDC__ */
223#endif /* __GNUC__ */ 222#endif /* __GNUC__ */
224 223
@@ -246,11 +245,11 @@ static int last_nonopt;
246 245
247#if defined(__STDC__) && __STDC__ 246#if defined(__STDC__) && __STDC__
248static void 247static void
249exchange (char **); 248exchange(char **);
250#endif 249#endif
251 250
252static void 251static void
253exchange (char **argv) 252exchange(char **argv)
254{ 253{
255 int bottom = first_nonopt; 254 int bottom = first_nonopt;
256 int middle = last_nonopt; 255 int middle = last_nonopt;
@@ -263,42 +262,42 @@ exchange (char **argv)
263 * but it consists of two parts that need to be swapped next. */ 262 * but it consists of two parts that need to be swapped next. */
264 263
265 while (top > middle && middle > bottom) 264 while (top > middle && middle > bottom)
266 {
267 if (top - middle > middle - bottom)
268 { 265 {
269 /* Bottom segment is the short one. */ 266 if (top - middle > middle - bottom)
270 int len = middle - bottom; 267 {
271 register int i; 268 /* Bottom segment is the short one. */
269 int len = middle - bottom;
270 register int i;
272 271
273 /* Swap it with the top part of the top segment. */ 272 /* Swap it with the top part of the top segment. */
274 for (i = 0; i < len; i++) 273 for (i = 0; i < len; i++)
275 { 274 {
276 tem = argv[bottom + i]; 275 tem = argv[bottom + i];
277 argv[bottom + i] = argv[top - (middle - bottom) + i]; 276 argv[bottom + i] = argv[top - (middle - bottom) + i];
278 argv[top - (middle - bottom) + i] = tem; 277 argv[top - (middle - bottom) + i] = tem;
279 SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); 278 SWAP_FLAGS(bottom + i, top - (middle - bottom) + i);
280 } 279 }
281 /* Exclude the moved bottom segment from further swapping. */ 280 /* Exclude the moved bottom segment from further swapping. */
282 top -= len; 281 top -= len;
283 } 282 }
284 else 283 else
285 { 284 {
286 /* Top segment is the short one. */ 285 /* Top segment is the short one. */
287 int len = top - middle; 286 int len = top - middle;
288 register int i; 287 register int i;
289 288
290 /* Swap it with the bottom part of the bottom segment. */ 289 /* Swap it with the bottom part of the bottom segment. */
291 for (i = 0; i < len; i++) 290 for (i = 0; i < len; i++)
292 { 291 {
293 tem = argv[bottom + i]; 292 tem = argv[bottom + i];
294 argv[bottom + i] = argv[middle + i]; 293 argv[bottom + i] = argv[middle + i];
295 argv[middle + i] = tem; 294 argv[middle + i] = tem;
296 SWAP_FLAGS (bottom + i, middle + i); 295 SWAP_FLAGS(bottom + i, middle + i);
297 } 296 }
298 /* Exclude the moved top segment from further swapping. */ 297 /* Exclude the moved top segment from further swapping. */
299 bottom += len; 298 bottom += len;
299 }
300 } 300 }
301 }
302 301
303 /* Update records for the slots the non-options now occupy. */ 302 /* Update records for the slots the non-options now occupy. */
304 303
@@ -310,10 +309,10 @@ exchange (char **argv)
310 309
311#if defined(__STDC__) && __STDC__ 310#if defined(__STDC__) && __STDC__
312static const char * 311static const char *
313_getopt_initialize (int, char *const *, const char *); 312_getopt_initialize(int, char *const *, const char *);
314#endif 313#endif
315static const char * 314static const char *
316_getopt_initialize (int argc, char *const *argv, const char *optstring) 315_getopt_initialize(int argc, char *const *argv, const char *optstring)
317{ 316{
318 /* Start processing options with ARGV-element 1 (since ARGV-element 0 317 /* Start processing options with ARGV-element 1 (since ARGV-element 0
319 * is the program name); the sequence of previously skipped 318 * is the program name); the sequence of previously skipped
@@ -323,20 +322,20 @@ _getopt_initialize (int argc, char *const *argv, const char *optstring)
323 322
324 nextchar = NULL; 323 nextchar = NULL;
325 324
326 posixly_correct = getenv ("POSIXLY_CORRECT"); 325 posixly_correct = getenv("POSIXLY_CORRECT");
327 326
328 /* Determine how to handle the ordering of options and nonoptions. */ 327 /* Determine how to handle the ordering of options and nonoptions. */
329 328
330 if (optstring[0] == '-') 329 if (optstring[0] == '-')
331 { 330 {
332 ordering = RETURN_IN_ORDER; 331 ordering = RETURN_IN_ORDER;
333 ++optstring; 332 ++optstring;
334 } 333 }
335 else if (optstring[0] == '+') 334 else if (optstring[0] == '+')
336 { 335 {
337 ordering = REQUIRE_ORDER; 336 ordering = REQUIRE_ORDER;
338 ++optstring; 337 ++optstring;
339 } 338 }
340 else if (posixly_correct != NULL) 339 else if (posixly_correct != NULL)
341 ordering = REQUIRE_ORDER; 340 ordering = REQUIRE_ORDER;
342 else 341 else
@@ -402,25 +401,25 @@ _getopt_initialize (int argc, char *const *argv, const char *optstring)
402 long-named options. */ 401 long-named options. */
403 402
404static int 403static int
405GN_getopt_internal (int argc, 404GN_getopt_internal(int argc,
406 char *const *argv, 405 char *const *argv,
407 const char *optstring, 406 const char *optstring,
408 const struct GNoption *longopts, 407 const struct GNoption *longopts,
409 int *longind, 408 int *longind,
410 int long_only) 409 int long_only)
411{ 410{
412 static int __getopt_initialized = 0; 411 static int __getopt_initialized = 0;
413 static int GNopterr = 1; 412 static int GNopterr = 1;
414 413
415 GNoptarg = NULL; 414 GNoptarg = NULL;
416 415
417 if (GNoptind == 0 || ! __getopt_initialized) 416 if (GNoptind == 0 || !__getopt_initialized)
418 { 417 {
419 if (GNoptind == 0) 418 if (GNoptind == 0)
420 GNoptind = 1; /* Don't scan ARGV[0], the program name. */ 419 GNoptind = 1; /* Don't scan ARGV[0], the program name. */
421 optstring = _getopt_initialize (argc, argv, optstring); 420 optstring = _getopt_initialize(argc, argv, optstring);
422 __getopt_initialized = 1; 421 __getopt_initialized = 1;
423 } 422 }
424 423
425 /* Test whether ARGV[GNoptind] points to a non-option argument. 424 /* Test whether ARGV[GNoptind] points to a non-option argument.
426 * Either it does not have option syntax, or there is an environment flag 425 * Either it does not have option syntax, or there is an environment flag
@@ -429,80 +428,80 @@ GN_getopt_internal (int argc,
429#define NONOPTION_P (argv[GNoptind][0] != '-' || argv[GNoptind][1] == '\0') 428#define NONOPTION_P (argv[GNoptind][0] != '-' || argv[GNoptind][1] == '\0')
430 429
431 if (nextchar == NULL || *nextchar == '\0') 430 if (nextchar == NULL || *nextchar == '\0')
432 {
433 /* Advance to the next ARGV-element. */
434
435 /* Give FIRST_NONOPT & LAST_NONOPT rational values if GNoptind has been
436 * moved back by the user (who may also have changed the arguments). */
437 if (last_nonopt > GNoptind)
438 last_nonopt = GNoptind;
439 if (first_nonopt > GNoptind)
440 first_nonopt = GNoptind;
441
442 if (ordering == PERMUTE)
443 { 431 {
444 /* If we have just processed some options following some non-options, 432 /* Advance to the next ARGV-element. */
445 * exchange them so that the options come first. */
446 433
447 if (first_nonopt != last_nonopt && last_nonopt != GNoptind) 434 /* Give FIRST_NONOPT & LAST_NONOPT rational values if GNoptind has been
448 exchange ((char **) argv); 435 * moved back by the user (who may also have changed the arguments). */
449 else if (last_nonopt != GNoptind) 436 if (last_nonopt > GNoptind)
437 last_nonopt = GNoptind;
438 if (first_nonopt > GNoptind)
450 first_nonopt = GNoptind; 439 first_nonopt = GNoptind;
451 440
452 /* Skip any additional non-options 441 if (ordering == PERMUTE)
453 * and extend the range of non-options previously skipped. */ 442 {
443 /* If we have just processed some options following some non-options,
444 * exchange them so that the options come first. */
454 445
455 while (GNoptind < argc && NONOPTION_P) 446 if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
456 GNoptind++; 447 exchange((char **)argv);
457 last_nonopt = GNoptind; 448 else if (last_nonopt != GNoptind)
458 } 449 first_nonopt = GNoptind;
459 450
460 /* The special ARGV-element `--' means premature end of options. 451 /* Skip any additional non-options
461 * Skip it like a null option, 452 * and extend the range of non-options previously skipped. */
462 * then exchange with previous non-options as if it were an option,
463 * then skip everything else like a non-option. */
464 if (GNoptind != argc && ! strcmp (argv[GNoptind], "--"))
465 {
466 GNoptind++;
467 453
468 if (first_nonopt != last_nonopt && last_nonopt != GNoptind) 454 while (GNoptind < argc && NONOPTION_P)
469 exchange ((char **) argv); 455 GNoptind++;
470 else if (first_nonopt == last_nonopt) 456 last_nonopt = GNoptind;
471 first_nonopt = GNoptind; 457 }
472 last_nonopt = argc;
473 458
474 GNoptind = argc; 459 /* The special ARGV-element `--' means premature end of options.
475 } 460 * Skip it like a null option,
461 * then exchange with previous non-options as if it were an option,
462 * then skip everything else like a non-option. */
463 if (GNoptind != argc && !strcmp(argv[GNoptind], "--"))
464 {
465 GNoptind++;
476 466
477 /* If we have done all the ARGV-elements, stop the scan 467 if (first_nonopt != last_nonopt && last_nonopt != GNoptind)
478 * and back over any non-options that we skipped and permuted. */ 468 exchange((char **)argv);
469 else if (first_nonopt == last_nonopt)
470 first_nonopt = GNoptind;
471 last_nonopt = argc;
479 472
480 if (GNoptind == argc) 473 GNoptind = argc;
481 { 474 }
482 /* Set the next-arg-index to point at the non-options
483 * that we previously skipped, so the caller will digest them. */
484 if (first_nonopt != last_nonopt)
485 GNoptind = first_nonopt;
486 return -1;
487 }
488 475
489 /* If we have come to a non-option and did not permute it, 476 /* If we have done all the ARGV-elements, stop the scan
490 * either stop the scan or describe it to the caller and pass it by. */ 477 * and back over any non-options that we skipped and permuted. */
491 478
492 if (NONOPTION_P) 479 if (GNoptind == argc)
493 { 480 {
494 if (ordering == REQUIRE_ORDER) 481 /* Set the next-arg-index to point at the non-options
495 return -1; 482 * that we previously skipped, so the caller will digest them. */
496 GNoptarg = argv[GNoptind++]; 483 if (first_nonopt != last_nonopt)
497 return 1; 484 GNoptind = first_nonopt;
498 } 485 return -1;
486 }
499 487
500 /* We have found another option-ARGV-element. 488 /* If we have come to a non-option and did not permute it,
501 * Skip the initial punctuation. */ 489 * either stop the scan or describe it to the caller and pass it by. */
502 490
503 nextchar = 491 if (NONOPTION_P)
504 (argv[GNoptind] + 1 + (longopts != NULL && argv[GNoptind][1] == '-')); 492 {
505 } 493 if (ordering == REQUIRE_ORDER)
494 return -1;
495 GNoptarg = argv[GNoptind++];
496 return 1;
497 }
498
499 /* We have found another option-ARGV-element.
500 * Skip the initial punctuation. */
501
502 nextchar =
503 (argv[GNoptind] + 1 + (longopts != NULL && argv[GNoptind][1] == '-'));
504 }
506 505
507 /* Decode the current option-ARGV-element. */ 506 /* Decode the current option-ARGV-element. */
508 507
@@ -522,359 +521,359 @@ GN_getopt_internal (int argc,
522 if (longopts != NULL && 521 if (longopts != NULL &&
523 (argv[GNoptind][1] == '-' || 522 (argv[GNoptind][1] == '-' ||
524 (long_only && 523 (long_only &&
525 (argv[GNoptind][2] || ! my_index (optstring, argv[GNoptind][1]))))) 524 (argv[GNoptind][2] || !my_index(optstring, argv[GNoptind][1])))))
526 {
527 char *nameend;
528 const struct GNoption *p;
529 const struct GNoption *pfound = NULL;
530 int exact = 0;
531 int ambig = 0;
532 int indfound = -1;
533 int option_index;
534
535 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
536 /* Do nothing. */;
537
538 /* Test all long options for either exact match
539 * or abbreviated matches. */
540 for (p = longopts, option_index = 0; p->name; p++, option_index++)
541 if (! strncmp (p->name, nextchar, nameend - nextchar))
542 {
543 if ((unsigned int) (nameend - nextchar) ==
544 (unsigned int) strlen (p->name))
545 {
546 /* Exact match found. */
547 pfound = p;
548 indfound = option_index;
549 exact = 1;
550 break;
551 }
552 else if (pfound == NULL)
553 {
554 /* First nonexact match found. */
555 pfound = p;
556 indfound = option_index;
557 }
558 else
559 /* Second or later nonexact match found. */
560 ambig = 1;
561 }
562
563 if (ambig && ! exact)
564 { 525 {
565 if (GNopterr) 526 char *nameend;
566 fprintf (stderr, 527 const struct GNoption *p;
567 _ ("%s: option `%s' is ambiguous\n"), 528 const struct GNoption *pfound = NULL;
568 argv[0], 529 int exact = 0;
569 argv[GNoptind]); 530 int ambig = 0;
570 nextchar += strlen (nextchar); 531 int indfound = -1;
571 GNoptind++; 532 int option_index;
572 return '?';
573 }
574 533
575 if (pfound != NULL) 534 for (nameend = nextchar; *nameend && *nameend != '='; nameend++)
576 { 535 /* Do nothing. */;
577 option_index = indfound; 536
578 GNoptind++; 537 /* Test all long options for either exact match
579 if (*nameend) 538 * or abbreviated matches. */
580 { 539 for (p = longopts, option_index = 0; p->name; p++, option_index++)
581 /* Don't test has_arg with >, because some C compilers don't 540 if (!strncmp(p->name, nextchar, nameend - nextchar))
582 * allow it to be used on enums. */
583 if (pfound->has_arg)
584 GNoptarg = nameend + 1;
585 else
586 {
587 if (GNopterr)
588 { 541 {
589 if (argv[GNoptind - 1][1] == '-') 542 if ((unsigned int)(nameend - nextchar) ==
590 /* --option */ 543 (unsigned int)strlen(p->name))
591 fprintf (stderr, 544 {
592 _ ("%s: option `--%s' does not allow an argument\n"), 545 /* Exact match found. */
593 argv[0], 546 pfound = p;
594 pfound->name); 547 indfound = option_index;
548 exact = 1;
549 break;
550 }
551 else if (pfound == NULL)
552 {
553 /* First nonexact match found. */
554 pfound = p;
555 indfound = option_index;
556 }
595 else 557 else
596 /* +option or -option */ 558 /* Second or later nonexact match found. */
597 fprintf (stderr, 559 ambig = 1;
598 _ ("%s: option `%c%s' does not allow an argument\n"),
599 argv[0],
600 argv[GNoptind - 1][0],
601 pfound->name);
602 } 560 }
603 nextchar += strlen (nextchar); 561
562 if (ambig && !exact)
563 {
564 if (GNopterr)
565 fprintf(stderr,
566 _("%s: option `%s' is ambiguous\n"),
567 argv[0],
568 argv[GNoptind]);
569 nextchar += strlen(nextchar);
570 GNoptind++;
604 return '?'; 571 return '?';
605 } 572 }
606 } 573
607 else if (pfound->has_arg == 1) 574 if (pfound != NULL)
608 {
609 if (GNoptind < argc)
610 { 575 {
611 GNoptarg = argv[GNoptind++]; 576 option_index = indfound;
577 GNoptind++;
578 if (*nameend)
579 {
580 /* Don't test has_arg with >, because some C compilers don't
581 * allow it to be used on enums. */
582 if (pfound->has_arg)
583 GNoptarg = nameend + 1;
584 else
585 {
586 if (GNopterr)
587 {
588 if (argv[GNoptind - 1][1] == '-')
589 /* --option */
590 fprintf(stderr,
591 _("%s: option `--%s' does not allow an argument\n"),
592 argv[0],
593 pfound->name);
594 else
595 /* +option or -option */
596 fprintf(stderr,
597 _("%s: option `%c%s' does not allow an argument\n"),
598 argv[0],
599 argv[GNoptind - 1][0],
600 pfound->name);
601 }
602 nextchar += strlen(nextchar);
603 return '?';
604 }
605 }
606 else if (pfound->has_arg == 1)
607 {
608 if (GNoptind < argc)
609 {
610 GNoptarg = argv[GNoptind++];
611 }
612 else
613 {
614 if (GNopterr)
615 {
616 fprintf(stderr,
617 _("%s: option `%s' requires an argument\n"),
618 argv[0],
619 argv[GNoptind - 1]);
620 }
621 nextchar += strlen(nextchar);
622 return (optstring[0] == ':') ? ':' : '?';
623 }
624 }
625 nextchar += strlen(nextchar);
626 if (longind != NULL)
627 *longind = option_index;
628 if (pfound->flag)
629 {
630 *(pfound->flag) = pfound->val;
631 return 0;
632 }
633 return pfound->val;
612 } 634 }
613 else 635
636 /* Can't find it as a long option. If this is not getopt_long_only,
637 * or the option starts with '--' or is not a valid short
638 * option, then it's an error.
639 * Otherwise interpret it as a short option. */
640 if (!long_only || argv[GNoptind][1] == '-' ||
641 my_index(optstring, *nextchar) == NULL)
614 { 642 {
615 if (GNopterr) 643 if (GNopterr)
616 { 644 {
617 fprintf (stderr, 645 if (argv[GNoptind][1] == '-')
618 _ ("%s: option `%s' requires an argument\n"), 646 /* --option */
619 argv[0], 647 fprintf(stderr,
620 argv[GNoptind - 1]); 648 _("%s: unrecognized option `--%s'\n"),
621 } 649 argv[0],
622 nextchar += strlen (nextchar); 650 nextchar);
623 return (optstring[0] == ':') ? ':' : '?'; 651 else
652 /* +option or -option */
653 fprintf(stderr,
654 _("%s: unrecognized option `%c%s'\n"),
655 argv[0],
656 argv[GNoptind][0],
657 nextchar);
658 }
659 nextchar = (char *)"";
660 GNoptind++;
661 return '?';
624 } 662 }
625 }
626 nextchar += strlen (nextchar);
627 if (longind != NULL)
628 *longind = option_index;
629 if (pfound->flag)
630 {
631 *(pfound->flag) = pfound->val;
632 return 0;
633 }
634 return pfound->val;
635 } 663 }
636 664
637 /* Can't find it as a long option. If this is not getopt_long_only,
638 * or the option starts with '--' or is not a valid short
639 * option, then it's an error.
640 * Otherwise interpret it as a short option. */
641 if (! long_only || argv[GNoptind][1] == '-' ||
642 my_index (optstring, *nextchar) == NULL)
643 {
644 if (GNopterr)
645 {
646 if (argv[GNoptind][1] == '-')
647 /* --option */
648 fprintf (stderr,
649 _ ("%s: unrecognized option `--%s'\n"),
650 argv[0],
651 nextchar);
652 else
653 /* +option or -option */
654 fprintf (stderr,
655 _ ("%s: unrecognized option `%c%s'\n"),
656 argv[0],
657 argv[GNoptind][0],
658 nextchar);
659 }
660 nextchar = (char *) "";
661 GNoptind++;
662 return '?';
663 }
664 }
665
666 /* Look at and handle the next short option-character. */ 665 /* Look at and handle the next short option-character. */
667 666
668 { 667 {
669 char c = *nextchar++; 668 char c = *nextchar++;
670 char *temp = my_index (optstring, c); 669 char *temp = my_index(optstring, c);
671 670
672 /* Increment `GNoptind' when we start to process its last character. */ 671 /* Increment `GNoptind' when we start to process its last character. */
673 if (*nextchar == '\0') 672 if (*nextchar == '\0')
674 ++GNoptind; 673 ++GNoptind;
675 674
676 if (temp == NULL || c == ':') 675 if (temp == NULL || c == ':')
677 {
678 if (GNopterr)
679 {
680 if (posixly_correct)
681 /* 1003.2 specifies the format of this message. */
682 fprintf (stderr, _ ("%s: illegal option -- %c\n"), argv[0], c);
683 else
684 fprintf (stderr, _ ("%s: invalid option -- %c\n"), argv[0], c);
685 }
686 return '?';
687 }
688 /* Convenience. Treat POSIX -W foo same as long option --foo */
689 if (temp[0] == 'W' && temp[1] == ';')
690 {
691 char *nameend;
692 const struct GNoption *p;
693 const struct GNoption *pfound = NULL;
694 int exact = 0;
695 int ambig = 0;
696 int indfound = 0;
697 int option_index;
698
699 /* This is an option that requires an argument. */
700 if (*nextchar != '\0')
701 {
702 GNoptarg = nextchar;
703 /* If we end this ARGV-element by taking the rest as an arg,
704 * we must advance to the next element now. */
705 GNoptind++;
706 }
707 else if (GNoptind == argc)
708 { 676 {
709 if (GNopterr) 677 if (GNopterr)
710 {
711 /* 1003.2 specifies the format of this message. */
712 fprintf (stderr,
713 _ ("%s: option requires an argument -- %c\n"),
714 argv[0],
715 c);
716 }
717 if (optstring[0] == ':')
718 c = ':';
719 else
720 c = '?';
721 return c;
722 }
723 else
724 /* We already incremented `GNoptind' once;
725 * increment it again when taking next ARGV-elt as argument. */
726 GNoptarg = argv[GNoptind++];
727
728 /* GNoptarg is now the argument, see if it's in the
729 * table of longopts. */
730
731 for (nextchar = nameend = GNoptarg; *nameend && *nameend != '=';
732 nameend++)
733 /* Do nothing. */;
734
735 /* Test all long options for either exact match
736 * or abbreviated matches. */
737 if (longopts != NULL)
738 for (p = longopts, option_index = 0; p->name; p++, option_index++)
739 if (! strncmp (p->name, nextchar, nameend - nextchar))
740 { 678 {
741 if ((unsigned int) (nameend - nextchar) == strlen (p->name)) 679 if (posixly_correct)
742 { 680 /* 1003.2 specifies the format of this message. */
743 /* Exact match found. */ 681 fprintf(stderr, _("%s: illegal option -- %c\n"), argv[0], c);
744 pfound = p;
745 indfound = option_index;
746 exact = 1;
747 break;
748 }
749 else if (pfound == NULL)
750 {
751 /* First nonexact match found. */
752 pfound = p;
753 indfound = option_index;
754 }
755 else 682 else
756 /* Second or later nonexact match found. */ 683 fprintf(stderr, _("%s: invalid option -- %c\n"), argv[0], c);
757 ambig = 1;
758 } 684 }
759 if (ambig && ! exact)
760 {
761 if (GNopterr)
762 fprintf (stderr,
763 _ ("%s: option `-W %s' is ambiguous\n"),
764 argv[0],
765 argv[GNoptind]);
766 nextchar += strlen (nextchar);
767 GNoptind++;
768 return '?'; 685 return '?';
769 } 686 }
770 if (pfound != NULL) 687 /* Convenience. Treat POSIX -W foo same as long option --foo */
688 if (temp[0] == 'W' && temp[1] == ';')
771 { 689 {
772 option_index = indfound; 690 char *nameend;
773 if (*nameend) 691 const struct GNoption *p;
774 { 692 const struct GNoption *pfound = NULL;
775 /* Don't test has_arg with >, because some C compilers don't 693 int exact = 0;
776 * allow it to be used on enums. */ 694 int ambig = 0;
777 if (pfound->has_arg) 695 int indfound = 0;
778 GNoptarg = nameend + 1; 696 int option_index;
779 else 697
698 /* This is an option that requires an argument. */
699 if (*nextchar != '\0')
700 {
701 GNoptarg = nextchar;
702 /* If we end this ARGV-element by taking the rest as an arg,
703 * we must advance to the next element now. */
704 GNoptind++;
705 }
706 else if (GNoptind == argc)
780 { 707 {
781 if (GNopterr) 708 if (GNopterr)
782 fprintf (stderr, 709 {
783 _ ("%s: option `-W %s' does not allow an argument\n"), 710 /* 1003.2 specifies the format of this message. */
784 argv[0], 711 fprintf(stderr,
785 pfound->name); 712 _("%s: option requires an argument -- %c\n"),
713 argv[0],
714 c);
715 }
716 if (optstring[0] == ':')
717 c = ':';
718 else
719 c = '?';
720 return c;
721 }
722 else
723 /* We already incremented `GNoptind' once;
724 * increment it again when taking next ARGV-elt as argument. */
725 GNoptarg = argv[GNoptind++];
786 726
787 nextchar += strlen (nextchar); 727 /* GNoptarg is now the argument, see if it's in the
728 * table of longopts. */
729
730 for (nextchar = nameend = GNoptarg; *nameend && *nameend != '=';
731 nameend++)
732 /* Do nothing. */;
733
734 /* Test all long options for either exact match
735 * or abbreviated matches. */
736 if (longopts != NULL)
737 for (p = longopts, option_index = 0; p->name; p++, option_index++)
738 if (!strncmp(p->name, nextchar, nameend - nextchar))
739 {
740 if ((unsigned int)(nameend - nextchar) == strlen(p->name))
741 {
742 /* Exact match found. */
743 pfound = p;
744 indfound = option_index;
745 exact = 1;
746 break;
747 }
748 else if (pfound == NULL)
749 {
750 /* First nonexact match found. */
751 pfound = p;
752 indfound = option_index;
753 }
754 else
755 /* Second or later nonexact match found. */
756 ambig = 1;
757 }
758 if (ambig && !exact)
759 {
760 if (GNopterr)
761 fprintf(stderr,
762 _("%s: option `-W %s' is ambiguous\n"),
763 argv[0],
764 argv[GNoptind]);
765 nextchar += strlen(nextchar);
766 GNoptind++;
788 return '?'; 767 return '?';
789 } 768 }
790 } 769 if (pfound != NULL)
791 else if (pfound->has_arg == 1)
792 {
793 if (GNoptind < argc)
794 GNoptarg = argv[GNoptind++];
795 else
796 { 770 {
797 if (GNopterr) 771 option_index = indfound;
798 fprintf (stderr, 772 if (*nameend)
799 _ ("%s: option `%s' requires an argument\n"), 773 {
800 argv[0], 774 /* Don't test has_arg with >, because some C compilers don't
801 argv[GNoptind - 1]); 775 * allow it to be used on enums. */
802 nextchar += strlen (nextchar); 776 if (pfound->has_arg)
803 return optstring[0] == ':' ? ':' : '?'; 777 GNoptarg = nameend + 1;
778 else
779 {
780 if (GNopterr)
781 fprintf(stderr,
782 _("%s: option `-W %s' does not allow an argument\n"),
783 argv[0],
784 pfound->name);
785
786 nextchar += strlen(nextchar);
787 return '?';
788 }
789 }
790 else if (pfound->has_arg == 1)
791 {
792 if (GNoptind < argc)
793 GNoptarg = argv[GNoptind++];
794 else
795 {
796 if (GNopterr)
797 fprintf(stderr,
798 _("%s: option `%s' requires an argument\n"),
799 argv[0],
800 argv[GNoptind - 1]);
801 nextchar += strlen(nextchar);
802 return optstring[0] == ':' ? ':' : '?';
803 }
804 }
805 nextchar += strlen(nextchar);
806 if (longind != NULL)
807 *longind = option_index;
808 if (pfound->flag)
809 {
810 *(pfound->flag) = pfound->val;
811 return 0;
812 }
813 return pfound->val;
804 } 814 }
805 }
806 nextchar += strlen (nextchar);
807 if (longind != NULL)
808 *longind = option_index;
809 if (pfound->flag)
810 {
811 *(pfound->flag) = pfound->val;
812 return 0;
813 }
814 return pfound->val;
815 }
816 nextchar = NULL;
817 return 'W'; /* Let the application handle it. */
818 }
819 if (temp[1] == ':')
820 {
821 if (temp[2] == ':')
822 {
823 /* This is an option that accepts an argument optionally. */
824 if (*nextchar != '\0')
825 {
826 GNoptarg = nextchar;
827 GNoptind++;
828 }
829 else
830 GNoptarg = NULL;
831 nextchar = NULL; 815 nextchar = NULL;
816 return 'W'; /* Let the application handle it. */
832 } 817 }
833 else 818 if (temp[1] == ':')
834 { 819 {
835 /* This is an option that requires an argument. */ 820 if (temp[2] == ':')
836 if (*nextchar != '\0')
837 {
838 GNoptarg = nextchar;
839 /* If we end this ARGV-element by taking the rest as an arg,
840 * we must advance to the next element now. */
841 GNoptind++;
842 }
843 else if (GNoptind == argc)
844 {
845 if (GNopterr)
846 { 821 {
847 /* 1003.2 specifies the format of this message. */ 822 /* This is an option that accepts an argument optionally. */
848 fprintf (stderr, 823 if (*nextchar != '\0')
849 _ ("%s: option requires an argument -- %c\n"), 824 {
850 argv[0], 825 GNoptarg = nextchar;
851 c); 826 GNoptind++;
827 }
828 else
829 GNoptarg = NULL;
830 nextchar = NULL;
852 } 831 }
853 if (optstring[0] == ':')
854 c = ':';
855 else
856 c = '?';
857 }
858 else 832 else
859 /* We already incremented `GNoptind' once; 833 {
860 * increment it again when taking next ARGV-elt as argument. */ 834 /* This is an option that requires an argument. */
861 GNoptarg = argv[GNoptind++]; 835 if (*nextchar != '\0')
862 nextchar = NULL; 836 {
837 GNoptarg = nextchar;
838 /* If we end this ARGV-element by taking the rest as an arg,
839 * we must advance to the next element now. */
840 GNoptind++;
841 }
842 else if (GNoptind == argc)
843 {
844 if (GNopterr)
845 {
846 /* 1003.2 specifies the format of this message. */
847 fprintf(stderr,
848 _("%s: option requires an argument -- %c\n"),
849 argv[0],
850 c);
851 }
852 if (optstring[0] == ':')
853 c = ':';
854 else
855 c = '?';
856 }
857 else
858 /* We already incremented `GNoptind' once;
859 * increment it again when taking next ARGV-elt as argument. */
860 GNoptarg = argv[GNoptind++];
861 nextchar = NULL;
862 }
863 } 863 }
864 }
865 return c; 864 return c;
866 } 865 }
867} 866}
868 867
869 868
870static int 869static int
871GNgetopt_long (int argc, 870GNgetopt_long(int argc,
872 char *const *argv, 871 char *const *argv,
873 const char *options, 872 const char *options,
874 const struct GNoption *long_options, 873 const struct GNoption *long_options,
875 int *opt_index) 874 int *opt_index)
876{ 875{
877 return GN_getopt_internal (argc, argv, options, long_options, opt_index, 0); 876 return GN_getopt_internal(argc, argv, options, long_options, opt_index, 0);
878} 877}
879 878
880/* ******************** now the GNUnet specific modifications... ********************* */ 879/* ******************** now the GNUnet specific modifications... ********************* */
@@ -890,10 +889,10 @@ GNgetopt_long (int argc,
890 * argument, or #GNUNET_SYSERR on error 889 * argument, or #GNUNET_SYSERR on error
891 */ 890 */
892int 891int
893GNUNET_GETOPT_run (const char *binaryOptions, 892GNUNET_GETOPT_run(const char *binaryOptions,
894 const struct GNUNET_GETOPT_CommandLineOption *allOptions, 893 const struct GNUNET_GETOPT_CommandLineOption *allOptions,
895 unsigned int argc, 894 unsigned int argc,
896 char *const *argv) 895 char *const *argv)
897{ 896{
898 struct GNoption *long_options; 897 struct GNoption *long_options;
899 struct GNUNET_GETOPT_CommandLineProcessorContext clpc; 898 struct GNUNET_GETOPT_CommandLineProcessorContext clpc;
@@ -905,7 +904,7 @@ GNUNET_GETOPT_run (const char *binaryOptions,
905 unsigned int optmatch = 0; 904 unsigned int optmatch = 0;
906 const char *have_exclusive = NULL; 905 const char *have_exclusive = NULL;
907 906
908 GNUNET_assert (argc > 0); 907 GNUNET_assert(argc > 0);
909 GNoptind = 0; 908 GNoptind = 0;
910 clpc.binaryName = argv[0]; 909 clpc.binaryName = argv[0];
911 clpc.binaryOptions = binaryOptions; 910 clpc.binaryOptions = binaryOptions;
@@ -917,20 +916,20 @@ GNUNET_GETOPT_run (const char *binaryOptions,
917 916
918 /* transform our option representation into the format 917 /* transform our option representation into the format
919 used by the GNU getopt copylib */ 918 used by the GNU getopt copylib */
920 long_options = GNUNET_new_array (count + 1, struct GNoption); 919 long_options = GNUNET_new_array(count + 1, struct GNoption);
921 seen = GNUNET_new_array (count, uint8_t); 920 seen = GNUNET_new_array(count, uint8_t);
922 shorts = GNUNET_malloc (count * 2 + 1); 921 shorts = GNUNET_malloc(count * 2 + 1);
923 spos = 0; 922 spos = 0;
924 for (unsigned i = 0; i < count; i++) 923 for (unsigned i = 0; i < count; i++)
925 { 924 {
926 long_options[i].name = allOptions[i].name; 925 long_options[i].name = allOptions[i].name;
927 long_options[i].has_arg = allOptions[i].require_argument; 926 long_options[i].has_arg = allOptions[i].require_argument;
928 long_options[i].flag = NULL; 927 long_options[i].flag = NULL;
929 long_options[i].val = allOptions[i].shortName; 928 long_options[i].val = allOptions[i].shortName;
930 shorts[spos++] = allOptions[i].shortName; 929 shorts[spos++] = allOptions[i].shortName;
931 if (allOptions[i].require_argument != 0) 930 if (allOptions[i].require_argument != 0)
932 shorts[spos++] = ':'; 931 shorts[spos++] = ':';
933 } 932 }
934 long_options[count].name = NULL; 933 long_options[count].name = NULL;
935 long_options[count].has_arg = 0; 934 long_options[count].has_arg = 0;
936 long_options[count].flag = NULL; 935 long_options[count].flag = NULL;
@@ -940,74 +939,74 @@ GNUNET_GETOPT_run (const char *binaryOptions,
940 939
941 /* main getopt loop */ 940 /* main getopt loop */
942 while (1) 941 while (1)
943 { 942 {
944 int option_index = 0; 943 int option_index = 0;
945 unsigned int i; 944 unsigned int i;
946 int c; 945 int c;
947 946
948 c = GNgetopt_long (argc, argv, shorts, long_options, &option_index); 947 c = GNgetopt_long(argc, argv, shorts, long_options, &option_index);
949 if (c == GNUNET_SYSERR) 948 if (c == GNUNET_SYSERR)
950 break; /* No more flags to process */ 949 break; /* No more flags to process */
951 950
952 /* Check which of our program's options was given by the user */ 951 /* Check which of our program's options was given by the user */
953 for (i = 0; i < count; i++) 952 for (i = 0; i < count; i++)
954 {
955 clpc.currentArgument = GNoptind - 1;
956 if ((char) c == allOptions[i].shortName)
957 {
958 optmatch++;
959 if (allOptions[i].option_exclusive)
960 have_exclusive = allOptions[i].name;
961 if (GNUNET_OK == cont)
962 { 953 {
963 /* parse the option using the option-specific processor */ 954 clpc.currentArgument = GNoptind - 1;
964 cont = allOptions[i].processor (&clpc, 955 if ((char)c == allOptions[i].shortName)
965 allOptions[i].scls, 956 {
966 allOptions[i].name, 957 optmatch++;
967 GNoptarg); 958 if (allOptions[i].option_exclusive)
959 have_exclusive = allOptions[i].name;
960 if (GNUNET_OK == cont)
961 {
962 /* parse the option using the option-specific processor */
963 cont = allOptions[i].processor(&clpc,
964 allOptions[i].scls,
965 allOptions[i].name,
966 GNoptarg);
967 }
968 seen[i] = 1;
969 break;
970 }
971 }
972 if (i == count)
973 {
974 fprintf(stderr, _("Use %s to get a list of options.\n"), "--help");
975 cont = GNUNET_SYSERR;
968 } 976 }
969 seen[i] = 1;
970 break;
971 }
972 }
973 if (i == count)
974 {
975 fprintf (stderr, _ ("Use %s to get a list of options.\n"), "--help");
976 cont = GNUNET_SYSERR;
977 } 977 }
978 } 978 GNUNET_free(shorts);
979 GNUNET_free (shorts); 979 GNUNET_free(long_options);
980 GNUNET_free (long_options);
981 980
982 /* check that if any option that was marked as exclusive 981 /* check that if any option that was marked as exclusive
983 is the only option that was provided */ 982 is the only option that was provided */
984 if ((NULL != have_exclusive) && (optmatch > 1)) 983 if ((NULL != have_exclusive) && (optmatch > 1))
985 { 984 {
986 fprintf (stderr, 985 fprintf(stderr,
987 _ ("Option `%s' can't be used with other options.\n"), 986 _("Option `%s' can't be used with other options.\n"),
988 have_exclusive); 987 have_exclusive);
989 cont = GNUNET_SYSERR; 988 cont = GNUNET_SYSERR;
990 } 989 }
991 if (GNUNET_YES == cont) 990 if (GNUNET_YES == cont)
992 {
993 /* check that all mandatory options are present */
994 for (count = 0; NULL != allOptions[count].name; count++)
995 { 991 {
996 if ((0 == seen[count]) && (allOptions[count].option_mandatory)) 992 /* check that all mandatory options are present */
997 { 993 for (count = 0; NULL != allOptions[count].name; count++)
998 fprintf (stderr, 994 {
999 _ ("Missing mandatory option `%s'.\n"), 995 if ((0 == seen[count]) && (allOptions[count].option_mandatory))
1000 allOptions[count].name); 996 {
1001 cont = GNUNET_SYSERR; 997 fprintf(stderr,
1002 } 998 _("Missing mandatory option `%s'.\n"),
999 allOptions[count].name);
1000 cont = GNUNET_SYSERR;
1001 }
1002 }
1003 } 1003 }
1004 } 1004 GNUNET_free(seen);
1005 GNUNET_free (seen);
1006 1005
1007 /* call cleaners, if available */ 1006 /* call cleaners, if available */
1008 for (unsigned int i = 0; NULL != allOptions[i].name; i++) 1007 for (unsigned int i = 0; NULL != allOptions[i].name; i++)
1009 if (NULL != allOptions[i].cleaner) 1008 if (NULL != allOptions[i].cleaner)
1010 allOptions[i].cleaner (allOptions[i].scls); 1009 allOptions[i].cleaner(allOptions[i].scls);
1011 1010
1012 if (GNUNET_OK != cont) 1011 if (GNUNET_OK != cont)
1013 return cont; 1012 return cont;
diff --git a/src/util/getopt_helpers.c b/src/util/getopt_helpers.c
index f53441508..a5e752546 100644
--- a/src/util/getopt_helpers.c
+++ b/src/util/getopt_helpers.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/getopt_helpers.c 22 * @file src/util/getopt_helpers.c
@@ -26,7 +26,7 @@
26#include "platform.h" 26#include "platform.h"
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29#define LOG(kind, ...) GNUNET_log_from (kind, "util-getopt", __VA_ARGS__) 29#define LOG(kind, ...) GNUNET_log_from(kind, "util-getopt", __VA_ARGS__)
30 30
31 31
32/** 32/**
@@ -39,16 +39,16 @@
39 * @return #GNUNET_NO (do not continue, not an error) 39 * @return #GNUNET_NO (do not continue, not an error)
40 */ 40 */
41static int 41static int
42print_version (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 42print_version(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
43 void *scls, 43 void *scls,
44 const char *option, 44 const char *option,
45 const char *value) 45 const char *value)
46{ 46{
47 const char *version = scls; 47 const char *version = scls;
48 48
49 (void) option; 49 (void)option;
50 (void) value; 50 (void)value;
51 printf ("%s v%s\n", ctx->binaryName, version); 51 printf("%s v%s\n", ctx->binaryName, version);
52 return GNUNET_NO; 52 return GNUNET_NO;
53} 53}
54 54
@@ -60,15 +60,16 @@ print_version (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
60 * @param version string with the version number 60 * @param version string with the version number
61 */ 61 */
62struct GNUNET_GETOPT_CommandLineOption 62struct GNUNET_GETOPT_CommandLineOption
63GNUNET_GETOPT_option_version (const char *version) 63GNUNET_GETOPT_option_version(const char *version)
64{ 64{
65 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = 'v', 65 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = 'v',
66 .name = "version", 66 .name = "version",
67 .description = gettext_noop ( 67 .description = gettext_noop(
68 "print the version number"), 68 "print the version number"),
69 .option_exclusive = 1, 69 .option_exclusive = 1,
70 .processor = &print_version, 70 .processor = &print_version,
71 .scls = (void *) version}; 71 .scls = (void *)version };
72
72 return clo; 73 return clo;
73} 74}
74 75
@@ -88,10 +89,10 @@ GNUNET_GETOPT_option_version (const char *version)
88 * @return #GNUNET_NO (do not continue, not an error) 89 * @return #GNUNET_NO (do not continue, not an error)
89 */ 90 */
90static int 91static int
91format_help (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 92format_help(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
92 void *scls, 93 void *scls,
93 const char *option, 94 const char *option,
94 const char *value) 95 const char *value)
95{ 96{
96 const char *about = scls; 97 const char *about = scls;
97 size_t slen; 98 size_t slen;
@@ -104,86 +105,86 @@ format_help (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
104 const struct GNUNET_GETOPT_CommandLineOption *opt; 105 const struct GNUNET_GETOPT_CommandLineOption *opt;
105 const struct GNUNET_OS_ProjectData *pd; 106 const struct GNUNET_OS_ProjectData *pd;
106 107
107 (void) option; 108 (void)option;
108 (void) value; 109 (void)value;
109 if (NULL != about) 110 if (NULL != about)
110 { 111 {
111 printf ("%s\n%s\n", ctx->binaryOptions, gettext (about)); 112 printf("%s\n%s\n", ctx->binaryOptions, gettext(about));
112 printf (_ ( 113 printf(_(
113 "Arguments mandatory for long options are also mandatory for short options.\n")); 114 "Arguments mandatory for long options are also mandatory for short options.\n"));
114 } 115 }
115 i = 0; 116 i = 0;
116 opt = ctx->allOptions; 117 opt = ctx->allOptions;
117 while (NULL != opt[i].description) 118 while (NULL != opt[i].description)
118 {
119 if (opt[i].shortName == '\0')
120 printf (" ");
121 else
122 printf (" -%c, ", opt[i].shortName);
123 printf ("--%s", opt[i].name);
124 slen = 8 + strlen (opt[i].name);
125 if (NULL != opt[i].argumentHelp)
126 { 119 {
127 printf ("=%s", opt[i].argumentHelp); 120 if (opt[i].shortName == '\0')
128 slen += 1 + strlen (opt[i].argumentHelp); 121 printf(" ");
129 } 122 else
130 if (slen > BORDER) 123 printf(" -%c, ", opt[i].shortName);
131 { 124 printf("--%s", opt[i].name);
132 printf ("\n%*s", BORDER, ""); 125 slen = 8 + strlen(opt[i].name);
133 slen = BORDER; 126 if (NULL != opt[i].argumentHelp)
134 } 127 {
135 if (slen < BORDER) 128 printf("=%s", opt[i].argumentHelp);
136 { 129 slen += 1 + strlen(opt[i].argumentHelp);
137 printf ("%*s", (int) (BORDER - slen), ""); 130 }
138 slen = BORDER; 131 if (slen > BORDER)
139 } 132 {
140 if (0 < strlen (opt[i].description)) 133 printf("\n%*s", BORDER, "");
141 trans = gettext (opt[i].description); 134 slen = BORDER;
142 else 135 }
143 trans = ""; 136 if (slen < BORDER)
144 ml = strlen (trans);
145 p = 0;
146 OUTER:
147 while (ml - p > 78 - slen)
148 {
149 for (j = p + 78 - slen; j > (int) p; j--)
150 {
151 if (isspace ((unsigned char) trans[j]))
152 { 137 {
153 scp = GNUNET_malloc (j - p + 1); 138 printf("%*s", (int)(BORDER - slen), "");
154 GNUNET_memcpy (scp, &trans[p], j - p); 139 slen = BORDER;
155 scp[j - p] = '\0'; 140 }
156 printf ("%s\n%*s", scp, BORDER + 2, ""); 141 if (0 < strlen(opt[i].description))
157 GNUNET_free (scp); 142 trans = gettext(opt[i].description);
158 p = j + 1; 143 else
144 trans = "";
145 ml = strlen(trans);
146 p = 0;
147OUTER:
148 while (ml - p > 78 - slen)
149 {
150 for (j = p + 78 - slen; j > (int)p; j--)
151 {
152 if (isspace((unsigned char)trans[j]))
153 {
154 scp = GNUNET_malloc(j - p + 1);
155 GNUNET_memcpy(scp, &trans[p], j - p);
156 scp[j - p] = '\0';
157 printf("%s\n%*s", scp, BORDER + 2, "");
158 GNUNET_free(scp);
159 p = j + 1;
160 slen = BORDER + 2;
161 goto OUTER;
162 }
163 }
164 /* could not find space to break line */
165 scp = GNUNET_malloc(78 - slen + 1);
166 GNUNET_memcpy(scp, &trans[p], 78 - slen);
167 scp[78 - slen] = '\0';
168 printf("%s\n%*s", scp, BORDER + 2, "");
169 GNUNET_free(scp);
159 slen = BORDER + 2; 170 slen = BORDER + 2;
160 goto OUTER; 171 p = p + 78 - slen;
161 } 172 }
162 } 173 /* print rest */
163 /* could not find space to break line */ 174 if (p < ml)
164 scp = GNUNET_malloc (78 - slen + 1); 175 printf("%s\n", &trans[p]);
165 GNUNET_memcpy (scp, &trans[p], 78 - slen); 176 if (strlen(trans) == 0)
166 scp[78 - slen] = '\0'; 177 printf("\n");
167 printf ("%s\n%*s", scp, BORDER + 2, ""); 178 i++;
168 GNUNET_free (scp);
169 slen = BORDER + 2;
170 p = p + 78 - slen;
171 } 179 }
172 /* print rest */ 180 pd = GNUNET_OS_project_data_get();
173 if (p < ml) 181 printf("Report bugs to %s.\n"
174 printf ("%s\n", &trans[p]); 182 "Home page: %s\n",
175 if (strlen (trans) == 0) 183 pd->bug_email,
176 printf ("\n"); 184 pd->homepage);
177 i++;
178 }
179 pd = GNUNET_OS_project_data_get ();
180 printf ("Report bugs to %s.\n"
181 "Home page: %s\n",
182 pd->bug_email,
183 pd->homepage);
184 185
185 if (0 != pd->is_gnu) 186 if (0 != pd->is_gnu)
186 printf ("General help using GNU software: http://www.gnu.org/gethelp/\n"); 187 printf("General help using GNU software: http://www.gnu.org/gethelp/\n");
187 188
188 return GNUNET_NO; 189 return GNUNET_NO;
189} 190}
@@ -196,15 +197,15 @@ format_help (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
196 * @param about string with brief description of the application 197 * @param about string with brief description of the application
197 */ 198 */
198struct GNUNET_GETOPT_CommandLineOption 199struct GNUNET_GETOPT_CommandLineOption
199GNUNET_GETOPT_option_help (const char *about) 200GNUNET_GETOPT_option_help(const char *about)
200{ 201{
201 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = 'h', 202 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = 'h',
202 .name = "help", 203 .name = "help",
203 .description = gettext_noop ( 204 .description = gettext_noop(
204 "print this help"), 205 "print this help"),
205 .option_exclusive = 1, 206 .option_exclusive = 1,
206 .processor = format_help, 207 .processor = format_help,
207 .scls = (void *) about}; 208 .scls = (void *)about };
208 209
209 return clo; 210 return clo;
210} 211}
@@ -225,16 +226,16 @@ GNUNET_GETOPT_option_help (const char *about)
225 * @return #GNUNET_OK 226 * @return #GNUNET_OK
226 */ 227 */
227static int 228static int
228increment_value (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 229increment_value(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
229 void *scls, 230 void *scls,
230 const char *option, 231 const char *option,
231 const char *value) 232 const char *value)
232{ 233{
233 unsigned int *val = scls; 234 unsigned int *val = scls;
234 235
235 (void) ctx; 236 (void)ctx;
236 (void) option; 237 (void)option;
237 (void) value; 238 (void)value;
238 (*val)++; 239 (*val)++;
239 return GNUNET_OK; 240 return GNUNET_OK;
240} 241}
@@ -250,16 +251,16 @@ increment_value (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
250 * @param[out] val increment by 1 each time the option is present 251 * @param[out] val increment by 1 each time the option is present
251 */ 252 */
252struct GNUNET_GETOPT_CommandLineOption 253struct GNUNET_GETOPT_CommandLineOption
253GNUNET_GETOPT_option_increment_uint (char shortName, 254GNUNET_GETOPT_option_increment_uint(char shortName,
254 const char *name, 255 const char *name,
255 const char *description, 256 const char *description,
256 unsigned int *val) 257 unsigned int *val)
257{ 258{
258 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 259 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
259 .name = name, 260 .name = name,
260 .description = description, 261 .description = description,
261 .processor = &increment_value, 262 .processor = &increment_value,
262 .scls = (void *) val}; 263 .scls = (void *)val };
263 264
264 return clo; 265 return clo;
265} 266}
@@ -272,14 +273,14 @@ GNUNET_GETOPT_option_increment_uint (char shortName,
272 * @param[out] level set to the verbosity level 273 * @param[out] level set to the verbosity level
273 */ 274 */
274struct GNUNET_GETOPT_CommandLineOption 275struct GNUNET_GETOPT_CommandLineOption
275GNUNET_GETOPT_option_verbose (unsigned int *level) 276GNUNET_GETOPT_option_verbose(unsigned int *level)
276{ 277{
277 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = 'V', 278 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = 'V',
278 .name = "verbose", 279 .name = "verbose",
279 .description = 280 .description =
280 gettext_noop ("be verbose"), 281 gettext_noop("be verbose"),
281 .processor = &increment_value, 282 .processor = &increment_value,
282 .scls = (void *) level}; 283 .scls = (void *)level };
283 284
284 return clo; 285 return clo;
285} 286}
@@ -300,16 +301,16 @@ GNUNET_GETOPT_option_verbose (unsigned int *level)
300 * @return #GNUNET_OK 301 * @return #GNUNET_OK
301 */ 302 */
302static int 303static int
303set_one (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 304set_one(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
304 void *scls, 305 void *scls,
305 const char *option, 306 const char *option,
306 const char *value) 307 const char *value)
307{ 308{
308 int *val = scls; 309 int *val = scls;
309 310
310 (void) ctx; 311 (void)ctx;
311 (void) option; 312 (void)option;
312 (void) value; 313 (void)value;
313 *val = 1; 314 *val = 1;
314 return GNUNET_OK; 315 return GNUNET_OK;
315} 316}
@@ -326,16 +327,16 @@ set_one (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
326 * @param[out] val set to 1 if the option is present 327 * @param[out] val set to 1 if the option is present
327 */ 328 */
328struct GNUNET_GETOPT_CommandLineOption 329struct GNUNET_GETOPT_CommandLineOption
329GNUNET_GETOPT_option_flag (char shortName, 330GNUNET_GETOPT_option_flag(char shortName,
330 const char *name, 331 const char *name,
331 const char *description, 332 const char *description,
332 int *val) 333 int *val)
333{ 334{
334 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 335 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
335 .name = name, 336 .name = name,
336 .description = description, 337 .description = description,
337 .processor = &set_one, 338 .processor = &set_one,
338 .scls = (void *) val}; 339 .scls = (void *)val };
339 340
340 return clo; 341 return clo;
341} 342}
@@ -356,18 +357,18 @@ GNUNET_GETOPT_option_flag (char shortName,
356 * @return #GNUNET_OK 357 * @return #GNUNET_OK
357 */ 358 */
358static int 359static int
359set_string (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 360set_string(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
360 void *scls, 361 void *scls,
361 const char *option, 362 const char *option,
362 const char *value) 363 const char *value)
363{ 364{
364 char **val = scls; 365 char **val = scls;
365 366
366 (void) ctx; 367 (void)ctx;
367 (void) option; 368 (void)option;
368 GNUNET_assert (NULL != value); 369 GNUNET_assert(NULL != value);
369 GNUNET_free_non_null (*val); 370 GNUNET_free_non_null(*val);
370 *val = GNUNET_strdup (value); 371 *val = GNUNET_strdup(value);
371 return GNUNET_OK; 372 return GNUNET_OK;
372} 373}
373 374
@@ -382,19 +383,19 @@ set_string (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
382 * @param[out] str set to the string 383 * @param[out] str set to the string
383 */ 384 */
384struct GNUNET_GETOPT_CommandLineOption 385struct GNUNET_GETOPT_CommandLineOption
385GNUNET_GETOPT_option_string (char shortName, 386GNUNET_GETOPT_option_string(char shortName,
386 const char *name, 387 const char *name,
387 const char *argumentHelp, 388 const char *argumentHelp,
388 const char *description, 389 const char *description,
389 char **str) 390 char **str)
390{ 391{
391 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 392 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
392 .name = name, 393 .name = name,
393 .argumentHelp = argumentHelp, 394 .argumentHelp = argumentHelp,
394 .description = description, 395 .description = description,
395 .require_argument = 1, 396 .require_argument = 1,
396 .processor = &set_string, 397 .processor = &set_string,
397 .scls = (void *) str}; 398 .scls = (void *)str };
398 399
399 return clo; 400 return clo;
400} 401}
@@ -407,16 +408,16 @@ GNUNET_GETOPT_option_string (char shortName,
407 * @param[out] level set to the log level 408 * @param[out] level set to the log level
408 */ 409 */
409struct GNUNET_GETOPT_CommandLineOption 410struct GNUNET_GETOPT_CommandLineOption
410GNUNET_GETOPT_option_loglevel (char **level) 411GNUNET_GETOPT_option_loglevel(char **level)
411{ 412{
412 struct GNUNET_GETOPT_CommandLineOption clo = 413 struct GNUNET_GETOPT_CommandLineOption clo =
413 {.shortName = 'L', 414 { .shortName = 'L',
414 .name = "log", 415 .name = "log",
415 .argumentHelp = "LOGLEVEL", 416 .argumentHelp = "LOGLEVEL",
416 .description = gettext_noop ("configure logging to use LOGLEVEL"), 417 .description = gettext_noop("configure logging to use LOGLEVEL"),
417 .require_argument = 1, 418 .require_argument = 1,
418 .processor = &set_string, 419 .processor = &set_string,
419 .scls = (void *) level}; 420 .scls = (void *)level };
420 421
421 return clo; 422 return clo;
422} 423}
@@ -434,18 +435,18 @@ GNUNET_GETOPT_option_loglevel (char **level)
434 * @return #GNUNET_OK 435 * @return #GNUNET_OK
435 */ 436 */
436static int 437static int
437set_filename (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 438set_filename(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
438 void *scls, 439 void *scls,
439 const char *option, 440 const char *option,
440 const char *value) 441 const char *value)
441{ 442{
442 char **val = scls; 443 char **val = scls;
443 444
444 (void) ctx; 445 (void)ctx;
445 (void) option; 446 (void)option;
446 GNUNET_assert (NULL != value); 447 GNUNET_assert(NULL != value);
447 GNUNET_free_non_null (*val); 448 GNUNET_free_non_null(*val);
448 *val = GNUNET_STRINGS_filename_expand (value); 449 *val = GNUNET_STRINGS_filename_expand(value);
449 return GNUNET_OK; 450 return GNUNET_OK;
450} 451}
451 452
@@ -460,19 +461,19 @@ set_filename (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
460 * @param[out] str set to the string 461 * @param[out] str set to the string
461 */ 462 */
462struct GNUNET_GETOPT_CommandLineOption 463struct GNUNET_GETOPT_CommandLineOption
463GNUNET_GETOPT_option_filename (char shortName, 464GNUNET_GETOPT_option_filename(char shortName,
464 const char *name, 465 const char *name,
465 const char *argumentHelp, 466 const char *argumentHelp,
466 const char *description, 467 const char *description,
467 char **str) 468 char **str)
468{ 469{
469 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 470 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
470 .name = name, 471 .name = name,
471 .argumentHelp = argumentHelp, 472 .argumentHelp = argumentHelp,
472 .description = description, 473 .description = description,
473 .require_argument = 1, 474 .require_argument = 1,
474 .processor = &set_filename, 475 .processor = &set_filename,
475 .scls = (void *) str}; 476 .scls = (void *)str };
476 477
477 return clo; 478 return clo;
478} 479}
@@ -484,17 +485,17 @@ GNUNET_GETOPT_option_filename (char shortName,
484 * @param[out] logfn set to the name of the logfile 485 * @param[out] logfn set to the name of the logfile
485 */ 486 */
486struct GNUNET_GETOPT_CommandLineOption 487struct GNUNET_GETOPT_CommandLineOption
487GNUNET_GETOPT_option_logfile (char **logfn) 488GNUNET_GETOPT_option_logfile(char **logfn)
488{ 489{
489 struct GNUNET_GETOPT_CommandLineOption clo = 490 struct GNUNET_GETOPT_CommandLineOption clo =
490 {.shortName = 'l', 491 { .shortName = 'l',
491 .name = "logfile", 492 .name = "logfile",
492 .argumentHelp = "FILENAME", 493 .argumentHelp = "FILENAME",
493 .description = 494 .description =
494 gettext_noop ("configure logging to write logs to FILENAME"), 495 gettext_noop("configure logging to write logs to FILENAME"),
495 .require_argument = 1, 496 .require_argument = 1,
496 .processor = &set_filename, 497 .processor = &set_filename,
497 .scls = (void *) logfn}; 498 .scls = (void *)logfn };
498 499
499 return clo; 500 return clo;
500} 501}
@@ -506,16 +507,16 @@ GNUNET_GETOPT_option_logfile (char **logfn)
506 * @param[out] fn set to the name of the configuration file 507 * @param[out] fn set to the name of the configuration file
507 */ 508 */
508struct GNUNET_GETOPT_CommandLineOption 509struct GNUNET_GETOPT_CommandLineOption
509GNUNET_GETOPT_option_cfgfile (char **fn) 510GNUNET_GETOPT_option_cfgfile(char **fn)
510{ 511{
511 struct GNUNET_GETOPT_CommandLineOption clo = 512 struct GNUNET_GETOPT_CommandLineOption clo =
512 {.shortName = 'c', 513 { .shortName = 'c',
513 .name = "config", 514 .name = "config",
514 .argumentHelp = "FILENAME", 515 .argumentHelp = "FILENAME",
515 .description = gettext_noop ("use configuration file FILENAME"), 516 .description = gettext_noop("use configuration file FILENAME"),
516 .require_argument = 1, 517 .require_argument = 1,
517 .processor = &set_filename, 518 .processor = &set_filename,
518 .scls = (void *) fn}; 519 .scls = (void *)fn };
519 520
520 return clo; 521 return clo;
521} 522}
@@ -535,22 +536,22 @@ GNUNET_GETOPT_option_cfgfile (char **fn)
535 * @return #GNUNET_OK if parsing the value worked 536 * @return #GNUNET_OK if parsing the value worked
536 */ 537 */
537static int 538static int
538set_ulong (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 539set_ulong(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
539 void *scls, 540 void *scls,
540 const char *option, 541 const char *option,
541 const char *value) 542 const char *value)
542{ 543{
543 unsigned long long *val = scls; 544 unsigned long long *val = scls;
544 char dummy[2]; 545 char dummy[2];
545 546
546 (void) ctx; 547 (void)ctx;
547 if (1 != sscanf (value, "%llu%1s", val, dummy)) 548 if (1 != sscanf(value, "%llu%1s", val, dummy))
548 { 549 {
549 fprintf (stderr, 550 fprintf(stderr,
550 _ ("You must pass a number to the `%s' option.\n"), 551 _("You must pass a number to the `%s' option.\n"),
551 option); 552 option);
552 return GNUNET_SYSERR; 553 return GNUNET_SYSERR;
553 } 554 }
554 return GNUNET_OK; 555 return GNUNET_OK;
555} 556}
556 557
@@ -565,19 +566,19 @@ set_ulong (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
565 * @param[out] val set to the value specified at the command line 566 * @param[out] val set to the value specified at the command line
566 */ 567 */
567struct GNUNET_GETOPT_CommandLineOption 568struct GNUNET_GETOPT_CommandLineOption
568GNUNET_GETOPT_option_ulong (char shortName, 569GNUNET_GETOPT_option_ulong(char shortName,
569 const char *name, 570 const char *name,
570 const char *argumentHelp, 571 const char *argumentHelp,
571 const char *description, 572 const char *description,
572 unsigned long long *val) 573 unsigned long long *val)
573{ 574{
574 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 575 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
575 .name = name, 576 .name = name,
576 .argumentHelp = argumentHelp, 577 .argumentHelp = argumentHelp,
577 .description = description, 578 .description = description,
578 .require_argument = 1, 579 .require_argument = 1,
579 .processor = &set_ulong, 580 .processor = &set_ulong,
580 .scls = (void *) val}; 581 .scls = (void *)val };
581 582
582 return clo; 583 return clo;
583} 584}
@@ -597,21 +598,21 @@ GNUNET_GETOPT_option_ulong (char shortName,
597 * @return #GNUNET_OK if parsing the value worked 598 * @return #GNUNET_OK if parsing the value worked
598 */ 599 */
599static int 600static int
600set_relative_time (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 601set_relative_time(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
601 void *scls, 602 void *scls,
602 const char *option, 603 const char *option,
603 const char *value) 604 const char *value)
604{ 605{
605 struct GNUNET_TIME_Relative *val = scls; 606 struct GNUNET_TIME_Relative *val = scls;
606 607
607 (void) ctx; 608 (void)ctx;
608 if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative (value, val)) 609 if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_relative(value, val))
609 { 610 {
610 fprintf (stderr, 611 fprintf(stderr,
611 _ ("You must pass relative time to the `%s' option.\n"), 612 _("You must pass relative time to the `%s' option.\n"),
612 option); 613 option);
613 return GNUNET_SYSERR; 614 return GNUNET_SYSERR;
614 } 615 }
615 return GNUNET_OK; 616 return GNUNET_OK;
616} 617}
617 618
@@ -627,19 +628,19 @@ set_relative_time (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
627 * @param[out] val set to the time specified at the command line 628 * @param[out] val set to the time specified at the command line
628 */ 629 */
629struct GNUNET_GETOPT_CommandLineOption 630struct GNUNET_GETOPT_CommandLineOption
630GNUNET_GETOPT_option_relative_time (char shortName, 631GNUNET_GETOPT_option_relative_time(char shortName,
631 const char *name, 632 const char *name,
632 const char *argumentHelp, 633 const char *argumentHelp,
633 const char *description, 634 const char *description,
634 struct GNUNET_TIME_Relative *val) 635 struct GNUNET_TIME_Relative *val)
635{ 636{
636 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 637 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
637 .name = name, 638 .name = name,
638 .argumentHelp = argumentHelp, 639 .argumentHelp = argumentHelp,
639 .description = description, 640 .description = description,
640 .require_argument = 1, 641 .require_argument = 1,
641 .processor = &set_relative_time, 642 .processor = &set_relative_time,
642 .scls = (void *) val}; 643 .scls = (void *)val };
643 644
644 return clo; 645 return clo;
645} 646}
@@ -659,21 +660,21 @@ GNUNET_GETOPT_option_relative_time (char shortName,
659 * @return #GNUNET_OK if parsing the value worked 660 * @return #GNUNET_OK if parsing the value worked
660 */ 661 */
661static int 662static int
662set_absolute_time (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 663set_absolute_time(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
663 void *scls, 664 void *scls,
664 const char *option, 665 const char *option,
665 const char *value) 666 const char *value)
666{ 667{
667 struct GNUNET_TIME_Absolute *val = scls; 668 struct GNUNET_TIME_Absolute *val = scls;
668 669
669 (void) ctx; 670 (void)ctx;
670 if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_absolute (value, val)) 671 if (GNUNET_OK != GNUNET_STRINGS_fancy_time_to_absolute(value, val))
671 { 672 {
672 fprintf (stderr, 673 fprintf(stderr,
673 _ ("You must pass absolute time to the `%s' option.\n"), 674 _("You must pass absolute time to the `%s' option.\n"),
674 option); 675 option);
675 return GNUNET_SYSERR; 676 return GNUNET_SYSERR;
676 } 677 }
677 return GNUNET_OK; 678 return GNUNET_OK;
678} 679}
679 680
@@ -689,19 +690,19 @@ set_absolute_time (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
689 * @param[out] val set to the time specified at the command line 690 * @param[out] val set to the time specified at the command line
690 */ 691 */
691struct GNUNET_GETOPT_CommandLineOption 692struct GNUNET_GETOPT_CommandLineOption
692GNUNET_GETOPT_option_absolute_time (char shortName, 693GNUNET_GETOPT_option_absolute_time(char shortName,
693 const char *name, 694 const char *name,
694 const char *argumentHelp, 695 const char *argumentHelp,
695 const char *description, 696 const char *description,
696 struct GNUNET_TIME_Absolute *val) 697 struct GNUNET_TIME_Absolute *val)
697{ 698{
698 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 699 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
699 .name = name, 700 .name = name,
700 .argumentHelp = argumentHelp, 701 .argumentHelp = argumentHelp,
701 .description = description, 702 .description = description,
702 .require_argument = 1, 703 .require_argument = 1,
703 .processor = &set_absolute_time, 704 .processor = &set_absolute_time,
704 .scls = (void *) val}; 705 .scls = (void *)val };
705 706
706 return clo; 707 return clo;
707} 708}
@@ -721,30 +722,30 @@ GNUNET_GETOPT_option_absolute_time (char shortName,
721 * @return #GNUNET_OK if parsing the value worked 722 * @return #GNUNET_OK if parsing the value worked
722 */ 723 */
723static int 724static int
724set_uint (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 725set_uint(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
725 void *scls, 726 void *scls,
726 const char *option, 727 const char *option,
727 const char *value) 728 const char *value)
728{ 729{
729 unsigned int *val = scls; 730 unsigned int *val = scls;
730 char dummy[2]; 731 char dummy[2];
731 732
732 (void) ctx; 733 (void)ctx;
733 if ('-' == *value) 734 if ('-' == *value)
734 { 735 {
735 fprintf (stderr, 736 fprintf(stderr,
736 _ ( 737 _(
737 "Your input for the '%s' option has to be a non negative number \n"), 738 "Your input for the '%s' option has to be a non negative number \n"),
738 option); 739 option);
739 return GNUNET_SYSERR; 740 return GNUNET_SYSERR;
740 } 741 }
741 if (1 != sscanf (value, "%u%1s", val, dummy)) 742 if (1 != sscanf(value, "%u%1s", val, dummy))
742 { 743 {
743 fprintf (stderr, 744 fprintf(stderr,
744 _ ("You must pass a number to the `%s' option.\n"), 745 _("You must pass a number to the `%s' option.\n"),
745 option); 746 option);
746 return GNUNET_SYSERR; 747 return GNUNET_SYSERR;
747 } 748 }
748 return GNUNET_OK; 749 return GNUNET_OK;
749} 750}
750 751
@@ -759,19 +760,19 @@ set_uint (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
759 * @param[out] val set to the value specified at the command line 760 * @param[out] val set to the value specified at the command line
760 */ 761 */
761struct GNUNET_GETOPT_CommandLineOption 762struct GNUNET_GETOPT_CommandLineOption
762GNUNET_GETOPT_option_uint (char shortName, 763GNUNET_GETOPT_option_uint(char shortName,
763 const char *name, 764 const char *name,
764 const char *argumentHelp, 765 const char *argumentHelp,
765 const char *description, 766 const char *description,
766 unsigned int *val) 767 unsigned int *val)
767{ 768{
768 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 769 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
769 .name = name, 770 .name = name,
770 .argumentHelp = argumentHelp, 771 .argumentHelp = argumentHelp,
771 .description = description, 772 .description = description,
772 .require_argument = 1, 773 .require_argument = 1,
773 .processor = &set_uint, 774 .processor = &set_uint,
774 .scls = (void *) val}; 775 .scls = (void *)val };
775 776
776 return clo; 777 return clo;
777} 778}
@@ -791,32 +792,32 @@ GNUNET_GETOPT_option_uint (char shortName,
791 * @return #GNUNET_OK if parsing the value worked 792 * @return #GNUNET_OK if parsing the value worked
792 */ 793 */
793static int 794static int
794set_uint16 (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 795set_uint16(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
795 void *scls, 796 void *scls,
796 const char *option, 797 const char *option,
797 const char *value) 798 const char *value)
798{ 799{
799 uint16_t *val = scls; 800 uint16_t *val = scls;
800 unsigned int v; 801 unsigned int v;
801 char dummy[2]; 802 char dummy[2];
802 803
803 (void) ctx; 804 (void)ctx;
804 if (1 != sscanf (value, "%u%1s", &v, dummy)) 805 if (1 != sscanf(value, "%u%1s", &v, dummy))
805 { 806 {
806 fprintf (stderr, 807 fprintf(stderr,
807 _ ("You must pass a number to the `%s' option.\n"), 808 _("You must pass a number to the `%s' option.\n"),
808 option); 809 option);
809 return GNUNET_SYSERR; 810 return GNUNET_SYSERR;
810 } 811 }
811 if (v > UINT16_MAX) 812 if (v > UINT16_MAX)
812 { 813 {
813 fprintf (stderr, 814 fprintf(stderr,
814 _ ("You must pass a number below %u to the `%s' option.\n"), 815 _("You must pass a number below %u to the `%s' option.\n"),
815 (unsigned int) UINT16_MAX, 816 (unsigned int)UINT16_MAX,
816 option); 817 option);
817 return GNUNET_SYSERR; 818 return GNUNET_SYSERR;
818 } 819 }
819 *val = (uint16_t) v; 820 *val = (uint16_t)v;
820 return GNUNET_OK; 821 return GNUNET_OK;
821} 822}
822 823
@@ -831,19 +832,19 @@ set_uint16 (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
831 * @param[out] val set to the value specified at the command line 832 * @param[out] val set to the value specified at the command line
832 */ 833 */
833struct GNUNET_GETOPT_CommandLineOption 834struct GNUNET_GETOPT_CommandLineOption
834GNUNET_GETOPT_option_uint16 (char shortName, 835GNUNET_GETOPT_option_uint16(char shortName,
835 const char *name, 836 const char *name,
836 const char *argumentHelp, 837 const char *argumentHelp,
837 const char *description, 838 const char *description,
838 uint16_t *val) 839 uint16_t *val)
839{ 840{
840 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 841 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
841 .name = name, 842 .name = name,
842 .argumentHelp = argumentHelp, 843 .argumentHelp = argumentHelp,
843 .description = description, 844 .description = description,
844 .require_argument = 1, 845 .require_argument = 1,
845 .processor = &set_uint16, 846 .processor = &set_uint16,
846 .scls = (void *) val}; 847 .scls = (void *)val };
847 848
848 return clo; 849 return clo;
849} 850}
@@ -852,8 +853,7 @@ GNUNET_GETOPT_option_uint16 (char shortName,
852/** 853/**
853 * Closure for #set_base32(). 854 * Closure for #set_base32().
854 */ 855 */
855struct Base32Context 856struct Base32Context {
856{
857 /** 857 /**
858 * Value to initialize (already allocated) 858 * Value to initialize (already allocated)
859 */ 859 */
@@ -880,26 +880,26 @@ struct Base32Context
880 * @return #GNUNET_OK if parsing the value worked 880 * @return #GNUNET_OK if parsing the value worked
881 */ 881 */
882static int 882static int
883set_base32 (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx, 883set_base32(struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
884 void *scls, 884 void *scls,
885 const char *option, 885 const char *option,
886 const char *value) 886 const char *value)
887{ 887{
888 struct Base32Context *bc = scls; 888 struct Base32Context *bc = scls;
889 889
890 (void) ctx; 890 (void)ctx;
891 if (GNUNET_OK != GNUNET_STRINGS_string_to_data (value, 891 if (GNUNET_OK != GNUNET_STRINGS_string_to_data(value,
892 strlen (value), 892 strlen(value),
893 bc->val, 893 bc->val,
894 bc->val_size)) 894 bc->val_size))
895 { 895 {
896 fprintf ( 896 fprintf(
897 stderr, 897 stderr,
898 _ ( 898 _(
899 "Argument `%s' malformed. Expected base32 (Crockford) encoded value.\n"), 899 "Argument `%s' malformed. Expected base32 (Crockford) encoded value.\n"),
900 option); 900 option);
901 return GNUNET_SYSERR; 901 return GNUNET_SYSERR;
902 } 902 }
903 return GNUNET_OK; 903 return GNUNET_OK;
904} 904}
905 905
@@ -911,9 +911,9 @@ set_base32 (struct GNUNET_GETOPT_CommandLineProcessorContext *ctx,
911 * @param cls value to GNUNET_free() 911 * @param cls value to GNUNET_free()
912 */ 912 */
913static void 913static void
914free_bc (void *cls) 914free_bc(void *cls)
915{ 915{
916 GNUNET_free (cls); 916 GNUNET_free(cls);
917} 917}
918 918
919 919
@@ -929,22 +929,22 @@ free_bc (void *cls)
929 * @param val_size size of @a val in bytes 929 * @param val_size size of @a val in bytes
930 */ 930 */
931struct GNUNET_GETOPT_CommandLineOption 931struct GNUNET_GETOPT_CommandLineOption
932GNUNET_GETOPT_option_base32_fixed_size (char shortName, 932GNUNET_GETOPT_option_base32_fixed_size(char shortName,
933 const char *name, 933 const char *name,
934 const char *argumentHelp, 934 const char *argumentHelp,
935 const char *description, 935 const char *description,
936 void *val, 936 void *val,
937 size_t val_size) 937 size_t val_size)
938{ 938{
939 struct Base32Context *bc = GNUNET_new (struct Base32Context); 939 struct Base32Context *bc = GNUNET_new(struct Base32Context);
940 struct GNUNET_GETOPT_CommandLineOption clo = {.shortName = shortName, 940 struct GNUNET_GETOPT_CommandLineOption clo = { .shortName = shortName,
941 .name = name, 941 .name = name,
942 .argumentHelp = argumentHelp, 942 .argumentHelp = argumentHelp,
943 .description = description, 943 .description = description,
944 .require_argument = 1, 944 .require_argument = 1,
945 .processor = &set_base32, 945 .processor = &set_base32,
946 .cleaner = &free_bc, 946 .cleaner = &free_bc,
947 .scls = (void *) bc}; 947 .scls = (void *)bc };
948 948
949 bc->val = val; 949 bc->val = val;
950 bc->val_size = val_size; 950 bc->val_size = val_size;
@@ -959,7 +959,7 @@ GNUNET_GETOPT_option_base32_fixed_size (char shortName,
959 * @return @a opt with the mandatory flag set. 959 * @return @a opt with the mandatory flag set.
960 */ 960 */
961struct GNUNET_GETOPT_CommandLineOption 961struct GNUNET_GETOPT_CommandLineOption
962GNUNET_GETOPT_option_mandatory (struct GNUNET_GETOPT_CommandLineOption opt) 962GNUNET_GETOPT_option_mandatory(struct GNUNET_GETOPT_CommandLineOption opt)
963{ 963{
964 opt.option_mandatory = 1; 964 opt.option_mandatory = 1;
965 return opt; 965 return opt;
@@ -973,7 +973,7 @@ GNUNET_GETOPT_option_mandatory (struct GNUNET_GETOPT_CommandLineOption opt)
973 * @return @a opt with the exclusive flag set. 973 * @return @a opt with the exclusive flag set.
974 */ 974 */
975struct GNUNET_GETOPT_CommandLineOption 975struct GNUNET_GETOPT_CommandLineOption
976GNUNET_GETOPT_option_exclusive (struct GNUNET_GETOPT_CommandLineOption opt) 976GNUNET_GETOPT_option_exclusive(struct GNUNET_GETOPT_CommandLineOption opt)
977{ 977{
978 opt.option_exclusive = 1; 978 opt.option_exclusive = 1;
979 return opt; 979 return opt;
diff --git a/src/util/gnunet-config-diff.c b/src/util/gnunet-config-diff.c
index 207b9518a..214d6d73f 100644
--- a/src/util/gnunet-config-diff.c
+++ b/src/util/gnunet-config-diff.c
@@ -2,22 +2,22 @@
2#include <gnunet_util_lib.h> 2#include <gnunet_util_lib.h>
3 3
4int 4int
5main (int argc, char **argv) 5main(int argc, char **argv)
6{ 6{
7 struct GNUNET_CONFIGURATION_Handle *i1; 7 struct GNUNET_CONFIGURATION_Handle *i1;
8 struct GNUNET_CONFIGURATION_Handle *i2; 8 struct GNUNET_CONFIGURATION_Handle *i2;
9 9
10 if (argc != 3) 10 if (argc != 3)
11 { 11 {
12 fprintf (stderr, "Invoke using `%s DEFAULTS-IN DIFFS'\n", argv[0]); 12 fprintf(stderr, "Invoke using `%s DEFAULTS-IN DIFFS'\n", argv[0]);
13 return 1;
14 }
15 i1 = GNUNET_CONFIGURATION_create();
16 i2 = GNUNET_CONFIGURATION_create();
17 if ((GNUNET_OK != GNUNET_CONFIGURATION_load(i1, argv[1])) ||
18 (GNUNET_OK != GNUNET_CONFIGURATION_load(i2, argv[2])))
13 return 1; 19 return 1;
14 } 20 if (GNUNET_OK != GNUNET_CONFIGURATION_write_diffs(i1, i2, argv[2]))
15 i1 = GNUNET_CONFIGURATION_create ();
16 i2 = GNUNET_CONFIGURATION_create ();
17 if ((GNUNET_OK != GNUNET_CONFIGURATION_load (i1, argv[1])) ||
18 (GNUNET_OK != GNUNET_CONFIGURATION_load (i2, argv[2])))
19 return 1;
20 if (GNUNET_OK != GNUNET_CONFIGURATION_write_diffs (i1, i2, argv[2]))
21 return 2; 21 return 2;
22 return 0; 22 return 0;
23} 23}
diff --git a/src/util/gnunet-config.c b/src/util/gnunet-config.c
index 3b9b64d4e..c67237a27 100644
--- a/src/util/gnunet-config.c
+++ b/src/util/gnunet-config.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/gnunet-config.c 22 * @file util/gnunet-config.c
@@ -80,36 +80,36 @@ static int rewrite;
80 * @param value value of the option 80 * @param value value of the option
81 */ 81 */
82static void 82static void
83print_option (void *cls, 83print_option(void *cls,
84 const char *section, 84 const char *section,
85 const char *option, 85 const char *option,
86 const char *value) 86 const char *value)
87{ 87{
88 const struct GNUNET_CONFIGURATION_Handle *cfg = cls; 88 const struct GNUNET_CONFIGURATION_Handle *cfg = cls;
89 89
90 (void) section; 90 (void)section;
91 if (is_filename) 91 if (is_filename)
92 { 92 {
93 char *value_fn; 93 char *value_fn;
94 char *fn; 94 char *fn;
95 95
96 GNUNET_assert (GNUNET_OK == 96 GNUNET_assert(GNUNET_OK ==
97 GNUNET_CONFIGURATION_get_value_filename (cfg, 97 GNUNET_CONFIGURATION_get_value_filename(cfg,
98 section, 98 section,
99 option, 99 option,
100 &value_fn)); 100 &value_fn));
101 fn = GNUNET_STRINGS_filename_expand (value_fn); 101 fn = GNUNET_STRINGS_filename_expand(value_fn);
102 if (NULL == fn) 102 if (NULL == fn)
103 fn = value_fn; 103 fn = value_fn;
104 else 104 else
105 GNUNET_free (value_fn); 105 GNUNET_free(value_fn);
106 fprintf (stdout, "%s = %s\n", option, fn); 106 fprintf(stdout, "%s = %s\n", option, fn);
107 GNUNET_free (fn); 107 GNUNET_free(fn);
108 } 108 }
109 else 109 else
110 { 110 {
111 fprintf (stdout, "%s = %s\n", option, value); 111 fprintf(stdout, "%s = %s\n", option, value);
112 } 112 }
113} 113}
114 114
115 115
@@ -120,10 +120,10 @@ print_option (void *cls,
120 * @param section a section in the configuration file 120 * @param section a section in the configuration file
121 */ 121 */
122static void 122static void
123print_section_name (void *cls, const char *section) 123print_section_name(void *cls, const char *section)
124{ 124{
125 (void) cls; 125 (void)cls;
126 fprintf (stdout, "%s\n", section); 126 fprintf(stdout, "%s\n", section);
127} 127}
128 128
129 129
@@ -137,133 +137,133 @@ print_section_name (void *cls, const char *section)
137 * @param cfg configuration 137 * @param cfg configuration
138 */ 138 */
139static void 139static void
140run (void *cls, 140run(void *cls,
141 char *const *args, 141 char *const *args,
142 const char *cfgfile, 142 const char *cfgfile,
143 const struct GNUNET_CONFIGURATION_Handle *cfg) 143 const struct GNUNET_CONFIGURATION_Handle *cfg)
144{ 144{
145 struct GNUNET_CONFIGURATION_Handle *out = NULL; 145 struct GNUNET_CONFIGURATION_Handle *out = NULL;
146 struct GNUNET_CONFIGURATION_Handle *diff = NULL; 146 struct GNUNET_CONFIGURATION_Handle *diff = NULL;
147 char *cfg_fn; 147 char *cfg_fn;
148 148
149 (void) cls; 149 (void)cls;
150 (void) args; 150 (void)args;
151 if (NULL != backend_check) 151 if (NULL != backend_check)
152 {
153 char *name;
154
155 GNUNET_asprintf (&name, "libgnunet_plugin_%s", backend_check);
156 global_ret = (GNUNET_OK == GNUNET_PLUGIN_test (name)) ? 0 : 77;
157 GNUNET_free (name);
158 return;
159 }
160 if (rewrite)
161 {
162 struct GNUNET_CONFIGURATION_Handle *def;
163
164 def = GNUNET_CONFIGURATION_create ();
165 if (GNUNET_OK != GNUNET_CONFIGURATION_load (def, NULL))
166 { 152 {
167 fprintf (stderr, _ ("failed to load configuration defaults")); 153 char *name;
168 global_ret = 1; 154
155 GNUNET_asprintf(&name, "libgnunet_plugin_%s", backend_check);
156 global_ret = (GNUNET_OK == GNUNET_PLUGIN_test(name)) ? 0 : 77;
157 GNUNET_free(name);
169 return; 158 return;
170 } 159 }
171 diff = GNUNET_CONFIGURATION_get_diff (def, cfg); 160 if (rewrite)
172 cfg = diff;
173 }
174 if (((! rewrite) && (NULL == section)) || list_sections)
175 {
176 if (! list_sections)
177 { 161 {
178 fprintf (stderr, 162 struct GNUNET_CONFIGURATION_Handle *def;
179 _ ("%s or %s argument is required\n"), 163
180 "--section", 164 def = GNUNET_CONFIGURATION_create();
181 "--list-sections"); 165 if (GNUNET_OK != GNUNET_CONFIGURATION_load(def, NULL))
182 global_ret = 1; 166 {
167 fprintf(stderr, _("failed to load configuration defaults"));
168 global_ret = 1;
169 return;
170 }
171 diff = GNUNET_CONFIGURATION_get_diff(def, cfg);
172 cfg = diff;
183 } 173 }
184 else 174 if (((!rewrite) && (NULL == section)) || list_sections)
185 { 175 {
186 fprintf (stderr, _ ("The following sections are available:\n")); 176 if (!list_sections)
187 GNUNET_CONFIGURATION_iterate_sections (cfg, &print_section_name, NULL); 177 {
178 fprintf(stderr,
179 _("%s or %s argument is required\n"),
180 "--section",
181 "--list-sections");
182 global_ret = 1;
183 }
184 else
185 {
186 fprintf(stderr, _("The following sections are available:\n"));
187 GNUNET_CONFIGURATION_iterate_sections(cfg, &print_section_name, NULL);
188 }
189 goto cleanup;
188 } 190 }
189 goto cleanup;
190 }
191 191
192 if ((NULL != section) && (NULL == value)) 192 if ((NULL != section) && (NULL == value))
193 {
194 if (NULL == option)
195 {
196 GNUNET_CONFIGURATION_iterate_section_values (cfg,
197 section,
198 &print_option,
199 (void *) cfg);
200 }
201 else
202 { 193 {
203 if (is_filename) 194 if (NULL == option)
204 {
205 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg,
206 section,
207 option,
208 &value))
209 { 195 {
210 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, section, option); 196 GNUNET_CONFIGURATION_iterate_section_values(cfg,
211 global_ret = 3; 197 section,
212 goto cleanup; 198 &print_option,
199 (void *)cfg);
213 } 200 }
214 }
215 else 201 else
216 {
217 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg,
218 section,
219 option,
220 &value))
221 { 202 {
222 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, section, option); 203 if (is_filename)
223 global_ret = 3; 204 {
224 goto cleanup; 205 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg,
206 section,
207 option,
208 &value))
209 {
210 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, section, option);
211 global_ret = 3;
212 goto cleanup;
213 }
214 }
215 else
216 {
217 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg,
218 section,
219 option,
220 &value))
221 {
222 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, section, option);
223 global_ret = 3;
224 goto cleanup;
225 }
226 }
227 fprintf(stdout, "%s\n", value);
225 } 228 }
226 }
227 fprintf (stdout, "%s\n", value);
228 } 229 }
229 }
230 else if (NULL != section) 230 else if (NULL != section)
231 {
232 if (NULL == option)
233 { 231 {
234 fprintf (stderr, _ ("--option argument required to set value\n")); 232 if (NULL == option)
235 global_ret = 1; 233 {
236 goto cleanup; 234 fprintf(stderr, _("--option argument required to set value\n"));
235 global_ret = 1;
236 goto cleanup;
237 }
238 out = GNUNET_CONFIGURATION_dup(cfg);
239 GNUNET_CONFIGURATION_set_value_string(out, section, option, value);
237 } 240 }
238 out = GNUNET_CONFIGURATION_dup (cfg);
239 GNUNET_CONFIGURATION_set_value_string (out, section, option, value);
240 }
241 cfg_fn = NULL; 241 cfg_fn = NULL;
242 if (NULL == cfgfile) 242 if (NULL == cfgfile)
243 { 243 {
244 const char *xdg = getenv ("XDG_CONFIG_HOME"); 244 const char *xdg = getenv("XDG_CONFIG_HOME");
245 if (NULL != xdg) 245 if (NULL != xdg)
246 GNUNET_asprintf (&cfg_fn, 246 GNUNET_asprintf(&cfg_fn,
247 "%s%s%s", 247 "%s%s%s",
248 xdg, 248 xdg,
249 DIR_SEPARATOR_STR, 249 DIR_SEPARATOR_STR,
250 GNUNET_OS_project_data_get ()->config_file); 250 GNUNET_OS_project_data_get()->config_file);
251 else 251 else
252 cfg_fn = GNUNET_strdup (GNUNET_OS_project_data_get ()->user_config_file); 252 cfg_fn = GNUNET_strdup(GNUNET_OS_project_data_get()->user_config_file);
253 cfgfile = cfg_fn; 253 cfgfile = cfg_fn;
254 } 254 }
255 if ((NULL != diff) || (NULL != out)) 255 if ((NULL != diff) || (NULL != out))
256 { 256 {
257 if (GNUNET_OK != 257 if (GNUNET_OK !=
258 GNUNET_CONFIGURATION_write ((NULL == out) ? diff : out, cfgfile)) 258 GNUNET_CONFIGURATION_write((NULL == out) ? diff : out, cfgfile))
259 global_ret = 2; 259 global_ret = 2;
260 } 260 }
261 GNUNET_free_non_null (cfg_fn); 261 GNUNET_free_non_null(cfg_fn);
262 if (NULL != out) 262 if (NULL != out)
263 GNUNET_CONFIGURATION_destroy (out); 263 GNUNET_CONFIGURATION_destroy(out);
264cleanup: 264cleanup:
265 if (NULL != diff) 265 if (NULL != diff)
266 GNUNET_CONFIGURATION_destroy (diff); 266 GNUNET_CONFIGURATION_destroy(diff);
267} 267}
268 268
269 269
@@ -275,63 +275,63 @@ cleanup:
275 * @return 0 ok, 1 on error 275 * @return 0 ok, 1 on error
276 */ 276 */
277int 277int
278main (int argc, char *const *argv) 278main(int argc, char *const *argv)
279{ 279{
280 struct GNUNET_GETOPT_CommandLineOption options[] = 280 struct GNUNET_GETOPT_CommandLineOption options[] =
281 {GNUNET_GETOPT_option_flag ( 281 { GNUNET_GETOPT_option_flag(
282 'f', 282 'f',
283 "filename", 283 "filename",
284 gettext_noop ("interpret option value as a filename (with $-expansion)"), 284 gettext_noop("interpret option value as a filename (with $-expansion)"),
285 &is_filename), 285 &is_filename),
286 GNUNET_GETOPT_option_exclusive (GNUNET_GETOPT_option_string ( 286 GNUNET_GETOPT_option_exclusive(GNUNET_GETOPT_option_string(
287 'b', 287 'b',
288 "supported-backend", 288 "supported-backend",
289 "BACKEND", 289 "BACKEND",
290 gettext_noop ( 290 gettext_noop(
291 "test if the current installation supports the specified BACKEND"), 291 "test if the current installation supports the specified BACKEND"),
292 &backend_check)), 292 &backend_check)),
293 GNUNET_GETOPT_option_string ('s', 293 GNUNET_GETOPT_option_string('s',
294 "section", 294 "section",
295 "SECTION", 295 "SECTION",
296 gettext_noop ( 296 gettext_noop(
297 "name of the section to access"), 297 "name of the section to access"),
298 &section), 298 &section),
299 GNUNET_GETOPT_option_string ('o', 299 GNUNET_GETOPT_option_string('o',
300 "option", 300 "option",
301 "OPTION", 301 "OPTION",
302 gettext_noop ("name of the option to access"), 302 gettext_noop("name of the option to access"),
303 &option), 303 &option),
304 GNUNET_GETOPT_option_string ('V', 304 GNUNET_GETOPT_option_string('V',
305 "value", 305 "value",
306 "VALUE", 306 "VALUE",
307 gettext_noop ("value to set"), 307 gettext_noop("value to set"),
308 &value), 308 &value),
309 GNUNET_GETOPT_option_flag ('S', 309 GNUNET_GETOPT_option_flag('S',
310 "list-sections", 310 "list-sections",
311 gettext_noop ( 311 gettext_noop(
312 "print available configuration sections"), 312 "print available configuration sections"),
313 &list_sections), 313 &list_sections),
314 GNUNET_GETOPT_option_flag ( 314 GNUNET_GETOPT_option_flag(
315 'w', 315 'w',
316 "rewrite", 316 "rewrite",
317 gettext_noop ( 317 gettext_noop(
318 "write configuration file that only contains delta to defaults"), 318 "write configuration file that only contains delta to defaults"),
319 &rewrite), 319 &rewrite),
320 GNUNET_GETOPT_OPTION_END}; 320 GNUNET_GETOPT_OPTION_END };
321 int ret; 321 int ret;
322 322
323 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) 323 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
324 return 2; 324 return 2;
325 325
326 ret = 326 ret =
327 GNUNET_PROGRAM_run (argc, 327 GNUNET_PROGRAM_run(argc,
328 argv, 328 argv,
329 "gnunet-config [OPTIONS]", 329 "gnunet-config [OPTIONS]",
330 gettext_noop ("Manipulate GNUnet configuration files"), 330 gettext_noop("Manipulate GNUnet configuration files"),
331 options, 331 options,
332 &run, 332 &run,
333 NULL); 333 NULL);
334 GNUNET_free ((void *) argv); 334 GNUNET_free((void *)argv);
335 if (GNUNET_OK == ret) 335 if (GNUNET_OK == ret)
336 return global_ret; 336 return global_ret;
337 return ret; 337 return ret;
diff --git a/src/util/gnunet-ecc.c b/src/util/gnunet-ecc.c
index e7a170b81..7fb8150f6 100644
--- a/src/util/gnunet-ecc.c
+++ b/src/util/gnunet-ecc.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/gnunet-ecc.c 22 * @file util/gnunet-ecc.c
@@ -31,7 +31,7 @@
31/** 31/**
32 * Number of characters a Base32-encoded public key requires. 32 * Number of characters a Base32-encoded public key requires.
33 */ 33 */
34#define KEY_STR_LEN sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) * 8 / 5 + 1 34#define KEY_STR_LEN sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) * 8 / 5 + 1
35 35
36/** 36/**
37 * Flag for listing public key. 37 * Flag for listing public key.
@@ -76,7 +76,7 @@ static unsigned int make_keys;
76 * @param prefix Desired prefix for the public keys, NULL if any key is OK. 76 * @param prefix Desired prefix for the public keys, NULL if any key is OK.
77 */ 77 */
78static void 78static void
79create_keys (const char *fn, const char *prefix) 79create_keys(const char *fn, const char *prefix)
80{ 80{
81 FILE *f; 81 FILE *f;
82 struct GNUNET_CRYPTO_EddsaPrivateKey *pk; 82 struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
@@ -89,120 +89,120 @@ create_keys (const char *fn, const char *prefix)
89 unsigned target_byte; 89 unsigned target_byte;
90 char *s; 90 char *s;
91 91
92 if (NULL == (f = fopen (fn, "w+"))) 92 if (NULL == (f = fopen(fn, "w+")))
93 { 93 {
94 fprintf (stderr, _ ("Failed to open `%s': %s\n"), fn, strerror (errno)); 94 fprintf(stderr, _("Failed to open `%s': %s\n"), fn, strerror(errno));
95 return; 95 return;
96 } 96 }
97 if (NULL != prefix) 97 if (NULL != prefix)
98 { 98 {
99 len = GNUNET_strlcpy (vanity, prefix, sizeof (vanity)); 99 len = GNUNET_strlcpy(vanity, prefix, sizeof(vanity));
100 n = len * 5 / 8; 100 n = len * 5 / 8;
101 rest = len * 5 % 8; 101 rest = len * 5 % 8;
102 102
103 memset (&vanity[len], '0', KEY_STR_LEN - len); 103 memset(&vanity[len], '0', KEY_STR_LEN - len);
104 vanity[KEY_STR_LEN] = '\0'; 104 vanity[KEY_STR_LEN] = '\0';
105 GNUNET_assert (GNUNET_OK == 105 GNUNET_assert(GNUNET_OK ==
106 GNUNET_CRYPTO_eddsa_public_key_from_string (vanity, 106 GNUNET_CRYPTO_eddsa_public_key_from_string(vanity,
107 KEY_STR_LEN, 107 KEY_STR_LEN,
108 &target_pub)); 108 &target_pub));
109 if (0 != rest) 109 if (0 != rest)
110 { 110 {
111 /** 111 /**
112 * Documentation by example: 112 * Documentation by example:
113 * vanity = "A" 113 * vanity = "A"
114 * len = 1 114 * len = 1
115 * n = 5/8 = 0 (bytes) 115 * n = 5/8 = 0 (bytes)
116 * rest = 5%8 = 5 (bits) 116 * rest = 5%8 = 5 (bits)
117 * mask = ~(2**(8 - 5) - 1) = ~(2**3 - 1) = ~(8 - 1) = ~b111 = b11111000 117 * mask = ~(2**(8 - 5) - 1) = ~(2**3 - 1) = ~(8 - 1) = ~b111 = b11111000
118 */ 118 */
119 mask = ~((int) pow (2, 8 - rest) - 1); 119 mask = ~((int)pow(2, 8 - rest) - 1);
120 target_byte = ((unsigned char *) &target_pub)[n] & mask; 120 target_byte = ((unsigned char *)&target_pub)[n] & mask;
121 }
122 else
123 {
124 /* Just so old (debian) versions of GCC calm down with the warnings. */
125 mask = target_byte = 0;
126 }
127 s = GNUNET_CRYPTO_eddsa_public_key_to_string(&target_pub);
128 fprintf(stderr,
129 _("Generating %u keys like %s, please wait"),
130 make_keys,
131 s);
132 GNUNET_free(s);
133 fprintf(stderr, "\nattempt %s [%u, %X]\n", vanity, (unsigned int)n, mask);
121 } 134 }
122 else 135 else
123 { 136 {
137 fprintf(stderr, _("Generating %u keys, please wait"), make_keys);
124 /* Just so old (debian) versions of GCC calm down with the warnings. */ 138 /* Just so old (debian) versions of GCC calm down with the warnings. */
125 mask = target_byte = 0; 139 n = rest = target_byte = mask = 0;
126 } 140 }
127 s = GNUNET_CRYPTO_eddsa_public_key_to_string (&target_pub);
128 fprintf (stderr,
129 _ ("Generating %u keys like %s, please wait"),
130 make_keys,
131 s);
132 GNUNET_free (s);
133 fprintf (stderr, "\nattempt %s [%u, %X]\n", vanity, (unsigned int) n, mask);
134 }
135 else
136 {
137 fprintf (stderr, _ ("Generating %u keys, please wait"), make_keys);
138 /* Just so old (debian) versions of GCC calm down with the warnings. */
139 n = rest = target_byte = mask = 0;
140 }
141 141
142 while (0 < make_keys--) 142 while (0 < make_keys--)
143 {
144 fprintf (stderr, ".");
145 if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create ()))
146 {
147 GNUNET_break (0);
148 break;
149 }
150 if (NULL != prefix)
151 { 143 {
152 struct GNUNET_CRYPTO_EddsaPublicKey newkey; 144 fprintf(stderr, ".");
153 145 if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create()))
154 GNUNET_CRYPTO_eddsa_key_get_public (pk, &newkey);
155 if (0 != memcmp (&target_pub, &newkey, n))
156 {
157 make_keys++;
158 continue;
159 }
160 if (0 != rest)
161 {
162 unsigned char new_byte;
163
164 new_byte = ((unsigned char *) &newkey)[n] & mask;
165 if (target_byte != new_byte)
166 { 146 {
167 make_keys++; 147 GNUNET_break(0);
168 continue; 148 break;
169 } 149 }
170 } 150 if (NULL != prefix)
171 } 151 {
172 if (GNUNET_TESTING_HOSTKEYFILESIZE != 152 struct GNUNET_CRYPTO_EddsaPublicKey newkey;
173 fwrite (pk, 1, GNUNET_TESTING_HOSTKEYFILESIZE, f)) 153
174 { 154 GNUNET_CRYPTO_eddsa_key_get_public(pk, &newkey);
175 fprintf (stderr, 155 if (0 != memcmp(&target_pub, &newkey, n))
176 _ ("\nFailed to write to `%s': %s\n"), 156 {
177 fn, 157 make_keys++;
178 strerror (errno)); 158 continue;
179 GNUNET_free (pk); 159 }
180 break; 160 if (0 != rest)
161 {
162 unsigned char new_byte;
163
164 new_byte = ((unsigned char *)&newkey)[n] & mask;
165 if (target_byte != new_byte)
166 {
167 make_keys++;
168 continue;
169 }
170 }
171 }
172 if (GNUNET_TESTING_HOSTKEYFILESIZE !=
173 fwrite(pk, 1, GNUNET_TESTING_HOSTKEYFILESIZE, f))
174 {
175 fprintf(stderr,
176 _("\nFailed to write to `%s': %s\n"),
177 fn,
178 strerror(errno));
179 GNUNET_free(pk);
180 break;
181 }
182 GNUNET_free(pk);
181 } 183 }
182 GNUNET_free (pk);
183 }
184 if (UINT_MAX == make_keys) 184 if (UINT_MAX == make_keys)
185 fprintf (stderr, _ ("\nFinished!\n")); 185 fprintf(stderr, _("\nFinished!\n"));
186 else 186 else
187 fprintf (stderr, _ ("\nError, %u keys not generated\n"), make_keys); 187 fprintf(stderr, _("\nError, %u keys not generated\n"), make_keys);
188 fclose (f); 188 fclose(f);
189} 189}
190 190
191 191
192static void 192static void
193print_hex (const char *msg, const void *buf, size_t size) 193print_hex(const char *msg, const void *buf, size_t size)
194{ 194{
195 printf ("%s: ", msg); 195 printf("%s: ", msg);
196 for (size_t i = 0; i < size; i++) 196 for (size_t i = 0; i < size; i++)
197 { 197 {
198 printf ("%02hhx", ((const uint8_t *) buf)[i]); 198 printf("%02hhx", ((const uint8_t *)buf)[i]);
199 } 199 }
200 printf ("\n"); 200 printf("\n");
201} 201}
202 202
203 203
204static void 204static void
205print_examples_ecdh () 205print_examples_ecdh()
206{ 206{
207 struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1; 207 struct GNUNET_CRYPTO_EcdhePrivateKey *dh_priv1;
208 struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1; 208 struct GNUNET_CRYPTO_EcdhePublicKey *dh_pub1;
@@ -211,40 +211,40 @@ print_examples_ecdh ()
211 struct GNUNET_HashCode hash; 211 struct GNUNET_HashCode hash;
212 char buf[128]; 212 char buf[128];
213 213
214 dh_pub1 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey); 214 dh_pub1 = GNUNET_new(struct GNUNET_CRYPTO_EcdhePublicKey);
215 dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create (); 215 dh_priv1 = GNUNET_CRYPTO_ecdhe_key_create();
216 dh_pub2 = GNUNET_new (struct GNUNET_CRYPTO_EcdhePublicKey); 216 dh_pub2 = GNUNET_new(struct GNUNET_CRYPTO_EcdhePublicKey);
217 dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create (); 217 dh_priv2 = GNUNET_CRYPTO_ecdhe_key_create();
218 GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv1, dh_pub1); 218 GNUNET_CRYPTO_ecdhe_key_get_public(dh_priv1, dh_pub1);
219 GNUNET_CRYPTO_ecdhe_key_get_public (dh_priv2, dh_pub2); 219 GNUNET_CRYPTO_ecdhe_key_get_public(dh_priv2, dh_pub2);
220 220
221 GNUNET_assert (NULL != 221 GNUNET_assert(NULL !=
222 GNUNET_STRINGS_data_to_string (dh_priv1, 32, buf, 128)); 222 GNUNET_STRINGS_data_to_string(dh_priv1, 32, buf, 128));
223 printf ("ECDHE key 1:\n"); 223 printf("ECDHE key 1:\n");
224 printf ("private: %s\n", buf); 224 printf("private: %s\n", buf);
225 print_hex ("private(hex)", dh_priv1, sizeof *dh_priv1); 225 print_hex("private(hex)", dh_priv1, sizeof *dh_priv1);
226 GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub1, 32, buf, 128)); 226 GNUNET_assert(NULL != GNUNET_STRINGS_data_to_string(dh_pub1, 32, buf, 128));
227 printf ("public: %s\n", buf); 227 printf("public: %s\n", buf);
228 print_hex ("public(hex)", dh_pub1, sizeof *dh_pub1); 228 print_hex("public(hex)", dh_pub1, sizeof *dh_pub1);
229 229
230 GNUNET_assert (NULL != 230 GNUNET_assert(NULL !=
231 GNUNET_STRINGS_data_to_string (dh_priv2, 32, buf, 128)); 231 GNUNET_STRINGS_data_to_string(dh_priv2, 32, buf, 128));
232 printf ("ECDHE key 2:\n"); 232 printf("ECDHE key 2:\n");
233 printf ("private: %s\n", buf); 233 printf("private: %s\n", buf);
234 print_hex ("private(hex)", dh_priv2, sizeof *dh_priv2); 234 print_hex("private(hex)", dh_priv2, sizeof *dh_priv2);
235 GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (dh_pub2, 32, buf, 128)); 235 GNUNET_assert(NULL != GNUNET_STRINGS_data_to_string(dh_pub2, 32, buf, 128));
236 printf ("public: %s\n", buf); 236 printf("public: %s\n", buf);
237 print_hex ("public(hex)", dh_pub2, sizeof *dh_pub2); 237 print_hex("public(hex)", dh_pub2, sizeof *dh_pub2);
238 238
239 GNUNET_assert (GNUNET_OK == 239 GNUNET_assert(GNUNET_OK ==
240 GNUNET_CRYPTO_ecc_ecdh (dh_priv1, dh_pub2, &hash)); 240 GNUNET_CRYPTO_ecc_ecdh(dh_priv1, dh_pub2, &hash));
241 GNUNET_assert (NULL != GNUNET_STRINGS_data_to_string (&hash, 64, buf, 128)); 241 GNUNET_assert(NULL != GNUNET_STRINGS_data_to_string(&hash, 64, buf, 128));
242 printf ("ECDH shared secret: %s\n", buf); 242 printf("ECDH shared secret: %s\n", buf);
243 243
244 GNUNET_free (dh_priv1); 244 GNUNET_free(dh_priv1);
245 GNUNET_free (dh_priv2); 245 GNUNET_free(dh_priv2);
246 GNUNET_free (dh_pub1); 246 GNUNET_free(dh_pub1);
247 GNUNET_free (dh_pub2); 247 GNUNET_free(dh_pub2);
248} 248}
249 249
250 250
@@ -252,16 +252,16 @@ print_examples_ecdh ()
252 * Print some random example operations to stdout. 252 * Print some random example operations to stdout.
253 */ 253 */
254static void 254static void
255print_examples () 255print_examples()
256{ 256{
257 print_examples_ecdh (); 257 print_examples_ecdh();
258 // print_examples_ecdsa (); 258 // print_examples_ecdsa ();
259 // print_examples_eddsa (); 259 // print_examples_eddsa ();
260} 260}
261 261
262 262
263static void 263static void
264print_key (const char *filename) 264print_key(const char *filename)
265{ 265{
266 struct GNUNET_DISK_FileHandle *fd; 266 struct GNUNET_DISK_FileHandle *fd;
267 struct GNUNET_CRYPTO_EddsaPrivateKey private_key; 267 struct GNUNET_CRYPTO_EddsaPrivateKey private_key;
@@ -273,64 +273,64 @@ print_key (const char *filename)
273 unsigned int c; 273 unsigned int c;
274 ssize_t sret; 274 ssize_t sret;
275 275
276 if (GNUNET_YES != GNUNET_DISK_file_test (filename)) 276 if (GNUNET_YES != GNUNET_DISK_file_test(filename))
277 { 277 {
278 fprintf (stderr, _ ("Hostkeys file `%s' not found\n"), filename); 278 fprintf(stderr, _("Hostkeys file `%s' not found\n"), filename);
279 return; 279 return;
280 } 280 }
281 281
282 /* Check hostkey file size, read entire thing into memory */ 282 /* Check hostkey file size, read entire thing into memory */
283 if (GNUNET_OK != 283 if (GNUNET_OK !=
284 GNUNET_DISK_file_size (filename, &fs, GNUNET_YES, GNUNET_YES)) 284 GNUNET_DISK_file_size(filename, &fs, GNUNET_YES, GNUNET_YES))
285 fs = 0; 285 fs = 0;
286 if (0 == fs) 286 if (0 == fs)
287 { 287 {
288 fprintf (stderr, _ ("Hostkeys file `%s' is empty\n"), filename); 288 fprintf(stderr, _("Hostkeys file `%s' is empty\n"), filename);
289 return; /* File is empty */ 289 return; /* File is empty */
290 } 290 }
291 if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE)) 291 if (0 != (fs % GNUNET_TESTING_HOSTKEYFILESIZE))
292 { 292 {
293 fprintf (stderr, _ ("Incorrect hostkey file format: %s\n"), filename); 293 fprintf(stderr, _("Incorrect hostkey file format: %s\n"), filename);
294 return; 294 return;
295 } 295 }
296 fd = GNUNET_DISK_file_open (filename, 296 fd = GNUNET_DISK_file_open(filename,
297 GNUNET_DISK_OPEN_READ, 297 GNUNET_DISK_OPEN_READ,
298 GNUNET_DISK_PERM_NONE); 298 GNUNET_DISK_PERM_NONE);
299 if (NULL == fd) 299 if (NULL == fd)
300 { 300 {
301 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", filename); 301 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", filename);
302 return; 302 return;
303 } 303 }
304 hostkeys_data = GNUNET_malloc (fs); 304 hostkeys_data = GNUNET_malloc(fs);
305 sret = GNUNET_DISK_file_read (fd, hostkeys_data, fs); 305 sret = GNUNET_DISK_file_read(fd, hostkeys_data, fs);
306 if ((sret < 0) || (fs != (size_t) sret)) 306 if ((sret < 0) || (fs != (size_t)sret))
307 { 307 {
308 fprintf (stderr, _ ("Could not read hostkey file: %s\n"), filename); 308 fprintf(stderr, _("Could not read hostkey file: %s\n"), filename);
309 GNUNET_free (hostkeys_data); 309 GNUNET_free(hostkeys_data);
310 GNUNET_DISK_file_close (fd); 310 GNUNET_DISK_file_close(fd);
311 return; 311 return;
312 } 312 }
313 GNUNET_DISK_file_close (fd); 313 GNUNET_DISK_file_close(fd);
314 314
315 if (NULL == hostkeys_data) 315 if (NULL == hostkeys_data)
316 return; 316 return;
317 total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE; 317 total_hostkeys = fs / GNUNET_TESTING_HOSTKEYFILESIZE;
318 for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++) 318 for (c = 0; (c < total_hostkeys) && (c < list_keys_count); c++)
319 {
320 GNUNET_memcpy (&private_key,
321 hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
322 GNUNET_TESTING_HOSTKEYFILESIZE);
323 GNUNET_CRYPTO_eddsa_key_get_public (&private_key, &public_key);
324 hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string (&public_key);
325 if (NULL != hostkey_str)
326 { 319 {
327 fprintf (stderr, "%4u: %s\n", c, hostkey_str); 320 GNUNET_memcpy(&private_key,
328 GNUNET_free (hostkey_str); 321 hostkeys_data + (c * GNUNET_TESTING_HOSTKEYFILESIZE),
322 GNUNET_TESTING_HOSTKEYFILESIZE);
323 GNUNET_CRYPTO_eddsa_key_get_public(&private_key, &public_key);
324 hostkey_str = GNUNET_CRYPTO_eddsa_public_key_to_string(&public_key);
325 if (NULL != hostkey_str)
326 {
327 fprintf(stderr, "%4u: %s\n", c, hostkey_str);
328 GNUNET_free(hostkey_str);
329 }
330 else
331 fprintf(stderr, "%4u: %s\n", c, "invalid");
329 } 332 }
330 else 333 GNUNET_free(hostkeys_data);
331 fprintf (stderr, "%4u: %s\n", c, "invalid");
332 }
333 GNUNET_free (hostkeys_data);
334} 334}
335 335
336 336
@@ -343,69 +343,69 @@ print_key (const char *filename)
343 * @param cfg configuration 343 * @param cfg configuration
344 */ 344 */
345static void 345static void
346run (void *cls, 346run(void *cls,
347 char *const *args, 347 char *const *args,
348 const char *cfgfile, 348 const char *cfgfile,
349 const struct GNUNET_CONFIGURATION_Handle *cfg) 349 const struct GNUNET_CONFIGURATION_Handle *cfg)
350{ 350{
351 (void) cls; 351 (void)cls;
352 (void) cfgfile; 352 (void)cfgfile;
353 (void) cfg; 353 (void)cfg;
354 354
355 if (print_examples_flag) 355 if (print_examples_flag)
356 { 356 {
357 print_examples (); 357 print_examples();
358 return; 358 return;
359 } 359 }
360 if (NULL == args[0]) 360 if (NULL == args[0])
361 { 361 {
362 fprintf (stderr, "%s", _ ("No hostkey file specified on command line\n")); 362 fprintf(stderr, "%s", _("No hostkey file specified on command line\n"));
363 return; 363 return;
364 } 364 }
365 if (list_keys) 365 if (list_keys)
366 { 366 {
367 print_key (args[0]); 367 print_key(args[0]);
368 return; 368 return;
369 } 369 }
370 if (make_keys > 0) 370 if (make_keys > 0)
371 { 371 {
372 create_keys (args[0], args[1]); 372 create_keys(args[0], args[1]);
373 return;
374 }
375 if (print_public_key || print_public_key_hex || print_private_key)
376 {
377 char *str;
378 struct GNUNET_DISK_FileHandle *keyfile;
379 struct GNUNET_CRYPTO_EddsaPrivateKey pk;
380 struct GNUNET_CRYPTO_EddsaPublicKey pub;
381
382 keyfile = GNUNET_DISK_file_open (args[0],
383 GNUNET_DISK_OPEN_READ,
384 GNUNET_DISK_PERM_NONE);
385 if (NULL == keyfile)
386 return; 373 return;
387 while (sizeof (pk) == GNUNET_DISK_file_read (keyfile, &pk, sizeof (pk))) 374 }
375 if (print_public_key || print_public_key_hex || print_private_key)
388 { 376 {
389 GNUNET_CRYPTO_eddsa_key_get_public (&pk, &pub); 377 char *str;
390 if (print_public_key_hex) 378 struct GNUNET_DISK_FileHandle *keyfile;
391 { 379 struct GNUNET_CRYPTO_EddsaPrivateKey pk;
392 print_hex ("HEX:", &pub, sizeof (pub)); 380 struct GNUNET_CRYPTO_EddsaPublicKey pub;
393 } 381
394 else if (print_public_key) 382 keyfile = GNUNET_DISK_file_open(args[0],
395 { 383 GNUNET_DISK_OPEN_READ,
396 str = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub); 384 GNUNET_DISK_PERM_NONE);
397 fprintf (stdout, "%s\n", str); 385 if (NULL == keyfile)
398 GNUNET_free (str); 386 return;
399 } 387 while (sizeof(pk) == GNUNET_DISK_file_read(keyfile, &pk, sizeof(pk)))
400 else if (print_private_key) 388 {
401 { 389 GNUNET_CRYPTO_eddsa_key_get_public(&pk, &pub);
402 str = GNUNET_CRYPTO_eddsa_private_key_to_string (&pk); 390 if (print_public_key_hex)
403 fprintf (stdout, "%s\n", str); 391 {
404 GNUNET_free (str); 392 print_hex("HEX:", &pub, sizeof(pub));
405 } 393 }
394 else if (print_public_key)
395 {
396 str = GNUNET_CRYPTO_eddsa_public_key_to_string(&pub);
397 fprintf(stdout, "%s\n", str);
398 GNUNET_free(str);
399 }
400 else if (print_private_key)
401 {
402 str = GNUNET_CRYPTO_eddsa_private_key_to_string(&pk);
403 fprintf(stdout, "%s\n", str);
404 GNUNET_free(str);
405 }
406 }
407 GNUNET_DISK_file_close(keyfile);
406 } 408 }
407 GNUNET_DISK_file_close (keyfile);
408 }
409} 409}
410 410
411 411
@@ -417,66 +417,66 @@ run (void *cls,
417 * @return 0 ok, 1 on error 417 * @return 0 ok, 1 on error
418 */ 418 */
419int 419int
420main (int argc, char *const *argv) 420main(int argc, char *const *argv)
421{ 421{
422 struct GNUNET_GETOPT_CommandLineOption options[] = 422 struct GNUNET_GETOPT_CommandLineOption options[] =
423 {GNUNET_GETOPT_option_flag ('i', 423 { GNUNET_GETOPT_option_flag('i',
424 "iterate", 424 "iterate",
425 gettext_noop ( 425 gettext_noop(
426 "list keys included in a file (for testing)"), 426 "list keys included in a file (for testing)"),
427 &list_keys), 427 &list_keys),
428 GNUNET_GETOPT_option_uint ( 428 GNUNET_GETOPT_option_uint(
429 'e', 429 'e',
430 "end=", 430 "end=",
431 "COUNT", 431 "COUNT",
432 gettext_noop ("number of keys to list included in a file (for testing)"), 432 gettext_noop("number of keys to list included in a file (for testing)"),
433 &list_keys_count), 433 &list_keys_count),
434 GNUNET_GETOPT_option_uint ( 434 GNUNET_GETOPT_option_uint(
435 'g', 435 'g',
436 "generate-keys", 436 "generate-keys",
437 "COUNT", 437 "COUNT",
438 gettext_noop ("create COUNT public-private key pairs (for testing)"), 438 gettext_noop("create COUNT public-private key pairs (for testing)"),
439 &make_keys), 439 &make_keys),
440 GNUNET_GETOPT_option_flag ('p', 440 GNUNET_GETOPT_option_flag('p',
441 "print-public-key", 441 "print-public-key",
442 gettext_noop ( 442 gettext_noop(
443 "print the public key in ASCII format"), 443 "print the public key in ASCII format"),
444 &print_public_key), 444 &print_public_key),
445 GNUNET_GETOPT_option_flag ('P', 445 GNUNET_GETOPT_option_flag('P',
446 "print-private-key", 446 "print-private-key",
447 gettext_noop ( 447 gettext_noop(
448 "print the private key in ASCII format"), 448 "print the private key in ASCII format"),
449 &print_private_key), 449 &print_private_key),
450 GNUNET_GETOPT_option_flag ('x', 450 GNUNET_GETOPT_option_flag('x',
451 "print-hex", 451 "print-hex",
452 gettext_noop ( 452 gettext_noop(
453 "print the public key in HEX format"), 453 "print the public key in HEX format"),
454 &print_public_key_hex), 454 &print_public_key_hex),
455 GNUNET_GETOPT_option_flag ( 455 GNUNET_GETOPT_option_flag(
456 'E', 456 'E',
457 "examples", 457 "examples",
458 gettext_noop ( 458 gettext_noop(
459 "print examples of ECC operations (used for compatibility testing)"), 459 "print examples of ECC operations (used for compatibility testing)"),
460 &print_examples_flag), 460 &print_examples_flag),
461 GNUNET_GETOPT_OPTION_END}; 461 GNUNET_GETOPT_OPTION_END };
462 int ret; 462 int ret;
463 463
464 list_keys_count = UINT32_MAX; 464 list_keys_count = UINT32_MAX;
465 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) 465 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
466 return 2; 466 return 2;
467 467
468 ret = (GNUNET_OK == 468 ret = (GNUNET_OK ==
469 GNUNET_PROGRAM_run (argc, 469 GNUNET_PROGRAM_run(argc,
470 argv, 470 argv,
471 "gnunet-ecc [OPTIONS] keyfile [VANITY_PREFIX]", 471 "gnunet-ecc [OPTIONS] keyfile [VANITY_PREFIX]",
472 gettext_noop ( 472 gettext_noop(
473 "Manipulate GNUnet private ECC key files"), 473 "Manipulate GNUnet private ECC key files"),
474 options, 474 options,
475 &run, 475 &run,
476 NULL)) 476 NULL))
477 ? 0 477 ? 0
478 : 1; 478 : 1;
479 GNUNET_free ((void *) argv); 479 GNUNET_free((void *)argv);
480 return ret; 480 return ret;
481} 481}
482 482
diff --git a/src/util/gnunet-helper-w32-console.c b/src/util/gnunet-helper-w32-console.c
index fdebd9a49..b773e27d7 100644
--- a/src/util/gnunet-helper-w32-console.c
+++ b/src/util/gnunet-helper-w32-console.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/gnunet-helper-w32-console.c 22 * @file src/util/gnunet-helper-w32-console.c
@@ -45,9 +45,9 @@ static HANDLE parent_handle;
45 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 45 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
46 */ 46 */
47static int 47static int
48write_all (int output, 48write_all(int output,
49 const void *buf, 49 const void *buf,
50 size_t size) 50 size_t size)
51{ 51{
52 const char *cbuf = buf; 52 const char *cbuf = buf;
53 size_t total; 53 size_t total;
@@ -55,17 +55,18 @@ write_all (int output,
55 55
56 total = 0; 56 total = 0;
57 do 57 do
58 { 58 {
59 wr = write (output, 59 wr = write(output,
60 &cbuf[total], 60 &cbuf[total],
61 size - total); 61 size - total);
62 if (wr > 0) 62 if (wr > 0)
63 total += wr; 63 total += wr;
64 } while ( (wr > 0) && (total < size) ); 64 }
65 while ((wr > 0) && (total < size));
65 if (wr <= 0) 66 if (wr <= 0)
66 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 67 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
67 "Failed to write to stdout: %s\n", 68 "Failed to write to stdout: %s\n",
68 strerror (errno)); 69 strerror(errno));
69 return (total == size) ? GNUNET_OK : GNUNET_SYSERR; 70 return (total == size) ? GNUNET_OK : GNUNET_SYSERR;
70} 71}
71 72
@@ -80,24 +81,24 @@ write_all (int output,
80 * @return #GNUNET_SYSERR to stop scanning (the pipe was broken somehow) 81 * @return #GNUNET_SYSERR to stop scanning (the pipe was broken somehow)
81 */ 82 */
82static int 83static int
83write_message (int output, 84write_message(int output,
84 uint16_t message_type, 85 uint16_t message_type,
85 const char *data, 86 const char *data,
86 size_t data_length) 87 size_t data_length)
87{ 88{
88 struct GNUNET_MessageHeader hdr; 89 struct GNUNET_MessageHeader hdr;
89 90
90#if 0 91#if 0
91 fprintf (stderr, 92 fprintf(stderr,
92 "Helper sends %u-byte message of type %u\n", 93 "Helper sends %u-byte message of type %u\n",
93 (unsigned int) (sizeof (struct GNUNET_MessageHeader) + data_length), 94 (unsigned int)(sizeof(struct GNUNET_MessageHeader) + data_length),
94 (unsigned int) message_type); 95 (unsigned int)message_type);
95#endif 96#endif
96 hdr.type = htons (message_type); 97 hdr.type = htons(message_type);
97 hdr.size = htons (sizeof (struct GNUNET_MessageHeader) + data_length); 98 hdr.size = htons(sizeof(struct GNUNET_MessageHeader) + data_length);
98 if (GNUNET_OK != write_all (output, &hdr, sizeof (hdr))) 99 if (GNUNET_OK != write_all(output, &hdr, sizeof(hdr)))
99 return GNUNET_SYSERR; 100 return GNUNET_SYSERR;
100 if (GNUNET_OK != write_all (output, data, data_length)) 101 if (GNUNET_OK != write_all(output, data, data_length))
101 return GNUNET_SYSERR; 102 return GNUNET_SYSERR;
102 return GNUNET_OK; 103 return GNUNET_OK;
103} 104}
@@ -112,7 +113,7 @@ write_message (int output,
112 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 113 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
113 */ 114 */
114static int 115static int
115read_events (HANDLE console, int output_stream) 116read_events(HANDLE console, int output_stream)
116{ 117{
117 DWORD rr; 118 DWORD rr;
118 BOOL b; 119 BOOL b;
@@ -121,30 +122,30 @@ read_events (HANDLE console, int output_stream)
121 int result; 122 int result;
122 123
123 result = GNUNET_SYSERR; 124 result = GNUNET_SYSERR;
124 buf = malloc (sizeof (INPUT_RECORD) * buffer_size); 125 buf = malloc(sizeof(INPUT_RECORD) * buffer_size);
125 if (NULL == buf) 126 if (NULL == buf)
126 return result; 127 return result;
127 b = TRUE; 128 b = TRUE;
128 rr = 1; 129 rr = 1;
129 while (TRUE == b && 0 < rr) 130 while (TRUE == b && 0 < rr)
130 {
131 rr = 0;
132 b = ReadConsoleInput (console, buf, buffer_size, &rr);
133 if (FALSE == b && ERROR_SUCCESS != GetLastError ())
134 break;
135 for (i = 0; i < rr; i++)
136 { 131 {
137 int r; 132 rr = 0;
138 r = write_message (output_stream, 133 b = ReadConsoleInput(console, buf, buffer_size, &rr);
139 GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_INPUT, 134 if (FALSE == b && ERROR_SUCCESS != GetLastError())
140 (const char *) &buf[i], 135 break;
141 sizeof (INPUT_RECORD)); 136 for (i = 0; i < rr; i++)
142 if (GNUNET_OK != r) 137 {
138 int r;
139 r = write_message(output_stream,
140 GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_INPUT,
141 (const char *)&buf[i],
142 sizeof(INPUT_RECORD));
143 if (GNUNET_OK != r)
144 break;
145 }
146 if (rr + 1 != i)
143 break; 147 break;
144 } 148 }
145 if (rr + 1 != i)
146 break;
147 }
148 return result; 149 return result;
149} 150}
150 151
@@ -158,7 +159,7 @@ read_events (HANDLE console, int output_stream)
158 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 159 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
159 */ 160 */
160static int 161static int
161read_chars (HANDLE console, int output_stream) 162read_chars(HANDLE console, int output_stream)
162{ 163{
163 DWORD rr; 164 DWORD rr;
164 BOOL b; 165 BOOL b;
@@ -171,78 +172,78 @@ read_chars (HANDLE console, int output_stream)
171 int result; 172 int result;
172 173
173 result = GNUNET_SYSERR; 174 result = GNUNET_SYSERR;
174 buf = malloc (sizeof (wchar_t) * buffer_size); 175 buf = malloc(sizeof(wchar_t) * buffer_size);
175 if (NULL == buf) 176 if (NULL == buf)
176 return result; 177 return result;
177 small_ubuf = malloc (sizeof (char) * buffer_size * 2); 178 small_ubuf = malloc(sizeof(char) * buffer_size * 2);
178 if (NULL == small_ubuf) 179 if (NULL == small_ubuf)
179 { 180 {
180 free (buf); 181 free(buf);
181 return result; 182 return result;
182 } 183 }
183 b = TRUE; 184 b = TRUE;
184 rr = 1; 185 rr = 1;
185 while (TRUE == b) 186 while (TRUE == b)
186 {
187 large_ubuf = NULL;
188 rr = 0;
189 b = ReadConsoleW (console, buf, buffer_size, &rr, NULL);
190 if (FALSE == b && ERROR_SUCCESS != GetLastError ())
191 break;
192 if (0 == rr)
193 continue;
194 /* Caveat: if the UTF-16-encoded string is longer than BUFFER_SIZE,
195 * there's a possibility that we will read up to a word that constitutes
196 * a part of a multi-byte UTF-16 codepoint. Converting that to UTF-8
197 * will either drop invalid word (flags == 0) or bail out because of it
198 * (flags == WC_ERR_INVALID_CHARS).
199 */
200 conv = WideCharToMultiByte (CP_UTF8, 0, buf, rr, small_ubuf, 0, NULL, FALSE);
201 if (0 == conv || 0xFFFD == conv)
202 continue;
203 if (conv <= buffer_size * 2 - 1)
204 {
205 memset (small_ubuf, 0, buffer_size * 2);
206 conv = WideCharToMultiByte (CP_UTF8, 0, buf, rr, small_ubuf, buffer_size * 2 - 1, NULL, FALSE);
207 if (0 == conv || 0xFFFD == conv)
208 continue;
209 ubuf = small_ubuf;
210 }
211 else
212 { 187 {
213 large_ubuf = malloc (conv + 1); 188 large_ubuf = NULL;
214 if (NULL == large_ubuf) 189 rr = 0;
190 b = ReadConsoleW(console, buf, buffer_size, &rr, NULL);
191 if (FALSE == b && ERROR_SUCCESS != GetLastError())
192 break;
193 if (0 == rr)
215 continue; 194 continue;
216 memset (large_ubuf, 0, conv + 1); 195 /* Caveat: if the UTF-16-encoded string is longer than BUFFER_SIZE,
217 conv = WideCharToMultiByte (CP_UTF8, 0, buf, rr, large_ubuf, conv, NULL, FALSE); 196 * there's a possibility that we will read up to a word that constitutes
197 * a part of a multi-byte UTF-16 codepoint. Converting that to UTF-8
198 * will either drop invalid word (flags == 0) or bail out because of it
199 * (flags == WC_ERR_INVALID_CHARS).
200 */
201 conv = WideCharToMultiByte(CP_UTF8, 0, buf, rr, small_ubuf, 0, NULL, FALSE);
218 if (0 == conv || 0xFFFD == conv) 202 if (0 == conv || 0xFFFD == conv)
219 {
220 free (large_ubuf);
221 large_ubuf = NULL;
222 continue; 203 continue;
223 } 204 if (conv <= buffer_size * 2 - 1)
224 ubuf = large_ubuf; 205 {
206 memset(small_ubuf, 0, buffer_size * 2);
207 conv = WideCharToMultiByte(CP_UTF8, 0, buf, rr, small_ubuf, buffer_size * 2 - 1, NULL, FALSE);
208 if (0 == conv || 0xFFFD == conv)
209 continue;
210 ubuf = small_ubuf;
211 }
212 else
213 {
214 large_ubuf = malloc(conv + 1);
215 if (NULL == large_ubuf)
216 continue;
217 memset(large_ubuf, 0, conv + 1);
218 conv = WideCharToMultiByte(CP_UTF8, 0, buf, rr, large_ubuf, conv, NULL, FALSE);
219 if (0 == conv || 0xFFFD == conv)
220 {
221 free(large_ubuf);
222 large_ubuf = NULL;
223 continue;
224 }
225 ubuf = large_ubuf;
226 }
227 r = write_message(output_stream,
228 GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS,
229 ubuf,
230 conv + 1);
231 if (large_ubuf)
232 free(large_ubuf);
233 if (GNUNET_OK != r)
234 break;
225 } 235 }
226 r = write_message (output_stream, 236 free(small_ubuf);
227 GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS, 237 free(buf);
228 ubuf,
229 conv + 1);
230 if (large_ubuf)
231 free (large_ubuf);
232 if (GNUNET_OK != r)
233 break;
234 }
235 free (small_ubuf);
236 free (buf);
237 return result; 238 return result;
238} 239}
239 240
240 241
241DWORD WINAPI 242DWORD WINAPI
242watch_parent (LPVOID param) 243watch_parent(LPVOID param)
243{ 244{
244 WaitForSingleObject (parent_handle, INFINITE); 245 WaitForSingleObject(parent_handle, INFINITE);
245 ExitProcess (1); 246 ExitProcess(1);
246 return 0; 247 return 0;
247} 248}
248 249
@@ -257,62 +258,62 @@ watch_parent (LPVOID param)
257 * @return 0 on success 258 * @return 0 on success
258 */ 259 */
259int 260int
260main (int argc, 261main(int argc,
261 char *const *argv) 262 char *const *argv)
262{ 263{
263 HANDLE os_stdin; 264 HANDLE os_stdin;
264 DWORD parent_pid; 265 DWORD parent_pid;
266
265 /* We're using stdout to communicate binary data back to the parent; use 267 /* We're using stdout to communicate binary data back to the parent; use
266 * binary mode. 268 * binary mode.
267 */ 269 */
268 _setmode (1, _O_BINARY); 270 _setmode(1, _O_BINARY);
269 271
270 if (argc != 4) 272 if (argc != 4)
271 { 273 {
272 fprintf (stderr, 274 fprintf(stderr,
273 "Usage: gnunet-helper-w32-console <chars|events> <buffer size> <parent pid>\n"); 275 "Usage: gnunet-helper-w32-console <chars|events> <buffer size> <parent pid>\n");
274 return 2; 276 return 2;
275 } 277 }
276 278
277 if (0 == strcmp (argv[1], "chars")) 279 if (0 == strcmp(argv[1], "chars"))
278 chars = GNUNET_YES; 280 chars = GNUNET_YES;
279 else if (0 == strcmp (argv[1], "events")) 281 else if (0 == strcmp(argv[1], "events"))
280 chars = GNUNET_NO; 282 chars = GNUNET_NO;
281 else 283 else
282 return 3; 284 return 3;
283 285
284 buffer_size = strtoul (argv[2], NULL, 10); 286 buffer_size = strtoul(argv[2], NULL, 10);
285 if (buffer_size <= 0) 287 if (buffer_size <= 0)
286 return 4; 288 return 4;
287 289
288 parent_pid = (DWORD) strtoul (argv[3], NULL, 10); 290 parent_pid = (DWORD)strtoul(argv[3], NULL, 10);
289 if (parent_pid == 0) 291 if (parent_pid == 0)
290 return 5; 292 return 5;
291 parent_handle = OpenProcess (SYNCHRONIZE, FALSE, parent_pid); 293 parent_handle = OpenProcess(SYNCHRONIZE, FALSE, parent_pid);
292 if (NULL == parent_handle) 294 if (NULL == parent_handle)
293 return 6; 295 return 6;
294 296
295 CreateThread (NULL, 0, watch_parent, NULL, 0, NULL); 297 CreateThread(NULL, 0, watch_parent, NULL, 0, NULL);
296 298
297 if (0 == AttachConsole (ATTACH_PARENT_PROCESS)) 299 if (0 == AttachConsole(ATTACH_PARENT_PROCESS))
298 { 300 {
299 if (ERROR_ACCESS_DENIED != GetLastError ()) 301 if (ERROR_ACCESS_DENIED != GetLastError())
300 return 5; 302 return 5;
301 } 303 }
302 304
303 /* Helper API overrides stdin, so we just attach to the console that we 305 /* Helper API overrides stdin, so we just attach to the console that we
304 * inherited. If we did. 306 * inherited. If we did.
305 */ 307 */
306 os_stdin = CreateFile ("CONIN$", GENERIC_READ | GENERIC_WRITE, 308 os_stdin = CreateFile("CONIN$", GENERIC_READ | GENERIC_WRITE,
307 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0); 309 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, 0);
308 if (INVALID_HANDLE_VALUE == os_stdin) 310 if (INVALID_HANDLE_VALUE == os_stdin)
309 return 1; 311 return 1;
310 312
311 if (GNUNET_NO == chars) 313 if (GNUNET_NO == chars)
312 return read_events (os_stdin, 1); 314 return read_events(os_stdin, 1);
313 else 315 else
314 return read_chars (os_stdin, 1); 316 return read_chars(os_stdin, 1);
315
316} 317}
317 318
318/* end of gnunet-helper-w32-console.c */ 319/* end of gnunet-helper-w32-console.c */
diff --git a/src/util/gnunet-helper-w32-console.h b/src/util/gnunet-helper-w32-console.h
index eaa9019a5..6af357cb7 100644
--- a/src/util/gnunet-helper-w32-console.h
+++ b/src/util/gnunet-helper-w32-console.h
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author LRN 22 * @author LRN
@@ -44,8 +44,7 @@ GNUNET_NETWORK_STRUCT_BEGIN
44/** 44/**
45 * This is just a dump of the INPUT_RECORD structure. 45 * This is just a dump of the INPUT_RECORD structure.
46 */ 46 */
47struct GNUNET_W32_CONSOLE_input 47struct GNUNET_W32_CONSOLE_input {
48{
49 /** 48 /**
50 * Type: GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_INPUT 49 * Type: GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_INPUT
51 */ 50 */
@@ -57,8 +56,7 @@ struct GNUNET_W32_CONSOLE_input
57/** 56/**
58 * A header, followed by UTF8-encoded, 0-terminated string 57 * A header, followed by UTF8-encoded, 0-terminated string
59 */ 58 */
60struct GNUNET_W32_CONSOLE_chars 59struct GNUNET_W32_CONSOLE_chars {
61{
62 /** 60 /**
63 * Type: GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS 61 * Type: GNUNET_MESSAGE_TYPE_W32_CONSOLE_HELPER_CHARS
64 */ 62 */
diff --git a/src/util/gnunet-qr.c b/src/util/gnunet-qr.c
index ff781f726..91c36dbdf 100644
--- a/src/util/gnunet-qr.c
+++ b/src/util/gnunet-qr.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/gnunet-qr.c 21 * @file util/gnunet-qr.c
22 * @author Hartmut Goebel (original implementation) 22 * @author Hartmut Goebel (original implementation)
@@ -31,7 +31,7 @@
31 31
32#define LOG(fmt, ...) \ 32#define LOG(fmt, ...) \
33 if (verbose == true) \ 33 if (verbose == true) \
34 printf (fmt, ##__VA_ARGS__) 34 printf (fmt, ## __VA_ARGS__)
35 35
36/** 36/**
37 * Video device to capture from. Sane default for GNU/Linux systems. 37 * Video device to capture from. Sane default for GNU/Linux systems.
@@ -72,14 +72,14 @@ static struct GNUNET_DISK_PipeHandle *sigpipe;
72 * @param cls closure, NULL 72 * @param cls closure, NULL
73 */ 73 */
74static void 74static void
75maint_child_death (void *cls) 75maint_child_death(void *cls)
76{ 76{
77 enum GNUNET_OS_ProcessStatusType type; 77 enum GNUNET_OS_ProcessStatusType type;
78 78
79 if ((GNUNET_OK != GNUNET_OS_process_status (p, &type, &exit_code)) || 79 if ((GNUNET_OK != GNUNET_OS_process_status(p, &type, &exit_code)) ||
80 (type != GNUNET_OS_PROCESS_EXITED)) 80 (type != GNUNET_OS_PROCESS_EXITED))
81 GNUNET_break (0 == GNUNET_OS_process_kill (p, GNUNET_TERM_SIG)); 81 GNUNET_break(0 == GNUNET_OS_process_kill(p, GNUNET_TERM_SIG));
82 GNUNET_OS_process_destroy (p); 82 GNUNET_OS_process_destroy(p);
83} 83}
84 84
85 85
@@ -92,10 +92,10 @@ maint_child_death (void *cls)
92 * @param cfg configuration 92 * @param cfg configuration
93 */ 93 */
94static void 94static void
95gnunet_uri (void *cls, 95gnunet_uri(void *cls,
96 const char *uri, 96 const char *uri,
97 const char *cfgfile, 97 const char *cfgfile,
98 const struct GNUNET_CONFIGURATION_Handle *cfg) 98 const struct GNUNET_CONFIGURATION_Handle *cfg)
99{ 99{
100 const char *orig_uri; 100 const char *orig_uri;
101 const char *slash; 101 const char *slash;
@@ -104,45 +104,45 @@ gnunet_uri (void *cls,
104 struct GNUNET_SCHEDULER_Task *rt; 104 struct GNUNET_SCHEDULER_Task *rt;
105 105
106 orig_uri = uri; 106 orig_uri = uri;
107 if (0 != strncasecmp ("gnunet://", uri, strlen ("gnunet://"))) 107 if (0 != strncasecmp("gnunet://", uri, strlen("gnunet://")))
108 { 108 {
109 fprintf (stderr, 109 fprintf(stderr,
110 _ ("Invalid URI: does not start with `%s'\n"), 110 _("Invalid URI: does not start with `%s'\n"),
111 "gnunet://"); 111 "gnunet://");
112 return; 112 return;
113 } 113 }
114 uri += strlen ("gnunet://"); 114 uri += strlen("gnunet://");
115 if (NULL == (slash = strchr (uri, '/'))) 115 if (NULL == (slash = strchr(uri, '/')))
116 { 116 {
117 fprintf (stderr, _ ("Invalid URI: fails to specify subsystem\n")); 117 fprintf(stderr, _("Invalid URI: fails to specify subsystem\n"));
118 return; 118 return;
119 } 119 }
120 subsystem = GNUNET_strndup (uri, slash - uri); 120 subsystem = GNUNET_strndup(uri, slash - uri);
121 if (GNUNET_OK != 121 if (GNUNET_OK !=
122 GNUNET_CONFIGURATION_get_value_string (cfg, "uri", subsystem, &program)) 122 GNUNET_CONFIGURATION_get_value_string(cfg, "uri", subsystem, &program))
123 { 123 {
124 fprintf (stderr, _ ("No handler known for subsystem `%s'\n"), subsystem); 124 fprintf(stderr, _("No handler known for subsystem `%s'\n"), subsystem);
125 GNUNET_free (subsystem); 125 GNUNET_free(subsystem);
126 return; 126 return;
127 } 127 }
128 GNUNET_free (subsystem); 128 GNUNET_free(subsystem);
129 rt = GNUNET_SCHEDULER_add_read_file ( 129 rt = GNUNET_SCHEDULER_add_read_file(
130 GNUNET_TIME_UNIT_FOREVER_REL, 130 GNUNET_TIME_UNIT_FOREVER_REL,
131 GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ), 131 GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ),
132 &maint_child_death, 132 &maint_child_death,
133 NULL); 133 NULL);
134 p = GNUNET_OS_start_process (GNUNET_NO, 134 p = GNUNET_OS_start_process(GNUNET_NO,
135 0, 135 0,
136 NULL, 136 NULL,
137 NULL, 137 NULL,
138 NULL, 138 NULL,
139 program, 139 program,
140 program, 140 program,
141 orig_uri, 141 orig_uri,
142 NULL); 142 NULL);
143 GNUNET_free (program); 143 GNUNET_free(program);
144 if (NULL == p) 144 if (NULL == p)
145 GNUNET_SCHEDULER_cancel (rt); 145 GNUNET_SCHEDULER_cancel(rt);
146} 146}
147 147
148 148
@@ -153,54 +153,54 @@ gnunet_uri (void *cls,
153 * @return NULL on error 153 * @return NULL on error
154 */ 154 */
155static const zbar_symbol_t * 155static const zbar_symbol_t *
156get_symbol (zbar_processor_t *proc) 156get_symbol(zbar_processor_t *proc)
157{ 157{
158 const zbar_symbol_set_t *symbols; 158 const zbar_symbol_set_t *symbols;
159 int rc; 159 int rc;
160 int n; 160 int n;
161 161
162 if (0 != zbar_processor_parse_config (proc, "enable")) 162 if (0 != zbar_processor_parse_config(proc, "enable"))
163 { 163 {
164 GNUNET_break (0); 164 GNUNET_break(0);
165 return NULL; 165 return NULL;
166 } 166 }
167 167
168 /* initialize the Processor */ 168 /* initialize the Processor */
169 if (0 != (rc = zbar_processor_init (proc, device, 1))) 169 if (0 != (rc = zbar_processor_init(proc, device, 1)))
170 { 170 {
171 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 171 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
172 "Failed to open device `%s': %d\n", 172 "Failed to open device `%s': %d\n",
173 device, 173 device,
174 rc); 174 rc);
175 return NULL; 175 return NULL;
176 } 176 }
177 177
178 /* enable the preview window */ 178 /* enable the preview window */
179 if ((0 != (rc = zbar_processor_set_visible (proc, 1))) || 179 if ((0 != (rc = zbar_processor_set_visible(proc, 1))) ||
180 (0 != (rc = zbar_processor_set_active (proc, 1)))) 180 (0 != (rc = zbar_processor_set_active(proc, 1))))
181 { 181 {
182 GNUNET_break (0); 182 GNUNET_break(0);
183 return NULL; 183 return NULL;
184 } 184 }
185 185
186 /* read at least one barcode (or until window closed) */ 186 /* read at least one barcode (or until window closed) */
187 LOG ("Capturing\n"); 187 LOG("Capturing\n");
188 n = zbar_process_one (proc, -1); 188 n = zbar_process_one(proc, -1);
189 189
190 /* hide the preview window */ 190 /* hide the preview window */
191 (void) zbar_processor_set_active (proc, 0); 191 (void)zbar_processor_set_active(proc, 0);
192 (void) zbar_processor_set_visible (proc, 0); 192 (void)zbar_processor_set_visible(proc, 0);
193 if (-1 == n) 193 if (-1 == n)
194 return NULL; /* likely user closed the window */ 194 return NULL; /* likely user closed the window */
195 LOG ("Got %i images\n", n); 195 LOG("Got %i images\n", n);
196 /* extract results */ 196 /* extract results */
197 symbols = zbar_processor_get_results (proc); 197 symbols = zbar_processor_get_results(proc);
198 if (NULL == symbols) 198 if (NULL == symbols)
199 { 199 {
200 GNUNET_break (0); 200 GNUNET_break(0);
201 return NULL; 201 return NULL;
202 } 202 }
203 return zbar_symbol_set_first_symbol (symbols); 203 return zbar_symbol_set_first_symbol(symbols);
204} 204}
205 205
206 206
@@ -210,7 +210,7 @@ get_symbol (zbar_processor_t *proc)
210 * @return NULL on error, otherwise the URI that we found 210 * @return NULL on error, otherwise the URI that we found
211 */ 211 */
212static char * 212static char *
213run_zbar () 213run_zbar()
214{ 214{
215 zbar_processor_t *proc; 215 zbar_processor_t *proc;
216 const char *data; 216 const char *data;
@@ -218,32 +218,32 @@ run_zbar ()
218 const zbar_symbol_t *symbol; 218 const zbar_symbol_t *symbol;
219 219
220 /* configure the Processor */ 220 /* configure the Processor */
221 proc = zbar_processor_create (1); 221 proc = zbar_processor_create(1);
222 if (NULL == proc) 222 if (NULL == proc)
223 { 223 {
224 GNUNET_break (0); 224 GNUNET_break(0);
225 return NULL; 225 return NULL;
226 } 226 }
227 227
228 symbol = get_symbol (proc); 228 symbol = get_symbol(proc);
229 if (NULL == symbol) 229 if (NULL == symbol)
230 { 230 {
231 zbar_processor_destroy (proc); 231 zbar_processor_destroy(proc);
232 return NULL; 232 return NULL;
233 } 233 }
234 data = zbar_symbol_get_data (symbol); 234 data = zbar_symbol_get_data(symbol);
235 if (NULL == data) 235 if (NULL == data)
236 { 236 {
237 GNUNET_break (0); 237 GNUNET_break(0);
238 zbar_processor_destroy (proc); 238 zbar_processor_destroy(proc);
239 return NULL; 239 return NULL;
240 } 240 }
241 LOG ("Found %s \"%s\"\n", 241 LOG("Found %s \"%s\"\n",
242 zbar_get_symbol_name (zbar_symbol_get_type (symbol)), 242 zbar_get_symbol_name(zbar_symbol_get_type(symbol)),
243 data); 243 data);
244 ret = GNUNET_strdup (data); 244 ret = GNUNET_strdup(data);
245 /* clean up */ 245 /* clean up */
246 zbar_processor_destroy (proc); 246 zbar_processor_destroy(proc);
247 return ret; 247 return ret;
248} 248}
249 249
@@ -257,55 +257,55 @@ run_zbar ()
257 * @param cfg configuration 257 * @param cfg configuration
258 */ 258 */
259static void 259static void
260run (void *cls, 260run(void *cls,
261 char *const *args, 261 char *const *args,
262 const char *cfgfile, 262 const char *cfgfile,
263 const struct GNUNET_CONFIGURATION_Handle *cfg) 263 const struct GNUNET_CONFIGURATION_Handle *cfg)
264{ 264{
265 char *data; 265 char *data;
266 266
267 data = run_zbar (); 267 data = run_zbar();
268 if (NULL == data) 268 if (NULL == data)
269 return; 269 return;
270 gnunet_uri (cls, data, cfgfile, cfg); 270 gnunet_uri(cls, data, cfgfile, cfg);
271 if (exit_code != 0) 271 if (exit_code != 0)
272 { 272 {
273 printf ("Failed to add URI %s\n", data); 273 printf("Failed to add URI %s\n", data);
274 } 274 }
275 else 275 else
276 { 276 {
277 printf ("Added URI %s\n", data); 277 printf("Added URI %s\n", data);
278 } 278 }
279 GNUNET_free (data); 279 GNUNET_free(data);
280}; 280};
281 281
282 282
283int 283int
284main (int argc, char *const *argv) 284main(int argc, char *const *argv)
285{ 285{
286 int ret; 286 int ret;
287 struct GNUNET_GETOPT_CommandLineOption options[] = 287 struct GNUNET_GETOPT_CommandLineOption options[] =
288 {GNUNET_GETOPT_option_string ( 288 { GNUNET_GETOPT_option_string(
289 'd', 289 'd',
290 "device", 290 "device",
291 "DEVICE", 291 "DEVICE",
292 gettext_noop ("use video-device DEVICE (default: /dev/video0"), 292 gettext_noop("use video-device DEVICE (default: /dev/video0"),
293 &device), 293 &device),
294 GNUNET_GETOPT_option_flag ('\0', 294 GNUNET_GETOPT_option_flag('\0',
295 "verbose", 295 "verbose",
296 gettext_noop ("be verbose"), 296 gettext_noop("be verbose"),
297 &verbose), 297 &verbose),
298 GNUNET_GETOPT_option_flag ('s', 298 GNUNET_GETOPT_option_flag('s',
299 "silent", 299 "silent",
300 gettext_noop ("do not show preview windows"), 300 gettext_noop("do not show preview windows"),
301 &silent), 301 &silent),
302 GNUNET_GETOPT_OPTION_END}; 302 GNUNET_GETOPT_OPTION_END };
303 303
304 ret = GNUNET_PROGRAM_run ( 304 ret = GNUNET_PROGRAM_run(
305 argc, 305 argc,
306 argv, 306 argv,
307 "gnunet-qr", 307 "gnunet-qr",
308 gettext_noop ( 308 gettext_noop(
309 "Scan a QR code using a video device and import the uri read"), 309 "Scan a QR code using a video device and import the uri read"),
310 options, 310 options,
311 &run, 311 &run,
diff --git a/src/util/gnunet-resolver.c b/src/util/gnunet-resolver.c
index 3aba5fb1e..dd1e8f5e0 100644
--- a/src/util/gnunet-resolver.c
+++ b/src/util/gnunet-resolver.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/gnunet-resolver.c 22 * @file util/gnunet-resolver.c
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28#include "gnunet_resolver_service.h" 28#include "gnunet_resolver_service.h"
29 29
30#define GET_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5) 30#define GET_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5)
31 31
32/** 32/**
33 * Flag for reverse lookup. 33 * Flag for reverse lookup.
@@ -43,15 +43,15 @@ static int reverse;
43 * on the last call to the callback 43 * on the last call to the callback
44 */ 44 */
45static void 45static void
46print_hostname (void *cls, 46print_hostname(void *cls,
47 const char *hostname) 47 const char *hostname)
48{ 48{
49 (void) cls; 49 (void)cls;
50 if (NULL == hostname) 50 if (NULL == hostname)
51 return; 51 return;
52 fprintf (stdout, 52 fprintf(stdout,
53 "%s\n", 53 "%s\n",
54 hostname); 54 hostname);
55} 55}
56 56
57 57
@@ -63,17 +63,17 @@ print_hostname (void *cls,
63 * @param addrlen length of the address 63 * @param addrlen length of the address
64 */ 64 */
65static void 65static void
66print_sockaddr (void *cls, 66print_sockaddr(void *cls,
67 const struct sockaddr *addr, 67 const struct sockaddr *addr,
68 socklen_t addrlen) 68 socklen_t addrlen)
69{ 69{
70 (void) cls; 70 (void)cls;
71 if (NULL == addr) 71 if (NULL == addr)
72 return; 72 return;
73 fprintf (stdout, 73 fprintf(stdout,
74 "%s\n", 74 "%s\n",
75 GNUNET_a2s (addr, 75 GNUNET_a2s(addr,
76 addrlen)); 76 addrlen));
77} 77}
78 78
79 79
@@ -86,69 +86,69 @@ print_sockaddr (void *cls,
86 * @param cfg configuration 86 * @param cfg configuration
87 */ 87 */
88static void 88static void
89run (void *cls, 89run(void *cls,
90 char *const *args, 90 char *const *args,
91 const char *cfgfile, 91 const char *cfgfile,
92 const struct GNUNET_CONFIGURATION_Handle *cfg) 92 const struct GNUNET_CONFIGURATION_Handle *cfg)
93{ 93{
94 const struct sockaddr *sa; 94 const struct sockaddr *sa;
95 socklen_t salen; 95 socklen_t salen;
96 struct sockaddr_in v4; 96 struct sockaddr_in v4;
97 struct sockaddr_in6 v6; 97 struct sockaddr_in6 v6;
98 98
99 (void) cls; 99 (void)cls;
100 (void) cfgfile; 100 (void)cfgfile;
101 (void) cfg; 101 (void)cfg;
102 if (NULL == args[0]) 102 if (NULL == args[0])
103 return; 103 return;
104 if (! reverse) 104 if (!reverse)
105 { 105 {
106 GNUNET_RESOLVER_ip_get (args[0], 106 GNUNET_RESOLVER_ip_get(args[0],
107 AF_UNSPEC, 107 AF_UNSPEC,
108 GET_TIMEOUT, 108 GET_TIMEOUT,
109 &print_sockaddr, 109 &print_sockaddr,
110 NULL); 110 NULL);
111 return; 111 return;
112 } 112 }
113 113
114 sa = NULL; 114 sa = NULL;
115 memset (&v4, 0, sizeof (v4)); 115 memset(&v4, 0, sizeof(v4));
116 v4.sin_family = AF_INET; 116 v4.sin_family = AF_INET;
117#if HAVE_SOCKADDR_IN_SIN_LEN 117#if HAVE_SOCKADDR_IN_SIN_LEN
118 v4.sin_len = sizeof (v4); 118 v4.sin_len = sizeof(v4);
119#endif 119#endif
120 if (1 == inet_pton (AF_INET, 120 if (1 == inet_pton(AF_INET,
121 args[0], 121 args[0],
122 &v4.sin_addr)) 122 &v4.sin_addr))
123 { 123 {
124 sa = (struct sockaddr *) &v4; 124 sa = (struct sockaddr *)&v4;
125 salen = sizeof (v4); 125 salen = sizeof(v4);
126 } 126 }
127 memset (&v6, 0, sizeof (v6)); 127 memset(&v6, 0, sizeof(v6));
128 v6.sin6_family = AF_INET6; 128 v6.sin6_family = AF_INET6;
129#if HAVE_SOCKADDR_IN_SIN_LEN 129#if HAVE_SOCKADDR_IN_SIN_LEN
130 v6.sin6_len = sizeof (v6); 130 v6.sin6_len = sizeof(v6);
131#endif 131#endif
132 if (1 == inet_pton (AF_INET6, 132 if (1 == inet_pton(AF_INET6,
133 args[0], 133 args[0],
134 &v6.sin6_addr)) 134 &v6.sin6_addr))
135 { 135 {
136 sa = (struct sockaddr *) &v6; 136 sa = (struct sockaddr *)&v6;
137 salen = sizeof (v6); 137 salen = sizeof(v6);
138 } 138 }
139 if (NULL == sa) 139 if (NULL == sa)
140 { 140 {
141 fprintf (stderr, 141 fprintf(stderr,
142 "`%s' is not a valid IP: %s\n", 142 "`%s' is not a valid IP: %s\n",
143 args[0], 143 args[0],
144 strerror (errno)); 144 strerror(errno));
145 return; 145 return;
146 } 146 }
147 GNUNET_RESOLVER_hostname_get (sa, salen, 147 GNUNET_RESOLVER_hostname_get(sa, salen,
148 GNUNET_YES, 148 GNUNET_YES,
149 GET_TIMEOUT, 149 GET_TIMEOUT,
150 &print_hostname, 150 &print_hostname,
151 NULL); 151 NULL);
152} 152}
153 153
154 154
@@ -160,25 +160,25 @@ run (void *cls,
160 * @return 0 ok, 1 on error 160 * @return 0 ok, 1 on error
161 */ 161 */
162int 162int
163main (int argc, char *const *argv) 163main(int argc, char *const *argv)
164{ 164{
165 struct GNUNET_GETOPT_CommandLineOption options[] = { 165 struct GNUNET_GETOPT_CommandLineOption options[] = {
166 GNUNET_GETOPT_option_flag ('r', 166 GNUNET_GETOPT_option_flag('r',
167 "reverse", 167 "reverse",
168 gettext_noop ("perform a reverse lookup"), 168 gettext_noop("perform a reverse lookup"),
169 &reverse), 169 &reverse),
170 GNUNET_GETOPT_OPTION_END 170 GNUNET_GETOPT_OPTION_END
171 }; 171 };
172 int ret; 172 int ret;
173 173
174 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) 174 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
175 return 2; 175 return 2;
176 176
177 ret = (GNUNET_OK == 177 ret = (GNUNET_OK ==
178 GNUNET_PROGRAM_run (argc, argv, "gnunet-resolver [hostname]", 178 GNUNET_PROGRAM_run(argc, argv, "gnunet-resolver [hostname]",
179 gettext_noop ("Use build-in GNUnet stub resolver"), 179 gettext_noop("Use build-in GNUnet stub resolver"),
180 options, &run, NULL)) ? 0 : 1; 180 options, &run, NULL)) ? 0 : 1;
181 GNUNET_free ((void*) argv); 181 GNUNET_free((void*)argv);
182 return ret; 182 return ret;
183} 183}
184 184
diff --git a/src/util/gnunet-scrypt.c b/src/util/gnunet-scrypt.c
index 6f9690c99..182ab346e 100644
--- a/src/util/gnunet-scrypt.c
+++ b/src/util/gnunet-scrypt.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/gnunet-scrypt.c 21 * @file util/gnunet-scrypt.c
22 * @brief tool to manipulate SCRYPT proofs of work. 22 * @brief tool to manipulate SCRYPT proofs of work.
@@ -55,15 +55,15 @@ static char *pwfn;
55 * @param cls closure 55 * @param cls closure
56 */ 56 */
57static void 57static void
58shutdown_task (void *cls) 58shutdown_task(void *cls)
59{ 59{
60 (void) cls; 60 (void)cls;
61 if (sizeof (proof) != GNUNET_DISK_fn_write (pwfn, 61 if (sizeof(proof) != GNUNET_DISK_fn_write(pwfn,
62 &proof, 62 &proof,
63 sizeof (proof), 63 sizeof(proof),
64 GNUNET_DISK_PERM_USER_READ | 64 GNUNET_DISK_PERM_USER_READ |
65 GNUNET_DISK_PERM_USER_WRITE)) 65 GNUNET_DISK_PERM_USER_WRITE))
66 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "write", pwfn); 66 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "write", pwfn);
67} 67}
68 68
69 69
@@ -75,18 +75,18 @@ shutdown_task (void *cls)
75 * @param result where to write the resulting hash 75 * @param result where to write the resulting hash
76 */ 76 */
77static void 77static void
78pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result) 78pow_hash(const void *buf, size_t buf_len, struct GNUNET_HashCode *result)
79{ 79{
80 GNUNET_break ( 80 GNUNET_break(
81 0 == gcry_kdf_derive (buf, 81 0 == gcry_kdf_derive(buf,
82 buf_len, 82 buf_len,
83 GCRY_KDF_SCRYPT, 83 GCRY_KDF_SCRYPT,
84 1 /* subalgo */, 84 1 /* subalgo */,
85 "gnunet-proof-of-work", 85 "gnunet-proof-of-work",
86 strlen ("gnunet-proof-of-work"), 86 strlen("gnunet-proof-of-work"),
87 2 /* iterations; keep cost of individual op small */, 87 2 /* iterations; keep cost of individual op small */,
88 sizeof (struct GNUNET_HashCode), 88 sizeof(struct GNUNET_HashCode),
89 result)); 89 result));
90} 90}
91 91
92 92
@@ -97,12 +97,12 @@ pow_hash (const void *buf, size_t buf_len, struct GNUNET_HashCode *result)
97 * @return the number of leading zero bits. 97 * @return the number of leading zero bits.
98 */ 98 */
99static unsigned int 99static unsigned int
100count_leading_zeroes (const struct GNUNET_HashCode *hash) 100count_leading_zeroes(const struct GNUNET_HashCode *hash)
101{ 101{
102 unsigned int hash_count; 102 unsigned int hash_count;
103 103
104 hash_count = 0; 104 hash_count = 0;
105 while (0 == GNUNET_CRYPTO_hash_get_bit (hash, hash_count)) 105 while (0 == GNUNET_CRYPTO_hash_get_bit(hash, hash_count))
106 hash_count++; 106 hash_count++;
107 return hash_count; 107 return hash_count;
108} 108}
@@ -115,68 +115,68 @@ count_leading_zeroes (const struct GNUNET_HashCode *hash)
115 * @param tc task context 115 * @param tc task context
116 */ 116 */
117static void 117static void
118find_proof (void *cls) 118find_proof(void *cls)
119{ 119{
120#define ROUND_SIZE 10 120#define ROUND_SIZE 10
121 uint64_t counter; 121 uint64_t counter;
122 char buf[sizeof (struct GNUNET_CRYPTO_EddsaPublicKey) + 122 char buf[sizeof(struct GNUNET_CRYPTO_EddsaPublicKey) +
123 sizeof (uint64_t)] GNUNET_ALIGN; 123 sizeof(uint64_t)] GNUNET_ALIGN;
124 struct GNUNET_HashCode result; 124 struct GNUNET_HashCode result;
125 unsigned int i; 125 unsigned int i;
126 struct GNUNET_TIME_Absolute timestamp; 126 struct GNUNET_TIME_Absolute timestamp;
127 struct GNUNET_TIME_Relative elapsed; 127 struct GNUNET_TIME_Relative elapsed;
128 128
129 (void) cls; 129 (void)cls;
130 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 130 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
131 "Got Proof of Work %llu\n", 131 "Got Proof of Work %llu\n",
132 (unsigned long long) proof); 132 (unsigned long long)proof);
133 proof_task = NULL; 133 proof_task = NULL;
134 GNUNET_memcpy (&buf[sizeof (uint64_t)], 134 GNUNET_memcpy(&buf[sizeof(uint64_t)],
135 &pub, 135 &pub,
136 sizeof (struct GNUNET_CRYPTO_EddsaPublicKey)); 136 sizeof(struct GNUNET_CRYPTO_EddsaPublicKey));
137 i = 0; 137 i = 0;
138 counter = proof; 138 counter = proof;
139 timestamp = GNUNET_TIME_absolute_get (); 139 timestamp = GNUNET_TIME_absolute_get();
140 while ((counter != UINT64_MAX) && (i < ROUND_SIZE)) 140 while ((counter != UINT64_MAX) && (i < ROUND_SIZE))
141 {
142 GNUNET_memcpy (buf, &counter, sizeof (uint64_t));
143 pow_hash (buf, sizeof (buf), &result);
144 if (nse_work_required <= count_leading_zeroes (&result))
145 { 141 {
146 proof = counter; 142 GNUNET_memcpy(buf, &counter, sizeof(uint64_t));
147 fprintf (stdout, 143 pow_hash(buf, sizeof(buf), &result);
148 "Proof of work found: %llu!\n", 144 if (nse_work_required <= count_leading_zeroes(&result))
149 (unsigned long long) proof); 145 {
150 GNUNET_SCHEDULER_shutdown (); 146 proof = counter;
151 return; 147 fprintf(stdout,
148 "Proof of work found: %llu!\n",
149 (unsigned long long)proof);
150 GNUNET_SCHEDULER_shutdown();
151 return;
152 }
153 counter++;
154 i++;
152 } 155 }
153 counter++; 156 elapsed = GNUNET_TIME_absolute_get_duration(timestamp);
154 i++; 157 elapsed = GNUNET_TIME_relative_divide(elapsed, ROUND_SIZE);
155 } 158 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
156 elapsed = GNUNET_TIME_absolute_get_duration (timestamp); 159 "Current: %llu [%s/proof]\n",
157 elapsed = GNUNET_TIME_relative_divide (elapsed, ROUND_SIZE); 160 (unsigned long long)counter,
158 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 161 GNUNET_STRINGS_relative_time_to_string(elapsed, 0));
159 "Current: %llu [%s/proof]\n",
160 (unsigned long long) counter,
161 GNUNET_STRINGS_relative_time_to_string (elapsed, 0));
162 if (proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE)) 162 if (proof / (100 * ROUND_SIZE) < counter / (100 * ROUND_SIZE))
163 { 163 {
164 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 164 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
165 "Testing proofs currently at %llu\n", 165 "Testing proofs currently at %llu\n",
166 (unsigned long long) counter); 166 (unsigned long long)counter);
167 /* remember progress every 100 rounds */ 167 /* remember progress every 100 rounds */
168 proof = counter; 168 proof = counter;
169 shutdown_task (NULL); 169 shutdown_task(NULL);
170 } 170 }
171 else 171 else
172 { 172 {
173 proof = counter; 173 proof = counter;
174 } 174 }
175 proof_task = 175 proof_task =
176 GNUNET_SCHEDULER_add_delayed_with_priority (proof_find_delay, 176 GNUNET_SCHEDULER_add_delayed_with_priority(proof_find_delay,
177 GNUNET_SCHEDULER_PRIORITY_IDLE, 177 GNUNET_SCHEDULER_PRIORITY_IDLE,
178 &find_proof, 178 &find_proof,
179 NULL); 179 NULL);
180} 180}
181 181
182 182
@@ -189,101 +189,101 @@ find_proof (void *cls)
189 * @param cfg configuration 189 * @param cfg configuration
190 */ 190 */
191static void 191static void
192run (void *cls, 192run(void *cls,
193 char *const *args, 193 char *const *args,
194 const char *cfgfile, 194 const char *cfgfile,
195 const struct GNUNET_CONFIGURATION_Handle *config) 195 const struct GNUNET_CONFIGURATION_Handle *config)
196{ 196{
197 struct GNUNET_CRYPTO_EddsaPrivateKey *pk; 197 struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
198 char *pids; 198 char *pids;
199 199
200 (void) cls; 200 (void)cls;
201 (void) args; 201 (void)args;
202 (void) cfgfile; 202 (void)cfgfile;
203 cfg = config; 203 cfg = config;
204 /* load proof of work */ 204 /* load proof of work */
205 if (NULL == pwfn) 205 if (NULL == pwfn)
206 {
207 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg,
208 "NSE",
209 "PROOFFILE",
210 &pwfn))
211 { 206 {
212 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "PROOFFILE"); 207 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg,
213 GNUNET_SCHEDULER_shutdown (); 208 "NSE",
214 return; 209 "PROOFFILE",
210 &pwfn))
211 {
212 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "PROOFFILE");
213 GNUNET_SCHEDULER_shutdown();
214 return;
215 }
215 } 216 }
216 } 217 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Proof of Work file: %s\n", pwfn);
217 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Proof of Work file: %s\n", pwfn); 218 if ((GNUNET_YES != GNUNET_DISK_file_test(pwfn)) ||
218 if ((GNUNET_YES != GNUNET_DISK_file_test (pwfn)) || 219 (sizeof(proof) != GNUNET_DISK_fn_read(pwfn, &proof, sizeof(proof))))
219 (sizeof (proof) != GNUNET_DISK_fn_read (pwfn, &proof, sizeof (proof))))
220 proof = 0; 220 proof = 0;
221 221
222 /* load private key */ 222 /* load private key */
223 if (NULL == pkfn) 223 if (NULL == pkfn)
224 {
225 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (cfg,
226 "PEER",
227 "PRIVATE_KEY",
228 &pkfn))
229 { 224 {
230 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, 225 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(cfg,
231 "PEER", 226 "PEER",
232 "PRIVATE_KEY"); 227 "PRIVATE_KEY",
228 &pkfn))
229 {
230 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR,
231 "PEER",
232 "PRIVATE_KEY");
233 return;
234 }
235 }
236 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Private Key file: %s\n", pkfn);
237 if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create_from_file(pkfn)))
238 {
239 fprintf(stderr, _("Loading hostkey from `%s' failed.\n"), pkfn);
240 GNUNET_free(pkfn);
233 return; 241 return;
234 } 242 }
235 } 243 GNUNET_free(pkfn);
236 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Private Key file: %s\n", pkfn); 244 GNUNET_CRYPTO_eddsa_key_get_public(pk, &pub);
237 if (NULL == (pk = GNUNET_CRYPTO_eddsa_key_create_from_file (pkfn))) 245 GNUNET_free(pk);
238 { 246 pids = GNUNET_CRYPTO_eddsa_public_key_to_string(&pub);
239 fprintf (stderr, _ ("Loading hostkey from `%s' failed.\n"), pkfn); 247 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Peer ID: %s\n", pids);
240 GNUNET_free (pkfn); 248 GNUNET_free(pids);
241 return;
242 }
243 GNUNET_free (pkfn);
244 GNUNET_CRYPTO_eddsa_key_get_public (pk, &pub);
245 GNUNET_free (pk);
246 pids = GNUNET_CRYPTO_eddsa_public_key_to_string (&pub);
247 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Peer ID: %s\n", pids);
248 GNUNET_free (pids);
249 249
250 /* get target bit amount */ 250 /* get target bit amount */
251 if (0 == nse_work_required) 251 if (0 == nse_work_required)
252 {
253 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg,
254 "NSE",
255 "WORKBITS",
256 &nse_work_required))
257 {
258 GNUNET_log_config_missing (GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKBITS");
259 GNUNET_SCHEDULER_shutdown ();
260 return;
261 }
262 if (nse_work_required >= sizeof (struct GNUNET_HashCode) * 8)
263 { 252 {
264 GNUNET_log_config_invalid (GNUNET_ERROR_TYPE_ERROR, 253 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg,
265 "NSE", 254 "NSE",
266 "WORKBITS", 255 "WORKBITS",
267 _ ("Value is too large.\n")); 256 &nse_work_required))
268 GNUNET_SCHEDULER_shutdown (); 257 {
269 return; 258 GNUNET_log_config_missing(GNUNET_ERROR_TYPE_ERROR, "NSE", "WORKBITS");
270 } 259 GNUNET_SCHEDULER_shutdown();
271 else if (0 == nse_work_required) 260 return;
272 { 261 }
273 GNUNET_SCHEDULER_shutdown (); 262 if (nse_work_required >= sizeof(struct GNUNET_HashCode) * 8)
274 return; 263 {
264 GNUNET_log_config_invalid(GNUNET_ERROR_TYPE_ERROR,
265 "NSE",
266 "WORKBITS",
267 _("Value is too large.\n"));
268 GNUNET_SCHEDULER_shutdown();
269 return;
270 }
271 else if (0 == nse_work_required)
272 {
273 GNUNET_SCHEDULER_shutdown();
274 return;
275 }
275 } 276 }
276 } 277 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Bits: %llu\n", nse_work_required);
277 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Bits: %llu\n", nse_work_required);
278 278
279 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 279 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
280 "Delay between tries: %s\n", 280 "Delay between tries: %s\n",
281 GNUNET_STRINGS_relative_time_to_string (proof_find_delay, 1)); 281 GNUNET_STRINGS_relative_time_to_string(proof_find_delay, 1));
282 proof_task = 282 proof_task =
283 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_IDLE, 283 GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_IDLE,
284 &find_proof, 284 &find_proof,
285 NULL); 285 NULL);
286 GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); 286 GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL);
287} 287}
288 288
289 289
@@ -295,52 +295,52 @@ run (void *cls,
295 * @return 0 ok, 1 on error 295 * @return 0 ok, 1 on error
296 */ 296 */
297int 297int
298main (int argc, char *const *argv) 298main(int argc, char *const *argv)
299{ 299{
300 struct GNUNET_GETOPT_CommandLineOption options[] = 300 struct GNUNET_GETOPT_CommandLineOption options[] =
301 {GNUNET_GETOPT_option_ulong ( 301 { GNUNET_GETOPT_option_ulong(
302 'b', 302 'b',
303 "bits", 303 "bits",
304 "BITS", 304 "BITS",
305 gettext_noop ("number of bits to require for the proof of work"), 305 gettext_noop("number of bits to require for the proof of work"),
306 &nse_work_required), 306 &nse_work_required),
307 GNUNET_GETOPT_option_filename ( 307 GNUNET_GETOPT_option_filename(
308 'k', 308 'k',
309 "keyfile", 309 "keyfile",
310 "FILE", 310 "FILE",
311 gettext_noop ("file with private key, otherwise default is used"), 311 gettext_noop("file with private key, otherwise default is used"),
312 &pkfn), 312 &pkfn),
313 GNUNET_GETOPT_option_filename ( 313 GNUNET_GETOPT_option_filename(
314 'o', 314 'o',
315 "outfile", 315 "outfile",
316 "FILE", 316 "FILE",
317 gettext_noop ("file with proof of work, otherwise default is used"), 317 gettext_noop("file with proof of work, otherwise default is used"),
318 &pwfn), 318 &pwfn),
319 GNUNET_GETOPT_option_relative_time ('t', 319 GNUNET_GETOPT_option_relative_time('t',
320 "timeout", 320 "timeout",
321 "TIME", 321 "TIME",
322 gettext_noop ( 322 gettext_noop(
323 "time to wait between calculations"), 323 "time to wait between calculations"),
324 &proof_find_delay), 324 &proof_find_delay),
325 GNUNET_GETOPT_OPTION_END}; 325 GNUNET_GETOPT_OPTION_END };
326 int ret; 326 int ret;
327 327
328 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) 328 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
329 return 2; 329 return 2;
330 330
331 ret = 331 ret =
332 (GNUNET_OK == 332 (GNUNET_OK ==
333 GNUNET_PROGRAM_run (argc, 333 GNUNET_PROGRAM_run(argc,
334 argv, 334 argv,
335 "gnunet-scrypt [OPTIONS] prooffile", 335 "gnunet-scrypt [OPTIONS] prooffile",
336 gettext_noop ("Manipulate GNUnet proof of work files"), 336 gettext_noop("Manipulate GNUnet proof of work files"),
337 options, 337 options,
338 &run, 338 &run,
339 NULL)) 339 NULL))
340 ? 0 340 ? 0
341 : 1; 341 : 1;
342 GNUNET_free ((void *) argv); 342 GNUNET_free((void *)argv);
343 GNUNET_free_non_null (pwfn); 343 GNUNET_free_non_null(pwfn);
344 return ret; 344 return ret;
345} 345}
346 346
diff --git a/src/util/gnunet-service-resolver.c b/src/util/gnunet-service-resolver.c
index 2cabe553b..a69a7bd66 100644
--- a/src/util/gnunet-service-resolver.c
+++ b/src/util/gnunet-service-resolver.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/gnunet-service-resolver.c 22 * @file util/gnunet-service-resolver.c
@@ -33,7 +33,7 @@
33/** 33/**
34 * How long do we wait for DNS answers? 34 * How long do we wait for DNS answers?
35 */ 35 */
36#define DNS_TIMEOUT GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30) 36#define DNS_TIMEOUT GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30)
37 37
38/** 38/**
39 * Maximum number of hostnames we cache results for. 39 * Maximum number of hostnames we cache results for.
@@ -43,8 +43,7 @@
43/** 43/**
44 * Entry in list of cached DNS records for a hostname. 44 * Entry in list of cached DNS records for a hostname.
45 */ 45 */
46struct RecordListEntry 46struct RecordListEntry {
47{
48 /** 47 /**
49 * This is a doubly linked list. 48 * This is a doubly linked list.
50 */ 49 */
@@ -65,8 +64,7 @@ struct RecordListEntry
65/** 64/**
66 * A cached DNS lookup result. 65 * A cached DNS lookup result.
67 */ 66 */
68struct ResolveCache 67struct ResolveCache {
69{
70 /** 68 /**
71 * This is a doubly linked list. 69 * This is a doubly linked list.
72 */ 70 */
@@ -97,8 +95,7 @@ struct ResolveCache
97/** 95/**
98 * Information about pending lookups. 96 * Information about pending lookups.
99 */ 97 */
100struct ActiveLookup 98struct ActiveLookup {
101{
102 /** 99 /**
103 * Stored in a DLL. 100 * Stored in a DLL.
104 */ 101 */
@@ -206,21 +203,21 @@ static unsigned int cache_size;
206 * @param rc entry to free 203 * @param rc entry to free
207 */ 204 */
208static void 205static void
209free_cache_entry (struct ResolveCache *rc) 206free_cache_entry(struct ResolveCache *rc)
210{ 207{
211 struct RecordListEntry *pos; 208 struct RecordListEntry *pos;
212 209
213 while (NULL != (pos = rc->records_head)) 210 while (NULL != (pos = rc->records_head))
214 { 211 {
215 GNUNET_CONTAINER_DLL_remove (rc->records_head, rc->records_tail, pos); 212 GNUNET_CONTAINER_DLL_remove(rc->records_head, rc->records_tail, pos);
216 GNUNET_DNSPARSER_free_record (pos->record); 213 GNUNET_DNSPARSER_free_record(pos->record);
217 GNUNET_free (pos->record); 214 GNUNET_free(pos->record);
218 GNUNET_free (pos); 215 GNUNET_free(pos);
219 } 216 }
220 GNUNET_free_non_null (rc->hostname); 217 GNUNET_free_non_null(rc->hostname);
221 GNUNET_CONTAINER_DLL_remove (cache_head, cache_tail, rc); 218 GNUNET_CONTAINER_DLL_remove(cache_head, cache_tail, rc);
222 cache_size--; 219 cache_size--;
223 GNUNET_free (rc); 220 GNUNET_free(rc);
224} 221}
225 222
226 223
@@ -230,21 +227,21 @@ free_cache_entry (struct ResolveCache *rc)
230 * @param rc entry to free 227 * @param rc entry to free
231 */ 228 */
232static void 229static void
233free_hosts_entry (struct ResolveCache *rc) 230free_hosts_entry(struct ResolveCache *rc)
234{ 231{
235 struct RecordListEntry *pos; 232 struct RecordListEntry *pos;
236 233
237 while (NULL != (pos = rc->records_head)) 234 while (NULL != (pos = rc->records_head))
238 { 235 {
239 GNUNET_CONTAINER_DLL_remove (rc->records_head, rc->records_tail, pos); 236 GNUNET_CONTAINER_DLL_remove(rc->records_head, rc->records_tail, pos);
240 GNUNET_DNSPARSER_free_record (pos->record); 237 GNUNET_DNSPARSER_free_record(pos->record);
241 GNUNET_free (pos->record); 238 GNUNET_free(pos->record);
242 GNUNET_free (pos); 239 GNUNET_free(pos);
243 } 240 }
244 GNUNET_free_non_null (rc->hostname); 241 GNUNET_free_non_null(rc->hostname);
245 GNUNET_CONTAINER_DLL_remove (hosts_head, hosts_tail, rc); 242 GNUNET_CONTAINER_DLL_remove(hosts_head, hosts_tail, rc);
246 cache_size--; 243 cache_size--;
247 GNUNET_free (rc); 244 GNUNET_free(rc);
248} 245}
249 246
250 247
@@ -254,21 +251,21 @@ free_hosts_entry (struct ResolveCache *rc)
254 * @param al an active lookup 251 * @param al an active lookup
255 */ 252 */
256static void 253static void
257free_active_lookup (struct ActiveLookup *al) 254free_active_lookup(struct ActiveLookup *al)
258{ 255{
259 GNUNET_CONTAINER_DLL_remove (lookup_head, lookup_tail, al); 256 GNUNET_CONTAINER_DLL_remove(lookup_head, lookup_tail, al);
260 if (NULL != al->resolve_handle) 257 if (NULL != al->resolve_handle)
261 { 258 {
262 GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle); 259 GNUNET_DNSSTUB_resolve_cancel(al->resolve_handle);
263 al->resolve_handle = NULL; 260 al->resolve_handle = NULL;
264 } 261 }
265 if (NULL != al->timeout_task) 262 if (NULL != al->timeout_task)
266 { 263 {
267 GNUNET_SCHEDULER_cancel (al->timeout_task); 264 GNUNET_SCHEDULER_cancel(al->timeout_task);
268 al->timeout_task = NULL; 265 al->timeout_task = NULL;
269 } 266 }
270 GNUNET_free_non_null (al->hostname); 267 GNUNET_free_non_null(al->hostname);
271 GNUNET_free (al); 268 GNUNET_free(al);
272} 269}
273 270
274 271
@@ -282,11 +279,11 @@ free_active_lookup (struct ActiveLookup *al)
282 * @return NULL if no nameserver is configured in this @a line 279 * @return NULL if no nameserver is configured in this @a line
283 */ 280 */
284static char * 281static char *
285extract_dns_server (const char *line, size_t line_len) 282extract_dns_server(const char *line, size_t line_len)
286{ 283{
287 if (0 == strncmp (line, "nameserver ", strlen ("nameserver "))) 284 if (0 == strncmp(line, "nameserver ", strlen("nameserver ")))
288 return GNUNET_strndup (line + strlen ("nameserver "), 285 return GNUNET_strndup(line + strlen("nameserver "),
289 line_len - strlen ("nameserver ")); 286 line_len - strlen("nameserver "));
290 return NULL; 287 return NULL;
291} 288}
292 289
@@ -301,11 +298,11 @@ extract_dns_server (const char *line, size_t line_len)
301 * @return NULL if no nameserver is configured in this @a line 298 * @return NULL if no nameserver is configured in this @a line
302 */ 299 */
303static char * 300static char *
304extract_search_domain (const char *line, size_t line_len) 301extract_search_domain(const char *line, size_t line_len)
305{ 302{
306 if (0 == strncmp (line, "search ", strlen ("search "))) 303 if (0 == strncmp(line, "search ", strlen("search ")))
307 return GNUNET_strndup (line + strlen ("search "), 304 return GNUNET_strndup(line + strlen("search "),
308 line_len - strlen ("search ")); 305 line_len - strlen("search "));
309 return NULL; 306 return NULL;
310} 307}
311 308
@@ -317,7 +314,7 @@ extract_search_domain (const char *line, size_t line_len)
317 * @return the number of server addresses in @server_addrs, -1 on error 314 * @return the number of server addresses in @server_addrs, -1 on error
318 */ 315 */
319static int 316static int
320lookup_dns_servers (char ***server_addrs) 317lookup_dns_servers(char ***server_addrs)
321{ 318{
322 struct GNUNET_DISK_FileHandle *fh; 319 struct GNUNET_DISK_FileHandle *fh;
323 struct GNUNET_DISK_MapHandle *mh; 320 struct GNUNET_DISK_MapHandle *mh;
@@ -326,63 +323,63 @@ lookup_dns_servers (char ***server_addrs)
326 size_t read_offset; 323 size_t read_offset;
327 unsigned int num_dns_servers; 324 unsigned int num_dns_servers;
328 325
329 fh = GNUNET_DISK_file_open ("/etc/resolv.conf", 326 fh = GNUNET_DISK_file_open("/etc/resolv.conf",
330 GNUNET_DISK_OPEN_READ, 327 GNUNET_DISK_OPEN_READ,
331 GNUNET_DISK_PERM_NONE); 328 GNUNET_DISK_PERM_NONE);
332 if (NULL == fh) 329 if (NULL == fh)
333 { 330 {
334 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 331 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
335 "Could not open /etc/resolv.conf. " 332 "Could not open /etc/resolv.conf. "
336 "DNS resolution will not be possible.\n"); 333 "DNS resolution will not be possible.\n");
337 return -1; 334 return -1;
338 } 335 }
339 if (GNUNET_OK != GNUNET_DISK_file_handle_size (fh, &bytes_read)) 336 if (GNUNET_OK != GNUNET_DISK_file_handle_size(fh, &bytes_read))
340 { 337 {
341 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 338 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
342 "Could not determine size of /etc/resolv.conf. " 339 "Could not determine size of /etc/resolv.conf. "
343 "DNS resolution will not be possible.\n"); 340 "DNS resolution will not be possible.\n");
344 GNUNET_DISK_file_close (fh); 341 GNUNET_DISK_file_close(fh);
345 return -1; 342 return -1;
346 } 343 }
347 if (((unsigned long long) bytes_read) > (unsigned long long) SIZE_MAX) 344 if (((unsigned long long)bytes_read) > (unsigned long long)SIZE_MAX)
348 { 345 {
349 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 346 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
350 "/etc/resolv.conf file too large to mmap. " 347 "/etc/resolv.conf file too large to mmap. "
351 "DNS resolution will not be possible.\n"); 348 "DNS resolution will not be possible.\n");
352 GNUNET_DISK_file_close (fh); 349 GNUNET_DISK_file_close(fh);
353 return -1; 350 return -1;
354 } 351 }
355 buf = GNUNET_DISK_file_map (fh, 352 buf = GNUNET_DISK_file_map(fh,
356 &mh, 353 &mh,
357 GNUNET_DISK_MAP_TYPE_READ, 354 GNUNET_DISK_MAP_TYPE_READ,
358 (size_t) bytes_read); 355 (size_t)bytes_read);
359 *server_addrs = NULL; 356 *server_addrs = NULL;
360 read_offset = 0; 357 read_offset = 0;
361 num_dns_servers = 0; 358 num_dns_servers = 0;
362 while (read_offset < (size_t) bytes_read) 359 while (read_offset < (size_t)bytes_read)
363 {
364 const char *newline;
365 size_t line_len;
366 char *dns_server;
367
368 newline = strchr (buf + read_offset, '\n');
369 if (NULL == newline)
370 break;
371 line_len = newline - buf - read_offset;
372 dns_server = extract_dns_server (buf + read_offset, line_len);
373 if (NULL != dns_server)
374 { 360 {
375 GNUNET_array_append (*server_addrs, num_dns_servers, dns_server); 361 const char *newline;
376 } 362 size_t line_len;
377 else if (NULL == my_domain) 363 char *dns_server;
378 { 364
379 my_domain = extract_search_domain (buf + read_offset, line_len); 365 newline = strchr(buf + read_offset, '\n');
366 if (NULL == newline)
367 break;
368 line_len = newline - buf - read_offset;
369 dns_server = extract_dns_server(buf + read_offset, line_len);
370 if (NULL != dns_server)
371 {
372 GNUNET_array_append(*server_addrs, num_dns_servers, dns_server);
373 }
374 else if (NULL == my_domain)
375 {
376 my_domain = extract_search_domain(buf + read_offset, line_len);
377 }
378 read_offset += line_len + 1;
380 } 379 }
381 read_offset += line_len + 1; 380 GNUNET_DISK_file_unmap(mh);
382 } 381 GNUNET_DISK_file_close(fh);
383 GNUNET_DISK_file_unmap (mh); 382 return (int)num_dns_servers;
384 GNUNET_DISK_file_close (fh);
385 return (int) num_dns_servers;
386} 383}
387 384
388 385
@@ -393,52 +390,52 @@ lookup_dns_servers (char ***server_addrs)
393 * @param af address family of @a ip, AF_INET or AF_INET6 390 * @param af address family of @a ip, AF_INET or AF_INET6
394 */ 391 */
395static char * 392static char *
396make_reverse_hostname (const void *ip, int af) 393make_reverse_hostname(const void *ip, int af)
397{ 394{
398 char *buf = GNUNET_new_array (80, char); 395 char *buf = GNUNET_new_array(80, char);
399 int pos = 0; 396 int pos = 0;
400 397
401 if (AF_INET == af) 398 if (AF_INET == af)
402 {
403 struct in_addr *addr = (struct in_addr *) ip;
404 uint32_t ip_int = addr->s_addr;
405
406 for (int i = 3; i >= 0; i--)
407 { 399 {
408 int n = 400 struct in_addr *addr = (struct in_addr *)ip;
409 GNUNET_snprintf (buf + pos, 80 - pos, "%u.", ((uint8_t *) &ip_int)[i]); 401 uint32_t ip_int = addr->s_addr;
410 if (n < 0) 402
411 { 403 for (int i = 3; i >= 0; i--)
412 GNUNET_free (buf); 404 {
413 return NULL; 405 int n =
414 } 406 GNUNET_snprintf(buf + pos, 80 - pos, "%u.", ((uint8_t *)&ip_int)[i]);
415 pos += n; 407 if (n < 0)
408 {
409 GNUNET_free(buf);
410 return NULL;
411 }
412 pos += n;
413 }
414 pos += GNUNET_snprintf(buf + pos, 80 - pos, "in-addr.arpa");
416 } 415 }
417 pos += GNUNET_snprintf (buf + pos, 80 - pos, "in-addr.arpa");
418 }
419 else if (AF_INET6 == af) 416 else if (AF_INET6 == af)
420 {
421 struct in6_addr *addr = (struct in6_addr *) ip;
422 for (int i = 15; i >= 0; i--)
423 { 417 {
424 int n = 418 struct in6_addr *addr = (struct in6_addr *)ip;
425 GNUNET_snprintf (buf + pos, 80 - pos, "%x.", addr->s6_addr[i] & 0xf); 419 for (int i = 15; i >= 0; i--)
426 if (n < 0) 420 {
427 { 421 int n =
428 GNUNET_free (buf); 422 GNUNET_snprintf(buf + pos, 80 - pos, "%x.", addr->s6_addr[i] & 0xf);
429 return NULL; 423 if (n < 0)
430 } 424 {
431 pos += n; 425 GNUNET_free(buf);
432 n = GNUNET_snprintf (buf + pos, 80 - pos, "%x.", addr->s6_addr[i] >> 4); 426 return NULL;
433 if (n < 0) 427 }
434 { 428 pos += n;
435 GNUNET_free (buf); 429 n = GNUNET_snprintf(buf + pos, 80 - pos, "%x.", addr->s6_addr[i] >> 4);
436 return NULL; 430 if (n < 0)
437 } 431 {
438 pos += n; 432 GNUNET_free(buf);
433 return NULL;
434 }
435 pos += n;
436 }
437 pos += GNUNET_snprintf(buf + pos, 80 - pos, "ip6.arpa");
439 } 438 }
440 pos += GNUNET_snprintf (buf + pos, 80 - pos, "ip6.arpa");
441 }
442 buf[pos] = '\0'; 439 buf[pos] = '\0';
443 return buf; 440 return buf;
444} 441}
@@ -456,10 +453,10 @@ make_reverse_hostname (const void *ip, int af)
456 * does not match @a record_type 453 * does not match @a record_type
457 */ 454 */
458static int 455static int
459send_reply (struct GNUNET_DNSPARSER_Record *record, 456send_reply(struct GNUNET_DNSPARSER_Record *record,
460 uint16_t record_type, 457 uint16_t record_type,
461 uint32_t client_request_id, 458 uint32_t client_request_id,
462 struct GNUNET_SERVICE_Client *client) 459 struct GNUNET_SERVICE_Client *client)
463{ 460{
464 struct GNUNET_RESOLVER_ResponseMessage *msg; 461 struct GNUNET_RESOLVER_ResponseMessage *msg;
465 struct GNUNET_MQ_Envelope *env; 462 struct GNUNET_MQ_Envelope *env;
@@ -467,45 +464,49 @@ send_reply (struct GNUNET_DNSPARSER_Record *record,
467 size_t payload_len; 464 size_t payload_len;
468 465
469 switch (record->type) 466 switch (record->type)
470 { 467 {
471 case GNUNET_DNSPARSER_TYPE_CNAME: 468 case GNUNET_DNSPARSER_TYPE_CNAME:
472 if (GNUNET_DNSPARSER_TYPE_CNAME != record_type) 469 if (GNUNET_DNSPARSER_TYPE_CNAME != record_type)
473 return GNUNET_NO; 470 return GNUNET_NO;
474 payload = record->data.hostname; 471 payload = record->data.hostname;
475 payload_len = strlen (record->data.hostname) + 1; 472 payload_len = strlen(record->data.hostname) + 1;
476 break; 473 break;
477 case GNUNET_DNSPARSER_TYPE_PTR: 474
478 if (GNUNET_DNSPARSER_TYPE_PTR != record_type) 475 case GNUNET_DNSPARSER_TYPE_PTR:
479 return GNUNET_NO; 476 if (GNUNET_DNSPARSER_TYPE_PTR != record_type)
480 payload = record->data.hostname; 477 return GNUNET_NO;
481 payload_len = strlen (record->data.hostname) + 1; 478 payload = record->data.hostname;
482 break; 479 payload_len = strlen(record->data.hostname) + 1;
483 case GNUNET_DNSPARSER_TYPE_A: 480 break;
484 if ((GNUNET_DNSPARSER_TYPE_A != record_type) && 481
485 (GNUNET_DNSPARSER_TYPE_ALL != record_type)) 482 case GNUNET_DNSPARSER_TYPE_A:
486 return GNUNET_NO; 483 if ((GNUNET_DNSPARSER_TYPE_A != record_type) &&
487 payload = record->data.raw.data; 484 (GNUNET_DNSPARSER_TYPE_ALL != record_type))
488 payload_len = record->data.raw.data_len; 485 return GNUNET_NO;
489 break; 486 payload = record->data.raw.data;
490 case GNUNET_DNSPARSER_TYPE_AAAA: 487 payload_len = record->data.raw.data_len;
491 if ((GNUNET_DNSPARSER_TYPE_AAAA != record_type) && 488 break;
492 (GNUNET_DNSPARSER_TYPE_ALL != record_type)) 489
490 case GNUNET_DNSPARSER_TYPE_AAAA:
491 if ((GNUNET_DNSPARSER_TYPE_AAAA != record_type) &&
492 (GNUNET_DNSPARSER_TYPE_ALL != record_type))
493 return GNUNET_NO;
494 payload = record->data.raw.data;
495 payload_len = record->data.raw.data_len;
496 break;
497
498 default:
499 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
500 "Cannot handle DNS response type %u: not supported here\n",
501 record->type);
493 return GNUNET_NO; 502 return GNUNET_NO;
494 payload = record->data.raw.data; 503 }
495 payload_len = record->data.raw.data_len; 504 env = GNUNET_MQ_msg_extra(msg,
496 break; 505 payload_len,
497 default: 506 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
498 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
499 "Cannot handle DNS response type %u: not supported here\n",
500 record->type);
501 return GNUNET_NO;
502 }
503 env = GNUNET_MQ_msg_extra (msg,
504 payload_len,
505 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
506 msg->client_id = client_request_id; 507 msg->client_id = client_request_id;
507 GNUNET_memcpy (&msg[1], payload, payload_len); 508 GNUNET_memcpy(&msg[1], payload, payload_len);
508 GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); 509 GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env);
509 return GNUNET_YES; 510 return GNUNET_YES;
510} 511}
511 512
@@ -518,15 +519,15 @@ send_reply (struct GNUNET_DNSPARSER_Record *record,
518 * @param client where to send @a record 519 * @param client where to send @a record
519 */ 520 */
520static void 521static void
521send_end_msg (uint32_t client_request_id, struct GNUNET_SERVICE_Client *client) 522send_end_msg(uint32_t client_request_id, struct GNUNET_SERVICE_Client *client)
522{ 523{
523 struct GNUNET_RESOLVER_ResponseMessage *msg; 524 struct GNUNET_RESOLVER_ResponseMessage *msg;
524 struct GNUNET_MQ_Envelope *env; 525 struct GNUNET_MQ_Envelope *env;
525 526
526 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Sending END message\n"); 527 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Sending END message\n");
527 env = GNUNET_MQ_msg (msg, GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE); 528 env = GNUNET_MQ_msg(msg, GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE);
528 msg->client_id = client_request_id; 529 msg->client_id = client_request_id;
529 GNUNET_MQ_send (GNUNET_SERVICE_client_get_mq (client), env); 530 GNUNET_MQ_send(GNUNET_SERVICE_client_get_mq(client), env);
530} 531}
531 532
532 533
@@ -538,27 +539,27 @@ send_end_msg (uint32_t client_request_id, struct GNUNET_SERVICE_Client *client)
538 * #GNUNET_NO if some entries are left 539 * #GNUNET_NO if some entries are left
539 */ 540 */
540static int 541static int
541remove_expired (struct ResolveCache *rc) 542remove_expired(struct ResolveCache *rc)
542{ 543{
543 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); 544 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
544 struct RecordListEntry *n; 545 struct RecordListEntry *n;
545 546
546 for (struct RecordListEntry *pos = rc->records_head; NULL != pos; pos = n) 547 for (struct RecordListEntry *pos = rc->records_head; NULL != pos; pos = n)
547 {
548 n = pos->next;
549 if (now.abs_value_us > pos->record->expiration_time.abs_value_us)
550 { 548 {
551 GNUNET_CONTAINER_DLL_remove (rc->records_head, rc->records_tail, pos); 549 n = pos->next;
552 GNUNET_DNSPARSER_free_record (pos->record); 550 if (now.abs_value_us > pos->record->expiration_time.abs_value_us)
553 GNUNET_free (pos->record); 551 {
554 GNUNET_free (pos); 552 GNUNET_CONTAINER_DLL_remove(rc->records_head, rc->records_tail, pos);
553 GNUNET_DNSPARSER_free_record(pos->record);
554 GNUNET_free(pos->record);
555 GNUNET_free(pos);
556 }
555 } 557 }
556 }
557 if (NULL == rc->records_head) 558 if (NULL == rc->records_head)
558 { 559 {
559 free_cache_entry (rc); 560 free_cache_entry(rc);
560 return GNUNET_YES; 561 return GNUNET_YES;
561 } 562 }
562 return GNUNET_NO; 563 return GNUNET_NO;
563} 564}
564 565
@@ -573,10 +574,10 @@ remove_expired (struct ResolveCache *rc)
573 * @param client who should get the result? 574 * @param client who should get the result?
574 */ 575 */
575static void 576static void
576process_get (const char *hostname, 577process_get(const char *hostname,
577 uint16_t record_type, 578 uint16_t record_type,
578 uint32_t client_request_id, 579 uint32_t client_request_id,
579 struct GNUNET_SERVICE_Client *client); 580 struct GNUNET_SERVICE_Client *client);
580 581
581 582
582/** 583/**
@@ -591,10 +592,10 @@ process_get (const char *hostname,
591 * @param client handle to the client making the request (for sending the reply) 592 * @param client handle to the client making the request (for sending the reply)
592 */ 593 */
593static int 594static int
594try_cache (const char *hostname, 595try_cache(const char *hostname,
595 uint16_t record_type, 596 uint16_t record_type,
596 uint32_t client_request_id, 597 uint32_t client_request_id,
597 struct GNUNET_SERVICE_Client *client) 598 struct GNUNET_SERVICE_Client *client)
598{ 599{
599 struct ResolveCache *pos; 600 struct ResolveCache *pos;
600 struct ResolveCache *next; 601 struct ResolveCache *next;
@@ -603,57 +604,57 @@ try_cache (const char *hostname,
603 604
604 in_hosts = GNUNET_NO; 605 in_hosts = GNUNET_NO;
605 for (pos = hosts_head; NULL != pos; pos = pos->next) 606 for (pos = hosts_head; NULL != pos; pos = pos->next)
606 if (0 == strcmp (pos->hostname, hostname)) 607 if (0 == strcmp(pos->hostname, hostname))
608 {
609 in_hosts = GNUNET_YES;
610 break;
611 }
612 if (NULL == pos)
607 { 613 {
608 in_hosts = GNUNET_YES; 614 next = cache_head;
609 break; 615 for (pos = next; NULL != pos; pos = next)
616 {
617 next = pos->next;
618 if (GNUNET_YES == remove_expired(pos))
619 continue;
620 if (0 == strcmp(pos->hostname, hostname))
621 break;
622 }
610 } 623 }
611 if (NULL == pos) 624 if (NULL == pos)
612 {
613 next = cache_head;
614 for (pos = next; NULL != pos; pos = next)
615 { 625 {
616 next = pos->next; 626 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "No cache entry for '%s'\n", hostname);
617 if (GNUNET_YES == remove_expired (pos)) 627 return GNUNET_NO;
618 continue;
619 if (0 == strcmp (pos->hostname, hostname))
620 break;
621 } 628 }
622 }
623 if (NULL == pos)
624 {
625 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "No cache entry for '%s'\n", hostname);
626 return GNUNET_NO;
627 }
628 if ((GNUNET_NO == in_hosts) && (cache_head != pos)) 629 if ((GNUNET_NO == in_hosts) && (cache_head != pos))
629 { 630 {
630 /* move result to head to achieve LRU for cache eviction */ 631 /* move result to head to achieve LRU for cache eviction */
631 GNUNET_CONTAINER_DLL_remove (cache_head, cache_tail, pos); 632 GNUNET_CONTAINER_DLL_remove(cache_head, cache_tail, pos);
632 GNUNET_CONTAINER_DLL_insert (cache_head, cache_tail, pos); 633 GNUNET_CONTAINER_DLL_insert(cache_head, cache_tail, pos);
633 } 634 }
634 found = GNUNET_NO; 635 found = GNUNET_NO;
635 for (struct RecordListEntry *rle = pos->records_head; NULL != rle; 636 for (struct RecordListEntry *rle = pos->records_head; NULL != rle;
636 rle = rle->next) 637 rle = rle->next)
637 {
638 const struct GNUNET_DNSPARSER_Record *record = rle->record;
639
640 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
641 "Found cache entry for '%s', record type '%u'\n",
642 hostname,
643 record_type);
644 if ((GNUNET_DNSPARSER_TYPE_CNAME == record->type) &&
645 (GNUNET_DNSPARSER_TYPE_CNAME != record_type) && (GNUNET_NO == found))
646 { 638 {
647 const char *hostname = record->data.hostname; 639 const struct GNUNET_DNSPARSER_Record *record = rle->record;
648 640
649 process_get (hostname, record_type, client_request_id, client); 641 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
650 return GNUNET_YES; /* counts as a cache "hit" */ 642 "Found cache entry for '%s', record type '%u'\n",
643 hostname,
644 record_type);
645 if ((GNUNET_DNSPARSER_TYPE_CNAME == record->type) &&
646 (GNUNET_DNSPARSER_TYPE_CNAME != record_type) && (GNUNET_NO == found))
647 {
648 const char *hostname = record->data.hostname;
649
650 process_get(hostname, record_type, client_request_id, client);
651 return GNUNET_YES; /* counts as a cache "hit" */
652 }
653 found |= send_reply(rle->record, record_type, client_request_id, client);
651 } 654 }
652 found |= send_reply (rle->record, record_type, client_request_id, client);
653 }
654 if (GNUNET_NO == found) 655 if (GNUNET_NO == found)
655 return GNUNET_NO; /* had records, but none matched! */ 656 return GNUNET_NO; /* had records, but none matched! */
656 send_end_msg (client_request_id, client); 657 send_end_msg(client_request_id, client);
657 return GNUNET_YES; 658 return GNUNET_YES;
658} 659}
659 660
@@ -670,64 +671,64 @@ try_cache (const char *hostname,
670 * @return #GNUNET_OK on success 671 * @return #GNUNET_OK on success
671 */ 672 */
672static int 673static int
673pack (const char *hostname, 674pack(const char *hostname,
674 uint16_t type, 675 uint16_t type,
675 uint16_t dns_id, 676 uint16_t dns_id,
676 char **packet_buf, 677 char **packet_buf,
677 size_t *packet_size) 678 size_t *packet_size)
678{ 679{
679 struct GNUNET_DNSPARSER_Query query; 680 struct GNUNET_DNSPARSER_Query query;
680 struct GNUNET_DNSPARSER_Packet packet; 681 struct GNUNET_DNSPARSER_Packet packet;
681 682
682 query.name = (char *) hostname; 683 query.name = (char *)hostname;
683 query.type = type; 684 query.type = type;
684 query.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; 685 query.dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;
685 memset (&packet, 0, sizeof (packet)); 686 memset(&packet, 0, sizeof(packet));
686 packet.num_queries = 1; 687 packet.num_queries = 1;
687 packet.queries = &query; 688 packet.queries = &query;
688 packet.id = htons (dns_id); 689 packet.id = htons(dns_id);
689 packet.flags.recursion_desired = 1; 690 packet.flags.recursion_desired = 1;
690 if (GNUNET_OK != 691 if (GNUNET_OK !=
691 GNUNET_DNSPARSER_pack (&packet, UINT16_MAX, packet_buf, packet_size)) 692 GNUNET_DNSPARSER_pack(&packet, UINT16_MAX, packet_buf, packet_size))
692 { 693 {
693 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 694 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
694 "Failed to pack query for hostname `%s'\n", 695 "Failed to pack query for hostname `%s'\n",
695 hostname); 696 hostname);
696 packet_buf = NULL; 697 packet_buf = NULL;
697 return GNUNET_SYSERR; 698 return GNUNET_SYSERR;
698 } 699 }
699 return GNUNET_OK; 700 return GNUNET_OK;
700} 701}
701 702
702static void 703static void
703cache_answers (const char *name, 704cache_answers(const char *name,
704 struct GNUNET_DNSPARSER_Record *records, 705 struct GNUNET_DNSPARSER_Record *records,
705 unsigned int num_records) 706 unsigned int num_records)
706{ 707{
707 struct ResolveCache *rc; 708 struct ResolveCache *rc;
708 struct GNUNET_DNSPARSER_Record *record; 709 struct GNUNET_DNSPARSER_Record *record;
709 struct RecordListEntry *rle; 710 struct RecordListEntry *rle;
710 711
711 for (unsigned int i = 0; i != num_records; i++) 712 for (unsigned int i = 0; i != num_records; i++)
712 {
713 record = &records[i];
714
715 for (rc = cache_head; NULL != rc; rc = rc->next)
716 if (0 == strcasecmp (rc->hostname, name))
717 break;
718 if (NULL == rc)
719 { 713 {
720 rc = GNUNET_new (struct ResolveCache); 714 record = &records[i];
721 rc->hostname = GNUNET_strdup (name); 715
722 GNUNET_CONTAINER_DLL_insert (cache_head, cache_tail, rc); 716 for (rc = cache_head; NULL != rc; rc = rc->next)
723 cache_size++; 717 if (0 == strcasecmp(rc->hostname, name))
718 break;
719 if (NULL == rc)
720 {
721 rc = GNUNET_new(struct ResolveCache);
722 rc->hostname = GNUNET_strdup(name);
723 GNUNET_CONTAINER_DLL_insert(cache_head, cache_tail, rc);
724 cache_size++;
725 }
726 /* TODO: ought to check first if we have this exact record
727 already in the cache! */
728 rle = GNUNET_new(struct RecordListEntry);
729 rle->record = GNUNET_DNSPARSER_duplicate_record(record);
730 GNUNET_CONTAINER_DLL_insert(rc->records_head, rc->records_tail, rle);
724 } 731 }
725 /* TODO: ought to check first if we have this exact record
726 already in the cache! */
727 rle = GNUNET_new (struct RecordListEntry);
728 rle->record = GNUNET_DNSPARSER_duplicate_record (record);
729 GNUNET_CONTAINER_DLL_insert (rc->records_head, rc->records_tail, rle);
730 }
731} 732}
732 733
733/** 734/**
@@ -739,107 +740,107 @@ cache_answers (const char *name,
739 * @param dns_len number of bytes in @a dns 740 * @param dns_len number of bytes in @a dns
740 */ 741 */
741static void 742static void
742handle_resolve_result (void *cls, 743handle_resolve_result(void *cls,
743 const struct GNUNET_TUN_DnsHeader *dns, 744 const struct GNUNET_TUN_DnsHeader *dns,
744 size_t dns_len) 745 size_t dns_len)
745{ 746{
746 struct ActiveLookup *al = cls; 747 struct ActiveLookup *al = cls;
747 struct GNUNET_DNSPARSER_Packet *parsed; 748 struct GNUNET_DNSPARSER_Packet *parsed;
748 749
749 parsed = GNUNET_DNSPARSER_parse ((const char *) dns, dns_len); 750 parsed = GNUNET_DNSPARSER_parse((const char *)dns, dns_len);
750 if (NULL == parsed) 751 if (NULL == parsed)
751 { 752 {
752 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 753 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
753 "Failed to parse DNS reply (hostname %s, request ID %u)\n", 754 "Failed to parse DNS reply (hostname %s, request ID %u)\n",
754 al->hostname, 755 al->hostname,
755 al->dns_id); 756 al->dns_id);
756 return; 757 return;
757 } 758 }
758 if (al->dns_id != ntohs (parsed->id)) 759 if (al->dns_id != ntohs(parsed->id))
759 { 760 {
760 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 761 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
761 "Request ID in DNS reply does not match\n"); 762 "Request ID in DNS reply does not match\n");
762 GNUNET_DNSPARSER_free_packet (parsed); 763 GNUNET_DNSPARSER_free_packet(parsed);
763 return; 764 return;
764 } 765 }
765 if (0 == parsed->num_answers + parsed->num_authority_records + 766 if (0 == parsed->num_answers + parsed->num_authority_records +
766 parsed->num_additional_records) 767 parsed->num_additional_records)
767 {
768 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
769 "DNS reply (hostname %s, request ID %u) contains no answers\n",
770 al->hostname,
771 (unsigned int) al->client_request_id);
772 /* resume by trying again from cache */
773 if (GNUNET_NO == try_cache (al->hostname,
774 al->record_type,
775 al->client_request_id,
776 al->client))
777 /* cache failed, tell client we could not get an answer */
778 { 768 {
779 send_end_msg (al->client_request_id, al->client); 769 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
770 "DNS reply (hostname %s, request ID %u) contains no answers\n",
771 al->hostname,
772 (unsigned int)al->client_request_id);
773 /* resume by trying again from cache */
774 if (GNUNET_NO == try_cache(al->hostname,
775 al->record_type,
776 al->client_request_id,
777 al->client))
778 /* cache failed, tell client we could not get an answer */
779 {
780 send_end_msg(al->client_request_id, al->client);
781 }
782 GNUNET_DNSPARSER_free_packet(parsed);
783 free_active_lookup(al);
784 return;
780 } 785 }
781 GNUNET_DNSPARSER_free_packet (parsed);
782 free_active_lookup (al);
783 return;
784 }
785 /* LRU-based cache eviction: we remove from tail */ 786 /* LRU-based cache eviction: we remove from tail */
786 while (cache_size > MAX_CACHE) 787 while (cache_size > MAX_CACHE)
787 free_cache_entry (cache_tail); 788 free_cache_entry(cache_tail);
788 789
789 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 790 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
790 "Got reply for hostname %s and request ID %u\n", 791 "Got reply for hostname %s and request ID %u\n",
791 al->hostname, 792 al->hostname,
792 (unsigned int) al->client_request_id); 793 (unsigned int)al->client_request_id);
793 /* add to cache */ 794 /* add to cache */
794 cache_answers (al->hostname, parsed->answers, parsed->num_answers); 795 cache_answers(al->hostname, parsed->answers, parsed->num_answers);
795 cache_answers (al->hostname, 796 cache_answers(al->hostname,
796 parsed->authority_records, 797 parsed->authority_records,
797 parsed->num_authority_records); 798 parsed->num_authority_records);
798 cache_answers (al->hostname, 799 cache_answers(al->hostname,
799 parsed->additional_records, 800 parsed->additional_records,
800 parsed->num_additional_records); 801 parsed->num_additional_records);
801 802
802 /* see if we need to do the 2nd request for AAAA records */ 803 /* see if we need to do the 2nd request for AAAA records */
803 if ((GNUNET_DNSPARSER_TYPE_ALL == al->record_type) && 804 if ((GNUNET_DNSPARSER_TYPE_ALL == al->record_type) &&
804 (GNUNET_NO == al->did_aaaa)) 805 (GNUNET_NO == al->did_aaaa))
805 { 806 {
806 char *packet_buf; 807 char *packet_buf;
807 size_t packet_size; 808 size_t packet_size;
808 uint16_t dns_id; 809 uint16_t dns_id;
809 810
810 dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, 811 dns_id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE,
811 UINT16_MAX); 812 UINT16_MAX);
812 if (GNUNET_OK == pack (al->hostname, 813 if (GNUNET_OK == pack(al->hostname,
813 GNUNET_DNSPARSER_TYPE_AAAA, 814 GNUNET_DNSPARSER_TYPE_AAAA,
814 dns_id, 815 dns_id,
815 &packet_buf, 816 &packet_buf,
816 &packet_size)) 817 &packet_size))
817 { 818 {
818 al->did_aaaa = GNUNET_YES; 819 al->did_aaaa = GNUNET_YES;
819 al->dns_id = dns_id; 820 al->dns_id = dns_id;
820 GNUNET_DNSSTUB_resolve_cancel (al->resolve_handle); 821 GNUNET_DNSSTUB_resolve_cancel(al->resolve_handle);
821 al->resolve_handle = GNUNET_DNSSTUB_resolve (dnsstub_ctx, 822 al->resolve_handle = GNUNET_DNSSTUB_resolve(dnsstub_ctx,
822 packet_buf, 823 packet_buf,
823 packet_size, 824 packet_size,
824 &handle_resolve_result, 825 &handle_resolve_result,
825 al); 826 al);
826 GNUNET_free (packet_buf); 827 GNUNET_free(packet_buf);
827 GNUNET_DNSPARSER_free_packet (parsed); 828 GNUNET_DNSPARSER_free_packet(parsed);
828 return; 829 return;
830 }
829 } 831 }
830 }
831 832
832 /* resume by trying again from cache */ 833 /* resume by trying again from cache */
833 if (GNUNET_NO == try_cache (al->hostname, 834 if (GNUNET_NO == try_cache(al->hostname,
834 al->record_type, 835 al->record_type,
835 al->client_request_id, 836 al->client_request_id,
836 al->client)) 837 al->client))
837 /* cache failed, tell client we could not get an answer */ 838 /* cache failed, tell client we could not get an answer */
838 { 839 {
839 send_end_msg (al->client_request_id, al->client); 840 send_end_msg(al->client_request_id, al->client);
840 } 841 }
841 free_active_lookup (al); 842 free_active_lookup(al);
842 GNUNET_DNSPARSER_free_packet (parsed); 843 GNUNET_DNSPARSER_free_packet(parsed);
843} 844}
844 845
845 846
@@ -850,14 +851,14 @@ handle_resolve_result (void *cls,
850 * @param cls a `struct ActiveLookup` 851 * @param cls a `struct ActiveLookup`
851 */ 852 */
852static void 853static void
853handle_resolve_timeout (void *cls) 854handle_resolve_timeout(void *cls)
854{ 855{
855 struct ActiveLookup *al = cls; 856 struct ActiveLookup *al = cls;
856 857
857 al->timeout_task = NULL; 858 al->timeout_task = NULL;
858 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "DNS lookup timeout!\n"); 859 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "DNS lookup timeout!\n");
859 send_end_msg (al->client_request_id, al->client); 860 send_end_msg(al->client_request_id, al->client);
860 free_active_lookup (al); 861 free_active_lookup(al);
861} 862}
862 863
863 864
@@ -872,10 +873,10 @@ handle_resolve_timeout (void *cls)
872 * @return #GNUNET_OK if the DNS query is now pending 873 * @return #GNUNET_OK if the DNS query is now pending
873 */ 874 */
874static int 875static int
875resolve_and_cache (const char *hostname, 876resolve_and_cache(const char *hostname,
876 uint16_t record_type, 877 uint16_t record_type,
877 uint32_t client_request_id, 878 uint32_t client_request_id,
878 struct GNUNET_SERVICE_Client *client) 879 struct GNUNET_SERVICE_Client *client)
879{ 880{
880 char *packet_buf; 881 char *packet_buf;
881 size_t packet_size; 882 size_t packet_size;
@@ -883,42 +884,42 @@ resolve_and_cache (const char *hostname,
883 uint16_t dns_id; 884 uint16_t dns_id;
884 uint16_t type; 885 uint16_t type;
885 886
886 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "resolve_and_cache `%s'\n", hostname); 887 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "resolve_and_cache `%s'\n", hostname);
887 dns_id = (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_NONCE, 888 dns_id = (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_NONCE,
888 UINT16_MAX); 889 UINT16_MAX);
889 890
890 if (GNUNET_DNSPARSER_TYPE_ALL == record_type) 891 if (GNUNET_DNSPARSER_TYPE_ALL == record_type)
891 type = GNUNET_DNSPARSER_TYPE_A; 892 type = GNUNET_DNSPARSER_TYPE_A;
892 else 893 else
893 type = record_type; 894 type = record_type;
894 if (GNUNET_OK != pack (hostname, type, dns_id, &packet_buf, &packet_size)) 895 if (GNUNET_OK != pack(hostname, type, dns_id, &packet_buf, &packet_size))
895 { 896 {
896 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 897 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
897 "Failed to pack query for hostname `%s'\n", 898 "Failed to pack query for hostname `%s'\n",
898 hostname); 899 hostname);
899 return GNUNET_SYSERR; 900 return GNUNET_SYSERR;
900 } 901 }
901 902
902 al = GNUNET_new (struct ActiveLookup); 903 al = GNUNET_new(struct ActiveLookup);
903 al->hostname = GNUNET_strdup (hostname); 904 al->hostname = GNUNET_strdup(hostname);
904 al->record_type = record_type; 905 al->record_type = record_type;
905 al->client_request_id = client_request_id; 906 al->client_request_id = client_request_id;
906 al->dns_id = dns_id; 907 al->dns_id = dns_id;
907 al->client = client; 908 al->client = client;
908 al->timeout_task = 909 al->timeout_task =
909 GNUNET_SCHEDULER_add_delayed (DNS_TIMEOUT, &handle_resolve_timeout, al); 910 GNUNET_SCHEDULER_add_delayed(DNS_TIMEOUT, &handle_resolve_timeout, al);
910 al->resolve_handle = GNUNET_DNSSTUB_resolve (dnsstub_ctx, 911 al->resolve_handle = GNUNET_DNSSTUB_resolve(dnsstub_ctx,
911 packet_buf, 912 packet_buf,
912 packet_size, 913 packet_size,
913 &handle_resolve_result, 914 &handle_resolve_result,
914 al); 915 al);
915 GNUNET_free (packet_buf); 916 GNUNET_free(packet_buf);
916 GNUNET_CONTAINER_DLL_insert (lookup_head, lookup_tail, al); 917 GNUNET_CONTAINER_DLL_insert(lookup_head, lookup_tail, al);
917 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 918 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
918 "Resolving %s, client_request_id = %u, dns_id = %u\n", 919 "Resolving %s, client_request_id = %u, dns_id = %u\n",
919 hostname, 920 hostname,
920 (unsigned int) client_request_id, 921 (unsigned int)client_request_id,
921 (unsigned int) dns_id); 922 (unsigned int)dns_id);
922 return GNUNET_OK; 923 return GNUNET_OK;
923} 924}
924 925
@@ -933,38 +934,38 @@ resolve_and_cache (const char *hostname,
933 * @param client who should get the result? 934 * @param client who should get the result?
934 */ 935 */
935static void 936static void
936process_get (const char *hostname, 937process_get(const char *hostname,
937 uint16_t record_type, 938 uint16_t record_type,
938 uint32_t client_request_id, 939 uint32_t client_request_id,
939 struct GNUNET_SERVICE_Client *client) 940 struct GNUNET_SERVICE_Client *client)
940{ 941{
941 char fqdn[255]; 942 char fqdn[255];
942 943
943 if (GNUNET_NO != try_cache (hostname, record_type, client_request_id, client)) 944 if (GNUNET_NO != try_cache(hostname, record_type, client_request_id, client))
944 return; 945 return;
945 if ((NULL != my_domain) && (NULL == strchr (hostname, (unsigned char) '.')) && 946 if ((NULL != my_domain) && (NULL == strchr(hostname, (unsigned char)'.')) &&
946 (strlen (hostname) + strlen (my_domain) <= 253)) 947 (strlen(hostname) + strlen(my_domain) <= 253))
947 { 948 {
948 GNUNET_snprintf (fqdn, sizeof (fqdn), "%s.%s", hostname, my_domain); 949 GNUNET_snprintf(fqdn, sizeof(fqdn), "%s.%s", hostname, my_domain);
949 } 950 }
950 else if (strlen (hostname) < 255) 951 else if (strlen(hostname) < 255)
951 { 952 {
952 GNUNET_snprintf (fqdn, sizeof (fqdn), "%s", hostname); 953 GNUNET_snprintf(fqdn, sizeof(fqdn), "%s", hostname);
953 } 954 }
954 else 955 else
955 {
956 GNUNET_break (0);
957 GNUNET_SERVICE_client_drop (client);
958 return;
959 }
960 if (GNUNET_NO == try_cache (fqdn, record_type, client_request_id, client))
961 {
962 if (GNUNET_OK !=
963 resolve_and_cache (fqdn, record_type, client_request_id, client))
964 { 956 {
965 send_end_msg (client_request_id, client); 957 GNUNET_break(0);
958 GNUNET_SERVICE_client_drop(client);
959 return;
960 }
961 if (GNUNET_NO == try_cache(fqdn, record_type, client_request_id, client))
962 {
963 if (GNUNET_OK !=
964 resolve_and_cache(fqdn, record_type, client_request_id, client))
965 {
966 send_end_msg(client_request_id, client);
967 }
966 } 968 }
967 }
968} 969}
969 970
970 971
@@ -976,41 +977,43 @@ process_get (const char *hostname,
976 * @return #GNUNET_OK if @a get is well-formed 977 * @return #GNUNET_OK if @a get is well-formed
977 */ 978 */
978static int 979static int
979check_get (void *cls, const struct GNUNET_RESOLVER_GetMessage *get) 980check_get(void *cls, const struct GNUNET_RESOLVER_GetMessage *get)
980{ 981{
981 uint16_t size; 982 uint16_t size;
982 int direction; 983 int direction;
983 int af; 984 int af;
984 985
985 (void) cls; 986 (void)cls;
986 size = ntohs (get->header.size) - sizeof (*get); 987 size = ntohs(get->header.size) - sizeof(*get);
987 direction = ntohl (get->direction); 988 direction = ntohl(get->direction);
988 if (GNUNET_NO == direction) 989 if (GNUNET_NO == direction)
989 {
990 GNUNET_MQ_check_zero_termination (get);
991 return GNUNET_OK;
992 }
993 af = ntohl (get->af);
994 switch (af)
995 {
996 case AF_INET:
997 if (size != sizeof (struct in_addr))
998 { 990 {
999 GNUNET_break (0); 991 GNUNET_MQ_check_zero_termination(get);
1000 return GNUNET_SYSERR; 992 return GNUNET_OK;
1001 } 993 }
1002 break; 994 af = ntohl(get->af);
1003 case AF_INET6: 995 switch (af)
1004 if (size != sizeof (struct in6_addr))
1005 { 996 {
1006 GNUNET_break (0); 997 case AF_INET:
998 if (size != sizeof(struct in_addr))
999 {
1000 GNUNET_break(0);
1001 return GNUNET_SYSERR;
1002 }
1003 break;
1004
1005 case AF_INET6:
1006 if (size != sizeof(struct in6_addr))
1007 {
1008 GNUNET_break(0);
1009 return GNUNET_SYSERR;
1010 }
1011 break;
1012
1013 default:
1014 GNUNET_break(0);
1007 return GNUNET_SYSERR; 1015 return GNUNET_SYSERR;
1008 } 1016 }
1009 break;
1010 default:
1011 GNUNET_break (0);
1012 return GNUNET_SYSERR;
1013 }
1014 return GNUNET_OK; 1017 return GNUNET_OK;
1015} 1018}
1016 1019
@@ -1022,7 +1025,7 @@ check_get (void *cls, const struct GNUNET_RESOLVER_GetMessage *get)
1022 * @param msg the actual message 1025 * @param msg the actual message
1023 */ 1026 */
1024static void 1027static void
1025handle_get (void *cls, const struct GNUNET_RESOLVER_GetMessage *msg) 1028handle_get(void *cls, const struct GNUNET_RESOLVER_GetMessage *msg)
1026{ 1029{
1027 struct GNUNET_SERVICE_Client *client = cls; 1030 struct GNUNET_SERVICE_Client *client = cls;
1028 int direction; 1031 int direction;
@@ -1030,56 +1033,59 @@ handle_get (void *cls, const struct GNUNET_RESOLVER_GetMessage *msg)
1030 uint32_t client_request_id; 1033 uint32_t client_request_id;
1031 char *hostname; 1034 char *hostname;
1032 1035
1033 direction = ntohl (msg->direction); 1036 direction = ntohl(msg->direction);
1034 af = ntohl (msg->af); 1037 af = ntohl(msg->af);
1035 client_request_id = msg->client_id; 1038 client_request_id = msg->client_id;
1036 GNUNET_SERVICE_client_continue (client); 1039 GNUNET_SERVICE_client_continue(client);
1037 if (GNUNET_NO == direction) 1040 if (GNUNET_NO == direction)
1038 {
1039 /* IP from hostname */
1040 hostname = GNUNET_strdup ((const char *) &msg[1]);
1041 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
1042 "Client asks to resolve `%s'\n",
1043 hostname);
1044 switch (af)
1045 { 1041 {
1046 case AF_UNSPEC: { 1042 /* IP from hostname */
1047 process_get (hostname, 1043 hostname = GNUNET_strdup((const char *)&msg[1]);
1048 GNUNET_DNSPARSER_TYPE_ALL, 1044 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1049 client_request_id, 1045 "Client asks to resolve `%s'\n",
1050 client); 1046 hostname);
1051 break; 1047 switch (af)
1052 } 1048 {
1053 case AF_INET: { 1049 case AF_UNSPEC: {
1054 process_get (hostname, 1050 process_get(hostname,
1055 GNUNET_DNSPARSER_TYPE_A, 1051 GNUNET_DNSPARSER_TYPE_ALL,
1056 client_request_id, 1052 client_request_id,
1057 client); 1053 client);
1058 break; 1054 break;
1059 } 1055 }
1060 case AF_INET6: { 1056
1061 process_get (hostname, 1057 case AF_INET: {
1062 GNUNET_DNSPARSER_TYPE_AAAA, 1058 process_get(hostname,
1063 client_request_id, 1059 GNUNET_DNSPARSER_TYPE_A,
1064 client); 1060 client_request_id,
1065 break; 1061 client);
1066 } 1062 break;
1067 default: { 1063 }
1068 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "got invalid af: %d\n", af); 1064
1069 GNUNET_assert (0); 1065 case AF_INET6: {
1066 process_get(hostname,
1067 GNUNET_DNSPARSER_TYPE_AAAA,
1068 client_request_id,
1069 client);
1070 break;
1071 }
1072
1073 default: {
1074 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "got invalid af: %d\n", af);
1075 GNUNET_assert(0);
1076 }
1077 }
1070 } 1078 }
1071 }
1072 }
1073 else 1079 else
1074 { 1080 {
1075 /* hostname from IP */ 1081 /* hostname from IP */
1076 hostname = make_reverse_hostname (&msg[1], af); 1082 hostname = make_reverse_hostname(&msg[1], af);
1077 process_get (hostname, 1083 process_get(hostname,
1078 GNUNET_DNSPARSER_TYPE_PTR, 1084 GNUNET_DNSPARSER_TYPE_PTR,
1079 client_request_id, 1085 client_request_id,
1080 client); 1086 client);
1081 } 1087 }
1082 GNUNET_free_non_null (hostname); 1088 GNUNET_free_non_null(hostname);
1083} 1089}
1084 1090
1085 1091
@@ -1089,18 +1095,18 @@ handle_get (void *cls, const struct GNUNET_RESOLVER_GetMessage *msg)
1089 * @param cls NULL, unused 1095 * @param cls NULL, unused
1090 */ 1096 */
1091static void 1097static void
1092shutdown_task (void *cls) 1098shutdown_task(void *cls)
1093{ 1099{
1094 (void) cls; 1100 (void)cls;
1095 1101
1096 while (NULL != lookup_head) 1102 while (NULL != lookup_head)
1097 free_active_lookup (lookup_head); 1103 free_active_lookup(lookup_head);
1098 while (NULL != cache_head) 1104 while (NULL != cache_head)
1099 free_cache_entry (cache_head); 1105 free_cache_entry(cache_head);
1100 while (NULL != hosts_head) 1106 while (NULL != hosts_head)
1101 free_hosts_entry (hosts_head); 1107 free_hosts_entry(hosts_head);
1102 GNUNET_DNSSTUB_stop (dnsstub_ctx); 1108 GNUNET_DNSSTUB_stop(dnsstub_ctx);
1103 GNUNET_free_non_null (my_domain); 1109 GNUNET_free_non_null(my_domain);
1104} 1110}
1105 1111
1106 1112
@@ -1114,28 +1120,28 @@ shutdown_task (void *cls)
1114 * @param data_size number of bytes in @a data 1120 * @param data_size number of bytes in @a data
1115 */ 1121 */
1116static void 1122static void
1117add_host (const char *hostname, 1123add_host(const char *hostname,
1118 uint16_t rec_type, 1124 uint16_t rec_type,
1119 const void *data, 1125 const void *data,
1120 size_t data_size) 1126 size_t data_size)
1121{ 1127{
1122 struct ResolveCache *rc; 1128 struct ResolveCache *rc;
1123 struct RecordListEntry *rle; 1129 struct RecordListEntry *rle;
1124 struct GNUNET_DNSPARSER_Record *rec; 1130 struct GNUNET_DNSPARSER_Record *rec;
1125 1131
1126 rec = GNUNET_malloc (sizeof (struct GNUNET_DNSPARSER_Record)); 1132 rec = GNUNET_malloc(sizeof(struct GNUNET_DNSPARSER_Record));
1127 rec->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS; 1133 rec->expiration_time = GNUNET_TIME_UNIT_FOREVER_ABS;
1128 rec->type = rec_type; 1134 rec->type = rec_type;
1129 rec->dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET; 1135 rec->dns_traffic_class = GNUNET_TUN_DNS_CLASS_INTERNET;
1130 rec->name = GNUNET_strdup (hostname); 1136 rec->name = GNUNET_strdup(hostname);
1131 rec->data.raw.data = GNUNET_memdup (data, data_size); 1137 rec->data.raw.data = GNUNET_memdup(data, data_size);
1132 rec->data.raw.data_len = data_size; 1138 rec->data.raw.data_len = data_size;
1133 rle = GNUNET_new (struct RecordListEntry); 1139 rle = GNUNET_new(struct RecordListEntry);
1134 rle->record = rec; 1140 rle->record = rec;
1135 rc = GNUNET_new (struct ResolveCache); 1141 rc = GNUNET_new(struct ResolveCache);
1136 rc->hostname = GNUNET_strdup (hostname); 1142 rc->hostname = GNUNET_strdup(hostname);
1137 GNUNET_CONTAINER_DLL_insert (rc->records_head, rc->records_tail, rle); 1143 GNUNET_CONTAINER_DLL_insert(rc->records_head, rc->records_tail, rle);
1138 GNUNET_CONTAINER_DLL_insert (hosts_head, hosts_tail, rc); 1144 GNUNET_CONTAINER_DLL_insert(hosts_head, hosts_tail, rc);
1139} 1145}
1140 1146
1141 1147
@@ -1146,7 +1152,7 @@ add_host (const char *hostname,
1146 * @param line_len number of bytes in @a line 1152 * @param line_len number of bytes in @a line
1147 */ 1153 */
1148static void 1154static void
1149extract_hosts (const char *line, size_t line_len) 1155extract_hosts(const char *line, size_t line_len)
1150{ 1156{
1151 const char *c; 1157 const char *c;
1152 struct in_addr v4; 1158 struct in_addr v4;
@@ -1155,33 +1161,33 @@ extract_hosts (const char *line, size_t line_len)
1155 char *tok; 1161 char *tok;
1156 1162
1157 /* ignore everything after '#' */ 1163 /* ignore everything after '#' */
1158 c = memrchr (line, (unsigned char) '#', line_len); 1164 c = memrchr(line, (unsigned char)'#', line_len);
1159 if (NULL != c) 1165 if (NULL != c)
1160 line_len = c - line; 1166 line_len = c - line;
1161 /* ignore leading whitespace */ 1167 /* ignore leading whitespace */
1162 while ((0 < line_len) && isspace ((unsigned char) *line)) 1168 while ((0 < line_len) && isspace((unsigned char)*line))
1163 { 1169 {
1164 line++; 1170 line++;
1165 line_len--; 1171 line_len--;
1166 } 1172 }
1167 tbuf = GNUNET_strndup (line, line_len); 1173 tbuf = GNUNET_strndup(line, line_len);
1168 tok = strtok (tbuf, " \t"); 1174 tok = strtok(tbuf, " \t");
1169 if (NULL == tok) 1175 if (NULL == tok)
1170 { 1176 {
1171 GNUNET_free (tbuf); 1177 GNUNET_free(tbuf);
1172 return; 1178 return;
1173 } 1179 }
1174 if (1 == inet_pton (AF_INET, tok, &v4)) 1180 if (1 == inet_pton(AF_INET, tok, &v4))
1175 { 1181 {
1176 while (NULL != (tok = strtok (NULL, " \t"))) 1182 while (NULL != (tok = strtok(NULL, " \t")))
1177 add_host (tok, GNUNET_DNSPARSER_TYPE_A, &v4, sizeof (struct in_addr)); 1183 add_host(tok, GNUNET_DNSPARSER_TYPE_A, &v4, sizeof(struct in_addr));
1178 } 1184 }
1179 else if (1 == inet_pton (AF_INET6, tok, &v6)) 1185 else if (1 == inet_pton(AF_INET6, tok, &v6))
1180 { 1186 {
1181 while (NULL != (tok = strtok (NULL, " \t"))) 1187 while (NULL != (tok = strtok(NULL, " \t")))
1182 add_host (tok, GNUNET_DNSPARSER_TYPE_AAAA, &v6, sizeof (struct in6_addr)); 1188 add_host(tok, GNUNET_DNSPARSER_TYPE_AAAA, &v6, sizeof(struct in6_addr));
1183 } 1189 }
1184 GNUNET_free (tbuf); 1190 GNUNET_free(tbuf);
1185} 1191}
1186 1192
1187 1193
@@ -1189,7 +1195,7 @@ extract_hosts (const char *line, size_t line_len)
1189 * Reads the list of hosts from /etc/hosts. 1195 * Reads the list of hosts from /etc/hosts.
1190 */ 1196 */
1191static void 1197static void
1192load_etc_hosts (void) 1198load_etc_hosts(void)
1193{ 1199{
1194 struct GNUNET_DISK_FileHandle *fh; 1200 struct GNUNET_DISK_FileHandle *fh;
1195 struct GNUNET_DISK_MapHandle *mh; 1201 struct GNUNET_DISK_MapHandle *mh;
@@ -1197,49 +1203,49 @@ load_etc_hosts (void)
1197 const char *buf; 1203 const char *buf;
1198 size_t read_offset; 1204 size_t read_offset;
1199 1205
1200 fh = GNUNET_DISK_file_open ("/etc/hosts", 1206 fh = GNUNET_DISK_file_open("/etc/hosts",
1201 GNUNET_DISK_OPEN_READ, 1207 GNUNET_DISK_OPEN_READ,
1202 GNUNET_DISK_PERM_NONE); 1208 GNUNET_DISK_PERM_NONE);
1203 if (NULL == fh) 1209 if (NULL == fh)
1204 { 1210 {
1205 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Failed to open /etc/hosts"); 1211 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Failed to open /etc/hosts");
1206 return; 1212 return;
1207 } 1213 }
1208 if (GNUNET_OK != GNUNET_DISK_file_handle_size (fh, &bytes_read)) 1214 if (GNUNET_OK != GNUNET_DISK_file_handle_size(fh, &bytes_read))
1209 { 1215 {
1210 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 1216 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1211 "Could not determin size of /etc/hosts. " 1217 "Could not determin size of /etc/hosts. "
1212 "DNS resolution will not be possible.\n"); 1218 "DNS resolution will not be possible.\n");
1213 GNUNET_DISK_file_close (fh); 1219 GNUNET_DISK_file_close(fh);
1214 return; 1220 return;
1215 } 1221 }
1216 if (((unsigned long long) bytes_read) > (unsigned long long) SIZE_MAX) 1222 if (((unsigned long long)bytes_read) > (unsigned long long)SIZE_MAX)
1217 { 1223 {
1218 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 1224 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1219 "/etc/hosts file too large to mmap. " 1225 "/etc/hosts file too large to mmap. "
1220 "DNS resolution will not be possible.\n"); 1226 "DNS resolution will not be possible.\n");
1221 GNUNET_DISK_file_close (fh); 1227 GNUNET_DISK_file_close(fh);
1222 return; 1228 return;
1223 } 1229 }
1224 buf = GNUNET_DISK_file_map (fh, 1230 buf = GNUNET_DISK_file_map(fh,
1225 &mh, 1231 &mh,
1226 GNUNET_DISK_MAP_TYPE_READ, 1232 GNUNET_DISK_MAP_TYPE_READ,
1227 (size_t) bytes_read); 1233 (size_t)bytes_read);
1228 read_offset = 0; 1234 read_offset = 0;
1229 while (read_offset < (size_t) bytes_read) 1235 while (read_offset < (size_t)bytes_read)
1230 { 1236 {
1231 const char *newline; 1237 const char *newline;
1232 size_t line_len; 1238 size_t line_len;
1233 1239
1234 newline = strchr (buf + read_offset, '\n'); 1240 newline = strchr(buf + read_offset, '\n');
1235 if (NULL == newline) 1241 if (NULL == newline)
1236 break; 1242 break;
1237 line_len = newline - buf - read_offset; 1243 line_len = newline - buf - read_offset;
1238 extract_hosts (buf + read_offset, line_len); 1244 extract_hosts(buf + read_offset, line_len);
1239 read_offset += line_len + 1; 1245 read_offset += line_len + 1;
1240 } 1246 }
1241 GNUNET_DISK_file_unmap (mh); 1247 GNUNET_DISK_file_unmap(mh);
1242 GNUNET_DISK_file_close (fh); 1248 GNUNET_DISK_file_close(fh);
1243} 1249}
1244 1250
1245 1251
@@ -1251,37 +1257,37 @@ load_etc_hosts (void)
1251 * @param sh service handle 1257 * @param sh service handle
1252 */ 1258 */
1253static void 1259static void
1254init_cb (void *cls, 1260init_cb(void *cls,
1255 const struct GNUNET_CONFIGURATION_Handle *cfg, 1261 const struct GNUNET_CONFIGURATION_Handle *cfg,
1256 struct GNUNET_SERVICE_Handle *sh) 1262 struct GNUNET_SERVICE_Handle *sh)
1257{ 1263{
1258 char **dns_servers; 1264 char **dns_servers;
1259 int num_dns_servers; 1265 int num_dns_servers;
1260 1266
1261 (void) cfg; 1267 (void)cfg;
1262 (void) sh; 1268 (void)sh;
1263 load_etc_hosts (); 1269 load_etc_hosts();
1264 GNUNET_SCHEDULER_add_shutdown (&shutdown_task, cls); 1270 GNUNET_SCHEDULER_add_shutdown(&shutdown_task, cls);
1265 dnsstub_ctx = GNUNET_DNSSTUB_start (128); 1271 dnsstub_ctx = GNUNET_DNSSTUB_start(128);
1266 dns_servers = NULL; 1272 dns_servers = NULL;
1267 num_dns_servers = lookup_dns_servers (&dns_servers); 1273 num_dns_servers = lookup_dns_servers(&dns_servers);
1268 if (0 >= num_dns_servers) 1274 if (0 >= num_dns_servers)
1269 { 1275 {
1270 GNUNET_log ( 1276 GNUNET_log(
1271 GNUNET_ERROR_TYPE_ERROR, 1277 GNUNET_ERROR_TYPE_ERROR,
1272 _ ("No DNS server available. DNS resolution will not be possible.\n")); 1278 _("No DNS server available. DNS resolution will not be possible.\n"));
1273 return; 1279 return;
1274 } 1280 }
1275 for (int i = 0; i < num_dns_servers; i++) 1281 for (int i = 0; i < num_dns_servers; i++)
1276 { 1282 {
1277 int result = GNUNET_DNSSTUB_add_dns_ip (dnsstub_ctx, dns_servers[i]); 1283 int result = GNUNET_DNSSTUB_add_dns_ip(dnsstub_ctx, dns_servers[i]);
1278 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 1284 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
1279 "Adding DNS server '%s': %s\n", 1285 "Adding DNS server '%s': %s\n",
1280 dns_servers[i], 1286 dns_servers[i],
1281 GNUNET_OK == result ? "success" : "failure"); 1287 GNUNET_OK == result ? "success" : "failure");
1282 GNUNET_free (dns_servers[i]); 1288 GNUNET_free(dns_servers[i]);
1283 } 1289 }
1284 GNUNET_free_non_null (dns_servers); 1290 GNUNET_free_non_null(dns_servers);
1285} 1291}
1286 1292
1287 1293
@@ -1294,12 +1300,12 @@ init_cb (void *cls,
1294 * @return @a c 1300 * @return @a c
1295 */ 1301 */
1296static void * 1302static void *
1297connect_cb (void *cls, 1303connect_cb(void *cls,
1298 struct GNUNET_SERVICE_Client *c, 1304 struct GNUNET_SERVICE_Client *c,
1299 struct GNUNET_MQ_Handle *mq) 1305 struct GNUNET_MQ_Handle *mq)
1300{ 1306{
1301 (void) cls; 1307 (void)cls;
1302 (void) mq; 1308 (void)mq;
1303 1309
1304 return c; 1310 return c;
1305} 1311}
@@ -1313,37 +1319,38 @@ connect_cb (void *cls,
1313 * @param internal_cls should be equal to @a c 1319 * @param internal_cls should be equal to @a c
1314 */ 1320 */
1315static void 1321static void
1316disconnect_cb (void *cls, struct GNUNET_SERVICE_Client *c, void *internal_cls) 1322disconnect_cb(void *cls, struct GNUNET_SERVICE_Client *c, void *internal_cls)
1317{ 1323{
1318 struct ActiveLookup *n; 1324 struct ActiveLookup *n;
1319 (void) cls;
1320 1325
1321 GNUNET_assert (c == internal_cls); 1326 (void)cls;
1327
1328 GNUNET_assert(c == internal_cls);
1322 n = lookup_head; 1329 n = lookup_head;
1323 for (struct ActiveLookup *al = n; NULL != al; al = n) 1330 for (struct ActiveLookup *al = n; NULL != al; al = n)
1324 { 1331 {
1325 n = al->next; 1332 n = al->next;
1326 if (al->client == c) 1333 if (al->client == c)
1327 free_active_lookup (al); 1334 free_active_lookup(al);
1328 } 1335 }
1329} 1336}
1330 1337
1331 1338
1332/** 1339/**
1333 * Define "main" method using service macro. 1340 * Define "main" method using service macro.
1334 */ 1341 */
1335GNUNET_SERVICE_MAIN ( 1342GNUNET_SERVICE_MAIN(
1336 "resolver", 1343 "resolver",
1337 GNUNET_SERVICE_OPTION_NONE, 1344 GNUNET_SERVICE_OPTION_NONE,
1338 &init_cb, 1345 &init_cb,
1339 &connect_cb, 1346 &connect_cb,
1340 &disconnect_cb, 1347 &disconnect_cb,
1341 NULL, 1348 NULL,
1342 GNUNET_MQ_hd_var_size (get, 1349 GNUNET_MQ_hd_var_size(get,
1343 GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST, 1350 GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST,
1344 struct GNUNET_RESOLVER_GetMessage, 1351 struct GNUNET_RESOLVER_GetMessage,
1345 NULL), 1352 NULL),
1346 GNUNET_MQ_handler_end ()); 1353 GNUNET_MQ_handler_end());
1347 1354
1348 1355
1349#if defined(LINUX) && defined(__GLIBC__) 1356#if defined(LINUX) && defined(__GLIBC__)
@@ -1352,11 +1359,11 @@ GNUNET_SERVICE_MAIN (
1352/** 1359/**
1353 * MINIMIZE heap size (way below 128k) since this process doesn't need much. 1360 * MINIMIZE heap size (way below 128k) since this process doesn't need much.
1354 */ 1361 */
1355void __attribute__ ((constructor)) GNUNET_RESOLVER_memory_init () 1362void __attribute__ ((constructor)) GNUNET_RESOLVER_memory_init()
1356{ 1363{
1357 mallopt (M_TRIM_THRESHOLD, 4 * 1024); 1364 mallopt(M_TRIM_THRESHOLD, 4 * 1024);
1358 mallopt (M_TOP_PAD, 1 * 1024); 1365 mallopt(M_TOP_PAD, 1 * 1024);
1359 malloc_trim (0); 1366 malloc_trim(0);
1360} 1367}
1361#endif 1368#endif
1362 1369
diff --git a/src/util/gnunet-timeout-w32.c b/src/util/gnunet-timeout-w32.c
index 6f92b172f..3e579714c 100644
--- a/src/util/gnunet-timeout-w32.c
+++ b/src/util/gnunet-timeout-w32.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/gnunet-timeout-w32.c 22 * @file src/util/gnunet-timeout-w32.c
@@ -29,7 +29,7 @@
29#include <stdio.h> 29#include <stdio.h>
30 30
31int 31int
32main (int argc, char *argv[]) 32main(int argc, char *argv[])
33{ 33{
34 int i; 34 int i;
35 DWORD wait_result; 35 DWORD wait_result;
@@ -56,138 +56,138 @@ main (int argc, char *argv[])
56 if (argc < 3) 56 if (argc < 3)
57 { 57 {
58 printf 58 printf
59 ("arg 1: timeout in sec., arg 2: executable, arg<n> arguments\n"); 59 ("arg 1: timeout in sec., arg 2: executable, arg<n> arguments\n");
60 exit (1); 60 exit(1);
61 } 61 }
62 62
63 timeout = atoi (argv[1]); 63 timeout = atoi(argv[1]);
64 64
65 if (timeout == 0) 65 if (timeout == 0)
66 timeout = 600; 66 timeout = 600;
67 67
68 commandline = GetCommandLineW (); 68 commandline = GetCommandLineW();
69 if (commandline == NULL) 69 if (commandline == NULL)
70 { 70 {
71 printf ("Failed to get commandline: %lu\n", GetLastError ()); 71 printf("Failed to get commandline: %lu\n", GetLastError());
72 exit (2); 72 exit(2);
73 } 73 }
74 74
75 wargv = CommandLineToArgvW (commandline, &wargc); 75 wargv = CommandLineToArgvW(commandline, &wargc);
76 if (wargv == NULL || wargc <= 1) 76 if (wargv == NULL || wargc <= 1)
77 { 77 {
78 printf ("Failed to get parse commandline: %lu\n", GetLastError ()); 78 printf("Failed to get parse commandline: %lu\n", GetLastError());
79 exit (3); 79 exit(3);
80 } 80 }
81 81
82 job = CreateJobObject (NULL, NULL); 82 job = CreateJobObject(NULL, NULL);
83 if (job == NULL) 83 if (job == NULL)
84 { 84 {
85 printf ("Failed to create a job: %lu\n", GetLastError ()); 85 printf("Failed to create a job: %lu\n", GetLastError());
86 exit (4); 86 exit(4);
87 } 87 }
88 88
89 pathbuf_len = GetEnvironmentVariableW (L"PATH", (wchar_t *) &pathbuf, 0); 89 pathbuf_len = GetEnvironmentVariableW(L"PATH", (wchar_t *)&pathbuf, 0);
90 90
91 alloc_len = pathbuf_len + 1; 91 alloc_len = pathbuf_len + 1;
92 92
93 pathbuf = malloc (alloc_len * sizeof (wchar_t)); 93 pathbuf = malloc(alloc_len * sizeof(wchar_t));
94 94
95 ptr = pathbuf; 95 ptr = pathbuf;
96 96
97 alloc_len = GetEnvironmentVariableW (L"PATH", ptr, pathbuf_len); 97 alloc_len = GetEnvironmentVariableW(L"PATH", ptr, pathbuf_len);
98 98
99 cmdlen = wcslen (wargv[2]); 99 cmdlen = wcslen(wargv[2]);
100 if (cmdlen < 5 || wcscmp (&wargv[2][cmdlen - 4], L".exe") != 0) 100 if (cmdlen < 5 || wcscmp(&wargv[2][cmdlen - 4], L".exe") != 0)
101 { 101 {
102 non_const_filename = malloc (sizeof (wchar_t) * (cmdlen + 5)); 102 non_const_filename = malloc(sizeof(wchar_t) * (cmdlen + 5));
103 swprintf (non_const_filename, cmdlen + 5, L"%S.exe", wargv[2]); 103 swprintf(non_const_filename, cmdlen + 5, L"%S.exe", wargv[2]);
104 } 104 }
105 else 105 else
106 { 106 {
107 non_const_filename = wcsdup (wargv[2]); 107 non_const_filename = wcsdup(wargv[2]);
108 } 108 }
109 109
110 /* Check that this is the full path. If it isn't, search. */ 110 /* Check that this is the full path. If it isn't, search. */
111 if (non_const_filename[1] == L':') 111 if (non_const_filename[1] == L':')
112 swprintf (wpath, sizeof (wpath) / sizeof (wchar_t), L"%S", non_const_filename); 112 swprintf(wpath, sizeof(wpath) / sizeof(wchar_t), L"%S", non_const_filename);
113 else if (!SearchPathW 113 else if (!SearchPathW
114 (pathbuf, non_const_filename, NULL, sizeof (wpath) / sizeof (wchar_t), 114 (pathbuf, non_const_filename, NULL, sizeof(wpath) / sizeof(wchar_t),
115 wpath, NULL)) 115 wpath, NULL))
116 { 116 {
117 printf ("Failed to get find executable: %lu\n", GetLastError ()); 117 printf("Failed to get find executable: %lu\n", GetLastError());
118 exit (5); 118 exit(5);
119 } 119 }
120 free (pathbuf); 120 free(pathbuf);
121 free (non_const_filename); 121 free(non_const_filename);
122 122
123 cmdlen = wcslen (wpath) + 4; 123 cmdlen = wcslen(wpath) + 4;
124 i = 3; 124 i = 3;
125 while (NULL != (arg = wargv[i++])) 125 while (NULL != (arg = wargv[i++]))
126 cmdlen += wcslen (arg) + 4; 126 cmdlen += wcslen(arg) + 4;
127 127
128 wcmd = malloc (sizeof (wchar_t) * (cmdlen + 1)); 128 wcmd = malloc(sizeof(wchar_t) * (cmdlen + 1));
129 wrote = 0; 129 wrote = 0;
130 i = 2; 130 i = 2;
131 while (NULL != (arg = wargv[i++])) 131 while (NULL != (arg = wargv[i++]))
132 {
133 /* This is to escape trailing slash */
134 wchar_t arg_lastchar = arg[wcslen (arg) - 1];
135 if (wrote == 0)
136 { 132 {
137 wrote += swprintf (&wcmd[wrote], cmdlen + 1 - wrote, L"\"%S%S\" ", wpath, 133 /* This is to escape trailing slash */
138 arg_lastchar == L'\\' ? L"\\" : L""); 134 wchar_t arg_lastchar = arg[wcslen(arg) - 1];
139 } 135 if (wrote == 0)
140 else 136 {
141 { 137 wrote += swprintf(&wcmd[wrote], cmdlen + 1 - wrote, L"\"%S%S\" ", wpath,
142 if (wcschr (arg, L' ') != NULL) 138 arg_lastchar == L'\\' ? L"\\" : L"");
143 wrote += swprintf (&wcmd[wrote], cmdlen + 1 - wrote, L"\"%S%S\"%S", arg, 139 }
144 arg_lastchar == L'\\' ? L"\\" : L"", i == wargc ? L"" : L" ");
145 else 140 else
146 wrote += swprintf (&wcmd[wrote], cmdlen + 1 - wrote, L"%S%S%S", arg, 141 {
147 arg_lastchar == L'\\' ? L"\\" : L"", i == wargc ? L"" : L" "); 142 if (wcschr(arg, L' ') != NULL)
143 wrote += swprintf(&wcmd[wrote], cmdlen + 1 - wrote, L"\"%S%S\"%S", arg,
144 arg_lastchar == L'\\' ? L"\\" : L"", i == wargc ? L"" : L" ");
145 else
146 wrote += swprintf(&wcmd[wrote], cmdlen + 1 - wrote, L"%S%S%S", arg,
147 arg_lastchar == L'\\' ? L"\\" : L"", i == wargc ? L"" : L" ");
148 }
148 } 149 }
149 }
150 150
151 LocalFree (wargv); 151 LocalFree(wargv);
152 152
153 memset (&start, 0, sizeof (start)); 153 memset(&start, 0, sizeof(start));
154 start.cb = sizeof (start); 154 start.cb = sizeof(start);
155 155
156 if (!CreateProcessW (wpath, wcmd, NULL, NULL, TRUE, CREATE_SUSPENDED, 156 if (!CreateProcessW(wpath, wcmd, NULL, NULL, TRUE, CREATE_SUSPENDED,
157 NULL, NULL, &start, &proc)) 157 NULL, NULL, &start, &proc))
158 { 158 {
159 wprintf (L"Failed to get spawn process `%S' with arguments `%S': %lu\n", wpath, wcmd, GetLastError ()); 159 wprintf(L"Failed to get spawn process `%S' with arguments `%S': %lu\n", wpath, wcmd, GetLastError());
160 exit (6); 160 exit(6);
161 } 161 }
162 162
163 AssignProcessToJobObject (job, proc.hProcess); 163 AssignProcessToJobObject(job, proc.hProcess);
164 164
165 ResumeThread (proc.hThread); 165 ResumeThread(proc.hThread);
166 CloseHandle (proc.hThread); 166 CloseHandle(proc.hThread);
167 167
168 free (wcmd); 168 free(wcmd);
169 169
170 wait_result = WaitForSingleObject (proc.hProcess, timeout * 1000); 170 wait_result = WaitForSingleObject(proc.hProcess, timeout * 1000);
171 if (wait_result == WAIT_OBJECT_0) 171 if (wait_result == WAIT_OBJECT_0)
172 {
173 DWORD status;
174 wait_result = GetExitCodeProcess (proc.hProcess, &status);
175 CloseHandle (proc.hProcess);
176 if (wait_result != 0)
177 { 172 {
178 printf ("Test process exited with result %lu\n", status); 173 DWORD status;
179 TerminateJobObject (job, status); 174 wait_result = GetExitCodeProcess(proc.hProcess, &status);
180 exit (status); 175 CloseHandle(proc.hProcess);
176 if (wait_result != 0)
177 {
178 printf("Test process exited with result %lu\n", status);
179 TerminateJobObject(job, status);
180 exit(status);
181 }
182 printf("Test process exited (failed to obtain exit status)\n");
183 TerminateJobObject(job, 0);
184 exit(0);
181 } 185 }
182 printf ("Test process exited (failed to obtain exit status)\n"); 186 printf("Child processes were killed after timeout of %u seconds\n",
183 TerminateJobObject (job, 0); 187 timeout);
184 exit (0); 188 TerminateJobObject(job, 1);
185 } 189 CloseHandle(proc.hProcess);
186 printf ("Child processes were killed after timeout of %u seconds\n", 190 exit(1);
187 timeout);
188 TerminateJobObject (job, 1);
189 CloseHandle (proc.hProcess);
190 exit (1);
191} 191}
192 192
193/* end of timeout_watchdog_w32.c */ 193/* end of timeout_watchdog_w32.c */
diff --git a/src/util/gnunet-timeout.c b/src/util/gnunet-timeout.c
index d71b66af4..2b1754a5e 100644
--- a/src/util/gnunet-timeout.c
+++ b/src/util/gnunet-timeout.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/gnunet-timeout.c 22 * @file src/util/gnunet-timeout.c
@@ -35,85 +35,85 @@ static pid_t child;
35 35
36 36
37static void 37static void
38sigchld_handler (int val) 38sigchld_handler(int val)
39{ 39{
40 int status = 0; 40 int status = 0;
41 int ret = 0; 41 int ret = 0;
42 42
43 (void) val; 43 (void)val;
44 waitpid (child, &status, 0); 44 waitpid(child, &status, 0);
45 if (WIFEXITED (status) != 0) 45 if (WIFEXITED(status) != 0)
46 { 46 {
47 ret = WEXITSTATUS (status); 47 ret = WEXITSTATUS(status);
48 fprintf (stderr, "Process exited with result %u\n", ret); 48 fprintf(stderr, "Process exited with result %u\n", ret);
49 _exit (ret); /* return same status code */ 49 _exit(ret); /* return same status code */
50 } 50 }
51 if (WIFSIGNALED (status) != 0) 51 if (WIFSIGNALED(status) != 0)
52 { 52 {
53 ret = WTERMSIG (status); 53 ret = WTERMSIG(status);
54 fprintf (stderr, "Process received signal %u\n", ret); 54 fprintf(stderr, "Process received signal %u\n", ret);
55 kill (getpid (), ret); /* kill self with the same signal */ 55 kill(getpid(), ret); /* kill self with the same signal */
56 } 56 }
57 _exit (-1); 57 _exit(-1);
58} 58}
59 59
60 60
61static void 61static void
62sigint_handler (int val) 62sigint_handler(int val)
63{ 63{
64 kill (0, val); 64 kill(0, val);
65 _exit (val); 65 _exit(val);
66} 66}
67 67
68 68
69int 69int
70main (int argc, char *argv[]) 70main(int argc, char *argv[])
71{ 71{
72 int timeout = 0; 72 int timeout = 0;
73 pid_t gpid = 0; 73 pid_t gpid = 0;
74 74
75 if (argc < 3) 75 if (argc < 3)
76 { 76 {
77 fprintf (stderr, 77 fprintf(stderr,
78 "arg 1: timeout in sec., arg 2: executable, arg<n> arguments\n"); 78 "arg 1: timeout in sec., arg 2: executable, arg<n> arguments\n");
79 exit (-1); 79 exit(-1);
80 } 80 }
81 81
82 timeout = atoi (argv[1]); 82 timeout = atoi(argv[1]);
83 83
84 if (timeout == 0) 84 if (timeout == 0)
85 timeout = 600; 85 timeout = 600;
86 86
87 /* with getpgid() it does not compile, but getpgrp is the BSD version and working */ 87 /* with getpgid() it does not compile, but getpgrp is the BSD version and working */
88 gpid = getpgrp (); 88 gpid = getpgrp();
89 89
90 signal (SIGCHLD, sigchld_handler); 90 signal(SIGCHLD, sigchld_handler);
91 signal (SIGABRT, sigint_handler); 91 signal(SIGABRT, sigint_handler);
92 signal (SIGFPE, sigint_handler); 92 signal(SIGFPE, sigint_handler);
93 signal (SIGILL, sigint_handler); 93 signal(SIGILL, sigint_handler);
94 signal (SIGINT, sigint_handler); 94 signal(SIGINT, sigint_handler);
95 signal (SIGSEGV, sigint_handler); 95 signal(SIGSEGV, sigint_handler);
96 signal (SIGTERM, sigint_handler); 96 signal(SIGTERM, sigint_handler);
97 97
98 child = fork (); 98 child = fork();
99 if (child == 0) 99 if (child == 0)
100 { 100 {
101 /* int setpgrp(pid_t pid, pid_t pgid); is not working on this machine */ 101 /* int setpgrp(pid_t pid, pid_t pgid); is not working on this machine */
102 //setpgrp (0, pid_t gpid); 102 //setpgrp (0, pid_t gpid);
103 if (-1 != gpid) 103 if (-1 != gpid)
104 setpgid (0, gpid); 104 setpgid(0, gpid);
105 execvp (argv[2], &argv[2]); 105 execvp(argv[2], &argv[2]);
106 exit (-1); 106 exit(-1);
107 } 107 }
108 if (child > 0) 108 if (child > 0)
109 { 109 {
110 sleep (timeout); 110 sleep(timeout);
111 printf ("Child processes were killed after timeout of %u seconds\n", 111 printf("Child processes were killed after timeout of %u seconds\n",
112 timeout); 112 timeout);
113 kill (0, SIGTERM); 113 kill(0, SIGTERM);
114 exit (3); 114 exit(3);
115 } 115 }
116 exit (-1); 116 exit(-1);
117} 117}
118 118
119/* end of timeout_watchdog.c */ 119/* end of timeout_watchdog.c */
diff --git a/src/util/gnunet-uri.c b/src/util/gnunet-uri.c
index 33ff7b1e6..75667b30f 100644
--- a/src/util/gnunet-uri.c
+++ b/src/util/gnunet-uri.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/gnunet-uri.c 22 * @file util/gnunet-uri.c
@@ -49,15 +49,15 @@ static struct GNUNET_DISK_PipeHandle *sigpipe;
49 * @param cls closure, NULL 49 * @param cls closure, NULL
50 */ 50 */
51static void 51static void
52maint_child_death (void *cls) 52maint_child_death(void *cls)
53{ 53{
54 enum GNUNET_OS_ProcessStatusType type; 54 enum GNUNET_OS_ProcessStatusType type;
55 55
56 (void) cls; 56 (void)cls;
57 if ((GNUNET_OK != GNUNET_OS_process_status (p, &type, &exit_code)) || 57 if ((GNUNET_OK != GNUNET_OS_process_status(p, &type, &exit_code)) ||
58 (type != GNUNET_OS_PROCESS_EXITED)) 58 (type != GNUNET_OS_PROCESS_EXITED))
59 GNUNET_break (0 == GNUNET_OS_process_kill (p, GNUNET_TERM_SIG)); 59 GNUNET_break(0 == GNUNET_OS_process_kill(p, GNUNET_TERM_SIG));
60 GNUNET_OS_process_destroy (p); 60 GNUNET_OS_process_destroy(p);
61} 61}
62 62
63 63
@@ -70,10 +70,10 @@ maint_child_death (void *cls)
70 * @param cfg configuration 70 * @param cfg configuration
71 */ 71 */
72static void 72static void
73run (void *cls, 73run(void *cls,
74 char *const *args, 74 char *const *args,
75 const char *cfgfile, 75 const char *cfgfile,
76 const struct GNUNET_CONFIGURATION_Handle *cfg) 76 const struct GNUNET_CONFIGURATION_Handle *cfg)
77{ 77{
78 const char *uri; 78 const char *uri;
79 const char *slash; 79 const char *slash;
@@ -81,52 +81,52 @@ run (void *cls,
81 char *program; 81 char *program;
82 struct GNUNET_SCHEDULER_Task *rt; 82 struct GNUNET_SCHEDULER_Task *rt;
83 83
84 (void) cls; 84 (void)cls;
85 (void) cfgfile; 85 (void)cfgfile;
86 if (NULL == (uri = args[0])) 86 if (NULL == (uri = args[0]))
87 { 87 {
88 fprintf (stderr, _ ("No URI specified on command line\n")); 88 fprintf(stderr, _("No URI specified on command line\n"));
89 return; 89 return;
90 } 90 }
91 if (0 != strncasecmp ("gnunet://", uri, strlen ("gnunet://"))) 91 if (0 != strncasecmp("gnunet://", uri, strlen("gnunet://")))
92 { 92 {
93 fprintf (stderr, 93 fprintf(stderr,
94 _ ("Invalid URI: does not start with `%s'\n"), 94 _("Invalid URI: does not start with `%s'\n"),
95 "gnunet://"); 95 "gnunet://");
96 return; 96 return;
97 } 97 }
98 uri += strlen ("gnunet://"); 98 uri += strlen("gnunet://");
99 if (NULL == (slash = strchr (uri, '/'))) 99 if (NULL == (slash = strchr(uri, '/')))
100 { 100 {
101 fprintf (stderr, _ ("Invalid URI: fails to specify subsystem\n")); 101 fprintf(stderr, _("Invalid URI: fails to specify subsystem\n"));
102 return; 102 return;
103 } 103 }
104 subsystem = GNUNET_strndup (uri, slash - uri); 104 subsystem = GNUNET_strndup(uri, slash - uri);
105 if (GNUNET_OK != 105 if (GNUNET_OK !=
106 GNUNET_CONFIGURATION_get_value_string (cfg, "uri", subsystem, &program)) 106 GNUNET_CONFIGURATION_get_value_string(cfg, "uri", subsystem, &program))
107 { 107 {
108 fprintf (stderr, _ ("No handler known for subsystem `%s'\n"), subsystem); 108 fprintf(stderr, _("No handler known for subsystem `%s'\n"), subsystem);
109 GNUNET_free (subsystem); 109 GNUNET_free(subsystem);
110 return; 110 return;
111 } 111 }
112 GNUNET_free (subsystem); 112 GNUNET_free(subsystem);
113 rt = GNUNET_SCHEDULER_add_read_file ( 113 rt = GNUNET_SCHEDULER_add_read_file(
114 GNUNET_TIME_UNIT_FOREVER_REL, 114 GNUNET_TIME_UNIT_FOREVER_REL,
115 GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ), 115 GNUNET_DISK_pipe_handle(sigpipe, GNUNET_DISK_PIPE_END_READ),
116 &maint_child_death, 116 &maint_child_death,
117 NULL); 117 NULL);
118 p = GNUNET_OS_start_process (GNUNET_NO, 118 p = GNUNET_OS_start_process(GNUNET_NO,
119 0, 119 0,
120 NULL, 120 NULL,
121 NULL, 121 NULL,
122 NULL, 122 NULL,
123 program, 123 program,
124 program, 124 program,
125 args[0], 125 args[0],
126 NULL); 126 NULL);
127 GNUNET_free (program); 127 GNUNET_free(program);
128 if (NULL == p) 128 if (NULL == p)
129 GNUNET_SCHEDULER_cancel (rt); 129 GNUNET_SCHEDULER_cancel(rt);
130} 130}
131 131
132 132
@@ -135,17 +135,17 @@ run (void *cls,
135 * respective handler by writing to the trigger pipe. 135 * respective handler by writing to the trigger pipe.
136 */ 136 */
137static void 137static void
138sighandler_child_death () 138sighandler_child_death()
139{ 139{
140 static char c; 140 static char c;
141 int old_errno = errno; /* back-up errno */ 141 int old_errno = errno; /* back-up errno */
142 142
143 GNUNET_break ( 143 GNUNET_break(
144 1 == 144 1 ==
145 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle (sigpipe, 145 GNUNET_DISK_file_write(GNUNET_DISK_pipe_handle(sigpipe,
146 GNUNET_DISK_PIPE_END_WRITE), 146 GNUNET_DISK_PIPE_END_WRITE),
147 &c, 147 &c,
148 sizeof (c))); 148 sizeof(c)));
149 errno = old_errno; /* restore errno */ 149 errno = old_errno; /* restore errno */
150} 150}
151 151
@@ -158,32 +158,33 @@ sighandler_child_death ()
158 * @return 0 ok, 1 on error 158 * @return 0 ok, 1 on error
159 */ 159 */
160int 160int
161main (int argc, char *const *argv) 161main(int argc, char *const *argv)
162{ 162{
163 static const struct GNUNET_GETOPT_CommandLineOption options[] = { 163 static const struct GNUNET_GETOPT_CommandLineOption options[] = {
164 GNUNET_GETOPT_OPTION_END}; 164 GNUNET_GETOPT_OPTION_END
165 };
165 struct GNUNET_SIGNAL_Context *shc_chld; 166 struct GNUNET_SIGNAL_Context *shc_chld;
166 int ret; 167 int ret;
167 168
168 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args (argc, argv, &argc, &argv)) 169 if (GNUNET_OK != GNUNET_STRINGS_get_utf8_args(argc, argv, &argc, &argv))
169 return 2; 170 return 2;
170 sigpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); 171 sigpipe = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
171 GNUNET_assert (sigpipe != NULL); 172 GNUNET_assert(sigpipe != NULL);
172 shc_chld = 173 shc_chld =
173 GNUNET_SIGNAL_handler_install (GNUNET_SIGCHLD, &sighandler_child_death); 174 GNUNET_SIGNAL_handler_install(GNUNET_SIGCHLD, &sighandler_child_death);
174 ret = GNUNET_PROGRAM_run (argc, 175 ret = GNUNET_PROGRAM_run(argc,
175 argv, 176 argv,
176 "gnunet-uri URI", 177 "gnunet-uri URI",
177 gettext_noop ( 178 gettext_noop(
178 "Perform default-actions for GNUnet URIs"), 179 "Perform default-actions for GNUnet URIs"),
179 options, 180 options,
180 &run, 181 &run,
181 NULL); 182 NULL);
182 GNUNET_SIGNAL_handler_uninstall (shc_chld); 183 GNUNET_SIGNAL_handler_uninstall(shc_chld);
183 shc_chld = NULL; 184 shc_chld = NULL;
184 GNUNET_DISK_pipe_close (sigpipe); 185 GNUNET_DISK_pipe_close(sigpipe);
185 sigpipe = NULL; 186 sigpipe = NULL;
186 GNUNET_free ((void *) argv); 187 GNUNET_free((void *)argv);
187 return ((GNUNET_OK == ret) && (0 == exit_code)) ? 0 : 1; 188 return ((GNUNET_OK == ret) && (0 == exit_code)) ? 0 : 1;
188} 189}
189 190
diff --git a/src/util/helper.c b/src/util/helper.c
index aa452d22b..f0892a485 100644
--- a/src/util/helper.c
+++ b/src/util/helper.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/helper.c 22 * @file util/helper.c
@@ -33,9 +33,7 @@
33/** 33/**
34 * Entry in the queue of messages we need to transmit to the helper. 34 * Entry in the queue of messages we need to transmit to the helper.
35 */ 35 */
36struct GNUNET_HELPER_SendHandle 36struct GNUNET_HELPER_SendHandle {
37{
38
39 /** 37 /**
40 * This is an entry in a DLL. 38 * This is an entry in a DLL.
41 */ 39 */
@@ -76,9 +74,7 @@ struct GNUNET_HELPER_SendHandle
76/** 74/**
77 * The handle to a helper process. 75 * The handle to a helper process.
78 */ 76 */
79struct GNUNET_HELPER_Handle 77struct GNUNET_HELPER_Handle {
80{
81
82 /** 78 /**
83 * PipeHandle to receive data from the helper 79 * PipeHandle to receive data from the helper
84 */ 80 */
@@ -176,40 +172,40 @@ struct GNUNET_HELPER_Handle
176 * @return #GNUNET_OK on success; #GNUNET_SYSERR on error 172 * @return #GNUNET_OK on success; #GNUNET_SYSERR on error
177 */ 173 */
178int 174int
179GNUNET_HELPER_kill (struct GNUNET_HELPER_Handle *h, int soft_kill) 175GNUNET_HELPER_kill(struct GNUNET_HELPER_Handle *h, int soft_kill)
180{ 176{
181 struct GNUNET_HELPER_SendHandle *sh; 177 struct GNUNET_HELPER_SendHandle *sh;
182 int ret; 178 int ret;
183 179
184 while (NULL != (sh = h->sh_head)) 180 while (NULL != (sh = h->sh_head))
185 { 181 {
186 GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh); 182 GNUNET_CONTAINER_DLL_remove(h->sh_head, h->sh_tail, sh);
187 if (NULL != sh->cont) 183 if (NULL != sh->cont)
188 sh->cont (sh->cont_cls, GNUNET_NO); 184 sh->cont(sh->cont_cls, GNUNET_NO);
189 GNUNET_free (sh); 185 GNUNET_free(sh);
190 } 186 }
191 if (NULL != h->restart_task) 187 if (NULL != h->restart_task)
192 { 188 {
193 GNUNET_SCHEDULER_cancel (h->restart_task); 189 GNUNET_SCHEDULER_cancel(h->restart_task);
194 h->restart_task = NULL; 190 h->restart_task = NULL;
195 } 191 }
196 if (NULL != h->read_task) 192 if (NULL != h->read_task)
197 { 193 {
198 GNUNET_SCHEDULER_cancel (h->read_task); 194 GNUNET_SCHEDULER_cancel(h->read_task);
199 h->read_task = NULL; 195 h->read_task = NULL;
200 } 196 }
201 if (NULL == h->helper_proc) 197 if (NULL == h->helper_proc)
202 return GNUNET_SYSERR; 198 return GNUNET_SYSERR;
203 if (GNUNET_YES == soft_kill) 199 if (GNUNET_YES == soft_kill)
204 { 200 {
205 /* soft-kill only possible with pipes */ 201 /* soft-kill only possible with pipes */
206 GNUNET_assert (NULL != h->helper_in); 202 GNUNET_assert(NULL != h->helper_in);
207 ret = GNUNET_DISK_pipe_close (h->helper_in); 203 ret = GNUNET_DISK_pipe_close(h->helper_in);
208 h->helper_in = NULL; 204 h->helper_in = NULL;
209 h->fh_to_helper = NULL; 205 h->fh_to_helper = NULL;
210 return ret; 206 return ret;
211 } 207 }
212 if (0 != GNUNET_OS_process_kill (h->helper_proc, GNUNET_TERM_SIG)) 208 if (0 != GNUNET_OS_process_kill(h->helper_proc, GNUNET_TERM_SIG))
213 return GNUNET_SYSERR; 209 return GNUNET_SYSERR;
214 return GNUNET_OK; 210 return GNUNET_OK;
215} 211}
@@ -224,50 +220,50 @@ GNUNET_HELPER_kill (struct GNUNET_HELPER_Handle *h, int soft_kill)
224 * @return #GNUNET_OK on success; #GNUNET_SYSERR on error 220 * @return #GNUNET_OK on success; #GNUNET_SYSERR on error
225 */ 221 */
226int 222int
227GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h) 223GNUNET_HELPER_wait(struct GNUNET_HELPER_Handle *h)
228{ 224{
229 struct GNUNET_HELPER_SendHandle *sh; 225 struct GNUNET_HELPER_SendHandle *sh;
230 int ret; 226 int ret;
231 227
232 ret = GNUNET_SYSERR; 228 ret = GNUNET_SYSERR;
233 if (NULL != h->helper_proc) 229 if (NULL != h->helper_proc)
234 { 230 {
235 ret = GNUNET_OS_process_wait (h->helper_proc); 231 ret = GNUNET_OS_process_wait(h->helper_proc);
236 GNUNET_OS_process_destroy (h->helper_proc); 232 GNUNET_OS_process_destroy(h->helper_proc);
237 h->helper_proc = NULL; 233 h->helper_proc = NULL;
238 } 234 }
239 if (NULL != h->read_task) 235 if (NULL != h->read_task)
240 { 236 {
241 GNUNET_SCHEDULER_cancel (h->read_task); 237 GNUNET_SCHEDULER_cancel(h->read_task);
242 h->read_task = NULL; 238 h->read_task = NULL;
243 } 239 }
244 if (NULL != h->write_task) 240 if (NULL != h->write_task)
245 { 241 {
246 GNUNET_SCHEDULER_cancel (h->write_task); 242 GNUNET_SCHEDULER_cancel(h->write_task);
247 h->write_task = NULL; 243 h->write_task = NULL;
248 } 244 }
249 if (NULL != h->helper_in) 245 if (NULL != h->helper_in)
250 { 246 {
251 GNUNET_DISK_pipe_close (h->helper_in); 247 GNUNET_DISK_pipe_close(h->helper_in);
252 h->helper_in = NULL; 248 h->helper_in = NULL;
253 h->fh_to_helper = NULL; 249 h->fh_to_helper = NULL;
254 } 250 }
255 if (NULL != h->helper_out) 251 if (NULL != h->helper_out)
256 { 252 {
257 GNUNET_DISK_pipe_close (h->helper_out); 253 GNUNET_DISK_pipe_close(h->helper_out);
258 h->helper_out = NULL; 254 h->helper_out = NULL;
259 h->fh_from_helper = NULL; 255 h->fh_from_helper = NULL;
260 } 256 }
261 while (NULL != (sh = h->sh_head)) 257 while (NULL != (sh = h->sh_head))
262 { 258 {
263 GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh); 259 GNUNET_CONTAINER_DLL_remove(h->sh_head, h->sh_tail, sh);
264 if (NULL != sh->cont) 260 if (NULL != sh->cont)
265 sh->cont (sh->cont_cls, GNUNET_NO); 261 sh->cont(sh->cont_cls, GNUNET_NO);
266 GNUNET_free (sh); 262 GNUNET_free(sh);
267 } 263 }
268 /* purge MST buffer */ 264 /* purge MST buffer */
269 if (NULL != h->mst) 265 if (NULL != h->mst)
270 (void) GNUNET_MST_from_buffer (h->mst, NULL, 0, GNUNET_YES, GNUNET_NO); 266 (void)GNUNET_MST_from_buffer(h->mst, NULL, 0, GNUNET_YES, GNUNET_NO);
271 return ret; 267 return ret;
272} 268}
273 269
@@ -280,18 +276,18 @@ GNUNET_HELPER_wait (struct GNUNET_HELPER_Handle *h)
280 * stdin; #GNUNET_NO to signal termination by sending SIGTERM to helper 276 * stdin; #GNUNET_NO to signal termination by sending SIGTERM to helper
281 */ 277 */
282static void 278static void
283stop_helper (struct GNUNET_HELPER_Handle *h, int soft_kill) 279stop_helper(struct GNUNET_HELPER_Handle *h, int soft_kill)
284{ 280{
285 if (NULL != h->restart_task) 281 if (NULL != h->restart_task)
286 { 282 {
287 GNUNET_SCHEDULER_cancel (h->restart_task); 283 GNUNET_SCHEDULER_cancel(h->restart_task);
288 h->restart_task = NULL; 284 h->restart_task = NULL;
289 } 285 }
290 else 286 else
291 { 287 {
292 GNUNET_break (GNUNET_OK == GNUNET_HELPER_kill (h, soft_kill)); 288 GNUNET_break(GNUNET_OK == GNUNET_HELPER_kill(h, soft_kill));
293 GNUNET_break (GNUNET_OK == GNUNET_HELPER_wait (h)); 289 GNUNET_break(GNUNET_OK == GNUNET_HELPER_wait(h));
294 } 290 }
295} 291}
296 292
297 293
@@ -301,7 +297,7 @@ stop_helper (struct GNUNET_HELPER_Handle *h, int soft_kill)
301 * @param cls handle to the helper process 297 * @param cls handle to the helper process
302 */ 298 */
303static void 299static void
304restart_task (void *cls); 300restart_task(void *cls);
305 301
306 302
307/** 303/**
@@ -310,87 +306,87 @@ restart_task (void *cls);
310 * @param cls handle to the helper process 306 * @param cls handle to the helper process
311 */ 307 */
312static void 308static void
313helper_read (void *cls) 309helper_read(void *cls)
314{ 310{
315 struct GNUNET_HELPER_Handle *h = cls; 311 struct GNUNET_HELPER_Handle *h = cls;
316 char buf[GNUNET_MAX_MESSAGE_SIZE] GNUNET_ALIGN; 312 char buf[GNUNET_MAX_MESSAGE_SIZE] GNUNET_ALIGN;
317 ssize_t t; 313 ssize_t t;
318 314
319 h->read_task = NULL; 315 h->read_task = NULL;
320 t = GNUNET_DISK_file_read (h->fh_from_helper, &buf, sizeof (buf)); 316 t = GNUNET_DISK_file_read(h->fh_from_helper, &buf, sizeof(buf));
321 if (t < 0) 317 if (t < 0)
322 {
323 /* On read-error, restart the helper */
324 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
325 _ ("Error reading from `%s': %s\n"),
326 h->binary_name,
327 strerror (errno));
328 if (NULL != h->exp_cb)
329 { 318 {
330 h->exp_cb (h->cb_cls); 319 /* On read-error, restart the helper */
331 GNUNET_HELPER_stop (h, GNUNET_NO); 320 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
321 _("Error reading from `%s': %s\n"),
322 h->binary_name,
323 strerror(errno));
324 if (NULL != h->exp_cb)
325 {
326 h->exp_cb(h->cb_cls);
327 GNUNET_HELPER_stop(h, GNUNET_NO);
328 return;
329 }
330 stop_helper(h, GNUNET_NO);
331 /* Restart the helper */
332 h->restart_task = GNUNET_SCHEDULER_add_delayed(
333 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
334 h->retry_back_off),
335 &restart_task,
336 h);
332 return; 337 return;
333 } 338 }
334 stop_helper (h, GNUNET_NO);
335 /* Restart the helper */
336 h->restart_task = GNUNET_SCHEDULER_add_delayed (
337 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
338 h->retry_back_off),
339 &restart_task,
340 h);
341 return;
342 }
343 if (0 == t) 339 if (0 == t)
344 {
345 /* this happens if the helper is shut down via a
346 signal, so it is not a "hard" error */
347 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
348 "Got 0 bytes from helper `%s' (EOF)\n",
349 h->binary_name);
350 if (NULL != h->exp_cb)
351 { 340 {
352 h->exp_cb (h->cb_cls); 341 /* this happens if the helper is shut down via a
353 GNUNET_HELPER_stop (h, GNUNET_NO); 342 signal, so it is not a "hard" error */
343 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
344 "Got 0 bytes from helper `%s' (EOF)\n",
345 h->binary_name);
346 if (NULL != h->exp_cb)
347 {
348 h->exp_cb(h->cb_cls);
349 GNUNET_HELPER_stop(h, GNUNET_NO);
350 return;
351 }
352 stop_helper(h, GNUNET_NO);
353 /* Restart the helper */
354 h->restart_task = GNUNET_SCHEDULER_add_delayed(
355 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
356 h->retry_back_off),
357 &restart_task,
358 h);
354 return; 359 return;
355 } 360 }
356 stop_helper (h, GNUNET_NO); 361 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
357 /* Restart the helper */ 362 "Got %u bytes from helper `%s'\n",
358 h->restart_task = GNUNET_SCHEDULER_add_delayed ( 363 (unsigned int)t,
359 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 364 h->binary_name);
360 h->retry_back_off), 365 h->read_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
361 &restart_task, 366 h->fh_from_helper,
362 h); 367 &helper_read,
363 return; 368 h);
364 }
365 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
366 "Got %u bytes from helper `%s'\n",
367 (unsigned int) t,
368 h->binary_name);
369 h->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL,
370 h->fh_from_helper,
371 &helper_read,
372 h);
373 if (GNUNET_SYSERR == 369 if (GNUNET_SYSERR ==
374 GNUNET_MST_from_buffer (h->mst, buf, t, GNUNET_NO, GNUNET_NO)) 370 GNUNET_MST_from_buffer(h->mst, buf, t, GNUNET_NO, GNUNET_NO))
375 {
376 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
377 _ ("Failed to parse inbound message from helper `%s'\n"),
378 h->binary_name);
379 if (NULL != h->exp_cb)
380 { 371 {
381 h->exp_cb (h->cb_cls); 372 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
382 GNUNET_HELPER_stop (h, GNUNET_NO); 373 _("Failed to parse inbound message from helper `%s'\n"),
374 h->binary_name);
375 if (NULL != h->exp_cb)
376 {
377 h->exp_cb(h->cb_cls);
378 GNUNET_HELPER_stop(h, GNUNET_NO);
379 return;
380 }
381 stop_helper(h, GNUNET_NO);
382 /* Restart the helper */
383 h->restart_task = GNUNET_SCHEDULER_add_delayed(
384 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
385 h->retry_back_off),
386 &restart_task,
387 h);
383 return; 388 return;
384 } 389 }
385 stop_helper (h, GNUNET_NO);
386 /* Restart the helper */
387 h->restart_task = GNUNET_SCHEDULER_add_delayed (
388 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
389 h->retry_back_off),
390 &restart_task,
391 h);
392 return;
393 }
394} 390}
395 391
396 392
@@ -400,55 +396,55 @@ helper_read (void *cls)
400 * @param h handle to the helper process 396 * @param h handle to the helper process
401 */ 397 */
402static void 398static void
403start_helper (struct GNUNET_HELPER_Handle *h) 399start_helper(struct GNUNET_HELPER_Handle *h)
404{ 400{
405 h->helper_in = 401 h->helper_in =
406 GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO); 402 GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
407 h->helper_out = 403 h->helper_out =
408 GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 404 GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
409 if ((h->helper_in == NULL) || (h->helper_out == NULL)) 405 if ((h->helper_in == NULL) || (h->helper_out == NULL))
410 { 406 {
411 /* out of file descriptors? try again later... */ 407 /* out of file descriptors? try again later... */
412 stop_helper (h, GNUNET_NO); 408 stop_helper(h, GNUNET_NO);
413 h->restart_task = GNUNET_SCHEDULER_add_delayed ( 409 h->restart_task = GNUNET_SCHEDULER_add_delayed(
414 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 410 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
415 h->retry_back_off), 411 h->retry_back_off),
416 &restart_task, 412 &restart_task,
417 h); 413 h);
418 return; 414 return;
419 } 415 }
420 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 416 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
421 "Starting HELPER process `%s'\n", 417 "Starting HELPER process `%s'\n",
422 h->binary_name); 418 h->binary_name);
423 h->fh_from_helper = 419 h->fh_from_helper =
424 GNUNET_DISK_pipe_handle (h->helper_out, GNUNET_DISK_PIPE_END_READ); 420 GNUNET_DISK_pipe_handle(h->helper_out, GNUNET_DISK_PIPE_END_READ);
425 h->fh_to_helper = 421 h->fh_to_helper =
426 GNUNET_DISK_pipe_handle (h->helper_in, GNUNET_DISK_PIPE_END_WRITE); 422 GNUNET_DISK_pipe_handle(h->helper_in, GNUNET_DISK_PIPE_END_WRITE);
427 h->helper_proc = GNUNET_OS_start_process_vap (h->with_control_pipe, 423 h->helper_proc = GNUNET_OS_start_process_vap(h->with_control_pipe,
428 GNUNET_OS_INHERIT_STD_ERR, 424 GNUNET_OS_INHERIT_STD_ERR,
429 h->helper_in, 425 h->helper_in,
430 h->helper_out, 426 h->helper_out,
431 NULL, 427 NULL,
432 h->binary_name, 428 h->binary_name,
433 h->binary_argv); 429 h->binary_argv);
434 if (NULL == h->helper_proc) 430 if (NULL == h->helper_proc)
435 { 431 {
436 /* failed to start process? try again later... */ 432 /* failed to start process? try again later... */
437 stop_helper (h, GNUNET_NO); 433 stop_helper(h, GNUNET_NO);
438 h->restart_task = GNUNET_SCHEDULER_add_delayed ( 434 h->restart_task = GNUNET_SCHEDULER_add_delayed(
439 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 435 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
440 h->retry_back_off), 436 h->retry_back_off),
441 &restart_task, 437 &restart_task,
442 h); 438 h);
443 return; 439 return;
444 } 440 }
445 GNUNET_DISK_pipe_close_end (h->helper_out, GNUNET_DISK_PIPE_END_WRITE); 441 GNUNET_DISK_pipe_close_end(h->helper_out, GNUNET_DISK_PIPE_END_WRITE);
446 GNUNET_DISK_pipe_close_end (h->helper_in, GNUNET_DISK_PIPE_END_READ); 442 GNUNET_DISK_pipe_close_end(h->helper_in, GNUNET_DISK_PIPE_END_READ);
447 if (NULL != h->mst) 443 if (NULL != h->mst)
448 h->read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 444 h->read_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
449 h->fh_from_helper, 445 h->fh_from_helper,
450 &helper_read, 446 &helper_read,
451 h); 447 h);
452} 448}
453 449
454 450
@@ -458,16 +454,16 @@ start_helper (struct GNUNET_HELPER_Handle *h)
458 * @param cls handle to the helper process 454 * @param cls handle to the helper process
459 */ 455 */
460static void 456static void
461restart_task (void *cls) 457restart_task(void *cls)
462{ 458{
463 struct GNUNET_HELPER_Handle *h = cls; 459 struct GNUNET_HELPER_Handle *h = cls;
464 460
465 h->restart_task = NULL; 461 h->restart_task = NULL;
466 h->retry_back_off++; 462 h->retry_back_off++;
467 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 463 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
468 "Restarting helper with back-off %u\n", 464 "Restarting helper with back-off %u\n",
469 h->retry_back_off); 465 h->retry_back_off);
470 start_helper (h); 466 start_helper(h);
471} 467}
472 468
473 469
@@ -488,35 +484,35 @@ restart_task (void *cls)
488 * @return the new Handle, NULL on error 484 * @return the new Handle, NULL on error
489 */ 485 */
490struct GNUNET_HELPER_Handle * 486struct GNUNET_HELPER_Handle *
491GNUNET_HELPER_start (int with_control_pipe, 487GNUNET_HELPER_start(int with_control_pipe,
492 const char *binary_name, 488 const char *binary_name,
493 char *const binary_argv[], 489 char *const binary_argv[],
494 GNUNET_MessageTokenizerCallback cb, 490 GNUNET_MessageTokenizerCallback cb,
495 GNUNET_HELPER_ExceptionCallback exp_cb, 491 GNUNET_HELPER_ExceptionCallback exp_cb,
496 void *cb_cls) 492 void *cb_cls)
497{ 493{
498 struct GNUNET_HELPER_Handle *h; 494 struct GNUNET_HELPER_Handle *h;
499 unsigned int c; 495 unsigned int c;
500 496
501 h = GNUNET_new (struct GNUNET_HELPER_Handle); 497 h = GNUNET_new(struct GNUNET_HELPER_Handle);
502 h->with_control_pipe = with_control_pipe; 498 h->with_control_pipe = with_control_pipe;
503 /* Lookup in libexec path only if we are starting gnunet helpers */ 499 /* Lookup in libexec path only if we are starting gnunet helpers */
504 if (NULL != strstr (binary_name, "gnunet")) 500 if (NULL != strstr(binary_name, "gnunet"))
505 h->binary_name = GNUNET_OS_get_libexec_binary_path (binary_name); 501 h->binary_name = GNUNET_OS_get_libexec_binary_path(binary_name);
506 else 502 else
507 h->binary_name = GNUNET_strdup (binary_name); 503 h->binary_name = GNUNET_strdup(binary_name);
508 for (c = 0; NULL != binary_argv[c]; c++) 504 for (c = 0; NULL != binary_argv[c]; c++)
509 ; 505 ;
510 h->binary_argv = GNUNET_malloc (sizeof (char *) * (c + 1)); 506 h->binary_argv = GNUNET_malloc(sizeof(char *) * (c + 1));
511 for (c = 0; NULL != binary_argv[c]; c++) 507 for (c = 0; NULL != binary_argv[c]; c++)
512 h->binary_argv[c] = GNUNET_strdup (binary_argv[c]); 508 h->binary_argv[c] = GNUNET_strdup(binary_argv[c]);
513 h->binary_argv[c] = NULL; 509 h->binary_argv[c] = NULL;
514 h->cb_cls = cb_cls; 510 h->cb_cls = cb_cls;
515 if (NULL != cb) 511 if (NULL != cb)
516 h->mst = GNUNET_MST_create (cb, h->cb_cls); 512 h->mst = GNUNET_MST_create(cb, h->cb_cls);
517 h->exp_cb = exp_cb; 513 h->exp_cb = exp_cb;
518 h->retry_back_off = 0; 514 h->retry_back_off = 0;
519 start_helper (h); 515 start_helper(h);
520 return h; 516 return h;
521} 517}
522 518
@@ -527,32 +523,32 @@ GNUNET_HELPER_start (int with_control_pipe,
527 * @param h the helper handle to free 523 * @param h the helper handle to free
528 */ 524 */
529void 525void
530GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h) 526GNUNET_HELPER_destroy(struct GNUNET_HELPER_Handle *h)
531{ 527{
532 unsigned int c; 528 unsigned int c;
533 struct GNUNET_HELPER_SendHandle *sh; 529 struct GNUNET_HELPER_SendHandle *sh;
534 530
535 if (NULL != h->write_task) 531 if (NULL != h->write_task)
536 { 532 {
537 GNUNET_SCHEDULER_cancel (h->write_task); 533 GNUNET_SCHEDULER_cancel(h->write_task);
538 h->write_task = NULL; 534 h->write_task = NULL;
539 } 535 }
540 GNUNET_assert (NULL == h->read_task); 536 GNUNET_assert(NULL == h->read_task);
541 GNUNET_assert (NULL == h->restart_task); 537 GNUNET_assert(NULL == h->restart_task);
542 while (NULL != (sh = h->sh_head)) 538 while (NULL != (sh = h->sh_head))
543 { 539 {
544 GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh); 540 GNUNET_CONTAINER_DLL_remove(h->sh_head, h->sh_tail, sh);
545 if (NULL != sh->cont) 541 if (NULL != sh->cont)
546 sh->cont (sh->cont_cls, GNUNET_SYSERR); 542 sh->cont(sh->cont_cls, GNUNET_SYSERR);
547 GNUNET_free (sh); 543 GNUNET_free(sh);
548 } 544 }
549 if (NULL != h->mst) 545 if (NULL != h->mst)
550 GNUNET_MST_destroy (h->mst); 546 GNUNET_MST_destroy(h->mst);
551 GNUNET_free (h->binary_name); 547 GNUNET_free(h->binary_name);
552 for (c = 0; h->binary_argv[c] != NULL; c++) 548 for (c = 0; h->binary_argv[c] != NULL; c++)
553 GNUNET_free (h->binary_argv[c]); 549 GNUNET_free(h->binary_argv[c]);
554 GNUNET_free (h->binary_argv); 550 GNUNET_free(h->binary_argv);
555 GNUNET_free (h); 551 GNUNET_free(h);
556} 552}
557 553
558 554
@@ -564,11 +560,11 @@ GNUNET_HELPER_destroy (struct GNUNET_HELPER_Handle *h)
564 * stdin; #GNUNET_NO to signal termination by sending SIGTERM to helper 560 * stdin; #GNUNET_NO to signal termination by sending SIGTERM to helper
565 */ 561 */
566void 562void
567GNUNET_HELPER_stop (struct GNUNET_HELPER_Handle *h, int soft_kill) 563GNUNET_HELPER_stop(struct GNUNET_HELPER_Handle *h, int soft_kill)
568{ 564{
569 h->exp_cb = NULL; 565 h->exp_cb = NULL;
570 stop_helper (h, soft_kill); 566 stop_helper(h, soft_kill);
571 GNUNET_HELPER_destroy (h); 567 GNUNET_HELPER_destroy(h);
572} 568}
573 569
574 570
@@ -578,7 +574,7 @@ GNUNET_HELPER_stop (struct GNUNET_HELPER_Handle *h, int soft_kill)
578 * @param cls handle to the helper process 574 * @param cls handle to the helper process
579 */ 575 */
580static void 576static void
581helper_write (void *cls) 577helper_write(void *cls)
582{ 578{
583 struct GNUNET_HELPER_Handle *h = cls; 579 struct GNUNET_HELPER_Handle *h = cls;
584 struct GNUNET_HELPER_SendHandle *sh; 580 struct GNUNET_HELPER_SendHandle *sh;
@@ -587,56 +583,56 @@ helper_write (void *cls)
587 583
588 h->write_task = NULL; 584 h->write_task = NULL;
589 if (NULL == (sh = h->sh_head)) 585 if (NULL == (sh = h->sh_head))
590 { 586 {
591 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Helper write had no work!\n"); 587 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Helper write had no work!\n");
592 return; /* how did this happen? */ 588 return; /* how did this happen? */
593 } 589 }
594 buf = (const char *) sh->msg; 590 buf = (const char *)sh->msg;
595 t = GNUNET_DISK_file_write (h->fh_to_helper, 591 t = GNUNET_DISK_file_write(h->fh_to_helper,
596 &buf[sh->wpos], 592 &buf[sh->wpos],
597 ntohs (sh->msg->size) - sh->wpos); 593 ntohs(sh->msg->size) - sh->wpos);
598 if (-1 == t) 594 if (-1 == t)
599 {
600 /* On write-error, restart the helper */
601 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
602 _ ("Error writing to `%s': %s\n"),
603 h->binary_name,
604 strerror (errno));
605 if (NULL != h->exp_cb)
606 { 595 {
607 h->exp_cb (h->cb_cls); 596 /* On write-error, restart the helper */
608 GNUNET_HELPER_stop (h, GNUNET_NO); 597 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
598 _("Error writing to `%s': %s\n"),
599 h->binary_name,
600 strerror(errno));
601 if (NULL != h->exp_cb)
602 {
603 h->exp_cb(h->cb_cls);
604 GNUNET_HELPER_stop(h, GNUNET_NO);
605 return;
606 }
607 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
608 "Stopping and restarting helper task!\n");
609 stop_helper(h, GNUNET_NO);
610 /* Restart the helper */
611 h->restart_task = GNUNET_SCHEDULER_add_delayed(
612 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS,
613 h->retry_back_off),
614 &restart_task,
615 h);
609 return; 616 return;
610 } 617 }
611 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 618 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
612 "Stopping and restarting helper task!\n"); 619 "Transmitted %u bytes to %s\n",
613 stop_helper (h, GNUNET_NO); 620 (unsigned int)t,
614 /* Restart the helper */ 621 h->binary_name);
615 h->restart_task = GNUNET_SCHEDULER_add_delayed (
616 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS,
617 h->retry_back_off),
618 &restart_task,
619 h);
620 return;
621 }
622 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
623 "Transmitted %u bytes to %s\n",
624 (unsigned int) t,
625 h->binary_name);
626 sh->wpos += t; 622 sh->wpos += t;
627 if (sh->wpos == ntohs (sh->msg->size)) 623 if (sh->wpos == ntohs(sh->msg->size))
628 { 624 {
629 GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh); 625 GNUNET_CONTAINER_DLL_remove(h->sh_head, h->sh_tail, sh);
630 if (NULL != sh->cont) 626 if (NULL != sh->cont)
631 sh->cont (sh->cont_cls, GNUNET_YES); 627 sh->cont(sh->cont_cls, GNUNET_YES);
632 GNUNET_free (sh); 628 GNUNET_free(sh);
633 } 629 }
634 if (NULL != h->sh_head) 630 if (NULL != h->sh_head)
635 h->write_task = 631 h->write_task =
636 GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, 632 GNUNET_SCHEDULER_add_write_file(GNUNET_TIME_UNIT_FOREVER_REL,
637 h->fh_to_helper, 633 h->fh_to_helper,
638 &helper_write, 634 &helper_write,
639 h); 635 h);
640} 636}
641 637
642 638
@@ -654,11 +650,11 @@ helper_write (void *cls)
654 * not be abortable) 650 * not be abortable)
655 */ 651 */
656struct GNUNET_HELPER_SendHandle * 652struct GNUNET_HELPER_SendHandle *
657GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h, 653GNUNET_HELPER_send(struct GNUNET_HELPER_Handle *h,
658 const struct GNUNET_MessageHeader *msg, 654 const struct GNUNET_MessageHeader *msg,
659 int can_drop, 655 int can_drop,
660 GNUNET_HELPER_Continuation cont, 656 GNUNET_HELPER_Continuation cont,
661 void *cont_cls) 657 void *cont_cls)
662{ 658{
663 struct GNUNET_HELPER_SendHandle *sh; 659 struct GNUNET_HELPER_SendHandle *sh;
664 uint16_t mlen; 660 uint16_t mlen;
@@ -667,20 +663,20 @@ GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h,
667 return NULL; 663 return NULL;
668 if ((GNUNET_YES == can_drop) && (NULL != h->sh_head)) 664 if ((GNUNET_YES == can_drop) && (NULL != h->sh_head))
669 return NULL; 665 return NULL;
670 mlen = ntohs (msg->size); 666 mlen = ntohs(msg->size);
671 sh = GNUNET_malloc (sizeof (struct GNUNET_HELPER_SendHandle) + mlen); 667 sh = GNUNET_malloc(sizeof(struct GNUNET_HELPER_SendHandle) + mlen);
672 sh->msg = (const struct GNUNET_MessageHeader *) &sh[1]; 668 sh->msg = (const struct GNUNET_MessageHeader *)&sh[1];
673 GNUNET_memcpy (&sh[1], msg, mlen); 669 GNUNET_memcpy(&sh[1], msg, mlen);
674 sh->h = h; 670 sh->h = h;
675 sh->cont = cont; 671 sh->cont = cont;
676 sh->cont_cls = cont_cls; 672 sh->cont_cls = cont_cls;
677 GNUNET_CONTAINER_DLL_insert_tail (h->sh_head, h->sh_tail, sh); 673 GNUNET_CONTAINER_DLL_insert_tail(h->sh_head, h->sh_tail, sh);
678 if (NULL == h->write_task) 674 if (NULL == h->write_task)
679 h->write_task = 675 h->write_task =
680 GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL, 676 GNUNET_SCHEDULER_add_write_file(GNUNET_TIME_UNIT_FOREVER_REL,
681 h->fh_to_helper, 677 h->fh_to_helper,
682 &helper_write, 678 &helper_write,
683 h); 679 h);
684 680
685 return sh; 681 return sh;
686} 682}
@@ -693,22 +689,22 @@ GNUNET_HELPER_send (struct GNUNET_HELPER_Handle *h,
693 * @param sh operation to cancel 689 * @param sh operation to cancel
694 */ 690 */
695void 691void
696GNUNET_HELPER_send_cancel (struct GNUNET_HELPER_SendHandle *sh) 692GNUNET_HELPER_send_cancel(struct GNUNET_HELPER_SendHandle *sh)
697{ 693{
698 struct GNUNET_HELPER_Handle *h = sh->h; 694 struct GNUNET_HELPER_Handle *h = sh->h;
699 695
700 sh->cont = NULL; 696 sh->cont = NULL;
701 sh->cont_cls = NULL; 697 sh->cont_cls = NULL;
702 if (0 == sh->wpos) 698 if (0 == sh->wpos)
703 {
704 GNUNET_CONTAINER_DLL_remove (h->sh_head, h->sh_tail, sh);
705 GNUNET_free (sh);
706 if (NULL == h->sh_head)
707 { 699 {
708 GNUNET_SCHEDULER_cancel (h->write_task); 700 GNUNET_CONTAINER_DLL_remove(h->sh_head, h->sh_tail, sh);
709 h->write_task = NULL; 701 GNUNET_free(sh);
702 if (NULL == h->sh_head)
703 {
704 GNUNET_SCHEDULER_cancel(h->write_task);
705 h->write_task = NULL;
706 }
710 } 707 }
711 }
712} 708}
713 709
714 710
diff --git a/src/util/load.c b/src/util/load.c
index f5ea875bb..5c4d9d37b 100644
--- a/src/util/load.c
+++ b/src/util/load.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/load.c 22 * @file util/load.c
@@ -27,14 +27,12 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29 29
30#define LOG(kind,...) GNUNET_log_from (kind, "util-load", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-load", __VA_ARGS__)
31 31
32/** 32/**
33 * Values we track for load calculations. 33 * Values we track for load calculations.
34 */ 34 */
35struct GNUNET_LOAD_Value 35struct GNUNET_LOAD_Value {
36{
37
38 /** 36 /**
39 * How fast should the load decline if no values are added? 37 * How fast should the load decline if no values are added?
40 */ 38 */
@@ -77,39 +75,38 @@ struct GNUNET_LOAD_Value
77 * load is so high that we currently cannot calculate it. 75 * load is so high that we currently cannot calculate it.
78 */ 76 */
79 double load; 77 double load;
80
81}; 78};
82 79
83 80
84static void 81static void
85internal_update (struct GNUNET_LOAD_Value *load) 82internal_update(struct GNUNET_LOAD_Value *load)
86{ 83{
87 struct GNUNET_TIME_Relative delta; 84 struct GNUNET_TIME_Relative delta;
88 unsigned int n; 85 unsigned int n;
89 86
90 if (load->autodecline.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) 87 if (load->autodecline.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
91 return; 88 return;
92 delta = GNUNET_TIME_absolute_get_duration (load->last_update); 89 delta = GNUNET_TIME_absolute_get_duration(load->last_update);
93 if (delta.rel_value_us < load->autodecline.rel_value_us) 90 if (delta.rel_value_us < load->autodecline.rel_value_us)
94 return; 91 return;
95 if (0 == load->autodecline.rel_value_us) 92 if (0 == load->autodecline.rel_value_us)
96 { 93 {
97 load->runavg_delay = 0.0; 94 load->runavg_delay = 0.0;
98 load->load = 0; 95 load->load = 0;
99 return; 96 return;
100 } 97 }
101 n = delta.rel_value_us / load->autodecline.rel_value_us; 98 n = delta.rel_value_us / load->autodecline.rel_value_us;
102 if (n > 16) 99 if (n > 16)
103 { 100 {
104 load->runavg_delay = 0.0; 101 load->runavg_delay = 0.0;
105 load->load = 0; 102 load->load = 0;
106 return; 103 return;
107 } 104 }
108 while (n > 0) 105 while (n > 0)
109 { 106 {
110 n--; 107 n--;
111 load->runavg_delay = (load->runavg_delay * 7.0) / 8.0; 108 load->runavg_delay = (load->runavg_delay * 7.0) / 8.0;
112 } 109 }
113} 110}
114 111
115 112
@@ -122,13 +119,13 @@ internal_update (struct GNUNET_LOAD_Value *load)
122 * @return the new load value 119 * @return the new load value
123 */ 120 */
124struct GNUNET_LOAD_Value * 121struct GNUNET_LOAD_Value *
125GNUNET_LOAD_value_init (struct GNUNET_TIME_Relative autodecline) 122GNUNET_LOAD_value_init(struct GNUNET_TIME_Relative autodecline)
126{ 123{
127 struct GNUNET_LOAD_Value *ret; 124 struct GNUNET_LOAD_Value *ret;
128 125
129 ret = GNUNET_new (struct GNUNET_LOAD_Value); 126 ret = GNUNET_new(struct GNUNET_LOAD_Value);
130 ret->autodecline = autodecline; 127 ret->autodecline = autodecline;
131 ret->last_update = GNUNET_TIME_absolute_get (); 128 ret->last_update = GNUNET_TIME_absolute_get();
132 return ret; 129 return ret;
133} 130}
134 131
@@ -140,10 +137,10 @@ GNUNET_LOAD_value_init (struct GNUNET_TIME_Relative autodecline)
140 * @param autodecline frequency of load decline 137 * @param autodecline frequency of load decline
141 */ 138 */
142void 139void
143GNUNET_LOAD_value_set_decline (struct GNUNET_LOAD_Value *load, 140GNUNET_LOAD_value_set_decline(struct GNUNET_LOAD_Value *load,
144 struct GNUNET_TIME_Relative autodecline) 141 struct GNUNET_TIME_Relative autodecline)
145{ 142{
146 internal_update (load); 143 internal_update(load);
147 load->autodecline = autodecline; 144 load->autodecline = autodecline;
148} 145}
149 146
@@ -154,7 +151,7 @@ GNUNET_LOAD_value_set_decline (struct GNUNET_LOAD_Value *load,
154 * @param load load to update 151 * @param load load to update
155 */ 152 */
156static void 153static void
157calculate_load (struct GNUNET_LOAD_Value *load) 154calculate_load(struct GNUNET_LOAD_Value *load)
158{ 155{
159 double stddev; 156 double stddev;
160 double avgdel; 157 double avgdel;
@@ -171,13 +168,13 @@ calculate_load (struct GNUNET_LOAD_Value *load)
171 * = (sum (val_i^2 - 2 avg val_i + avg^2) / (n-1) 168 * = (sum (val_i^2 - 2 avg val_i + avg^2) / (n-1)
172 * = (sum (val_i^2) - 2 avg sum (val_i) + n * avg^2) / (n-1) 169 * = (sum (val_i^2) - 2 avg sum (val_i) + n * avg^2) / (n-1)
173 */ 170 */
174 sum_val_i = (double) load->cummulative_delay; 171 sum_val_i = (double)load->cummulative_delay;
175 n = ((double) load->cummulative_request_count); 172 n = ((double)load->cummulative_request_count);
176 nm1 = n - 1.0; 173 nm1 = n - 1.0;
177 avgdel = sum_val_i / n; 174 avgdel = sum_val_i / n;
178 stddev = 175 stddev =
179 (((double) load->cummulative_squared_delay) - 2.0 * avgdel * sum_val_i + 176 (((double)load->cummulative_squared_delay) - 2.0 * avgdel * sum_val_i +
180 n * avgdel * avgdel) / nm1; 177 n * avgdel * avgdel) / nm1;
181 if (stddev <= 0) 178 if (stddev <= 0)
182 stddev = 0.01; /* must have been rounding error or zero; prevent division by zero */ 179 stddev = 0.01; /* must have been rounding error or zero; prevent division by zero */
183 /* now calculate load based on how far out we are from 180 /* now calculate load based on how far out we are from
@@ -199,10 +196,10 @@ calculate_load (struct GNUNET_LOAD_Value *load)
199 * that we could not do proper calculations 196 * that we could not do proper calculations
200 */ 197 */
201double 198double
202GNUNET_LOAD_get_load (struct GNUNET_LOAD_Value *load) 199GNUNET_LOAD_get_load(struct GNUNET_LOAD_Value *load)
203{ 200{
204 internal_update (load); 201 internal_update(load);
205 calculate_load (load); 202 calculate_load(load);
206 return load->load; 203 return load->load;
207} 204}
208 205
@@ -214,16 +211,16 @@ GNUNET_LOAD_get_load (struct GNUNET_LOAD_Value *load)
214 * @return zero if update was never called 211 * @return zero if update was never called
215 */ 212 */
216double 213double
217GNUNET_LOAD_get_average (struct GNUNET_LOAD_Value *load) 214GNUNET_LOAD_get_average(struct GNUNET_LOAD_Value *load)
218{ 215{
219 double n; 216 double n;
220 double sum_val_i; 217 double sum_val_i;
221 218
222 internal_update (load); 219 internal_update(load);
223 if (load->cummulative_request_count == 0) 220 if (load->cummulative_request_count == 0)
224 return 0.0; 221 return 0.0;
225 n = ((double) load->cummulative_request_count); 222 n = ((double)load->cummulative_request_count);
226 sum_val_i = (double) load->cummulative_delay; 223 sum_val_i = (double)load->cummulative_delay;
227 return sum_val_i / n; 224 return sum_val_i / n;
228} 225}
229 226
@@ -235,19 +232,19 @@ GNUNET_LOAD_get_average (struct GNUNET_LOAD_Value *load)
235 * @param data latest measurement value (for example, delay) 232 * @param data latest measurement value (for example, delay)
236 */ 233 */
237void 234void
238GNUNET_LOAD_update (struct GNUNET_LOAD_Value *load, uint64_t data) 235GNUNET_LOAD_update(struct GNUNET_LOAD_Value *load, uint64_t data)
239{ 236{
240 uint32_t dv; 237 uint32_t dv;
241 238
242 internal_update (load); 239 internal_update(load);
243 load->last_update = GNUNET_TIME_absolute_get (); 240 load->last_update = GNUNET_TIME_absolute_get();
244 if (data > 64 * 1024) 241 if (data > 64 * 1024)
245 { 242 {
246 /* very large */ 243 /* very large */
247 load->load = 100.0; 244 load->load = 100.0;
248 return; 245 return;
249 } 246 }
250 dv = (uint32_t) data; 247 dv = (uint32_t)data;
251 load->cummulative_delay += dv; 248 load->cummulative_delay += dv;
252 load->cummulative_squared_delay += dv * dv; 249 load->cummulative_squared_delay += dv * dv;
253 load->cummulative_request_count++; 250 load->cummulative_request_count++;
diff --git a/src/util/mq.c b/src/util/mq.c
index 03b0f3a2a..188606fb4 100644
--- a/src/util/mq.c
+++ b/src/util/mq.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Florian Dold 22 * @author Florian Dold
@@ -26,11 +26,10 @@
26#include "platform.h" 26#include "platform.h"
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29#define LOG(kind, ...) GNUNET_log_from (kind, "util-mq", __VA_ARGS__) 29#define LOG(kind, ...) GNUNET_log_from(kind, "util-mq", __VA_ARGS__)
30 30
31 31
32struct GNUNET_MQ_Envelope 32struct GNUNET_MQ_Envelope {
33{
34 /** 33 /**
35 * Messages are stored in a linked list. 34 * Messages are stored in a linked list.
36 * Each queue has its own list of envelopes. 35 * Each queue has its own list of envelopes.
@@ -82,8 +81,7 @@ struct GNUNET_MQ_Envelope
82/** 81/**
83 * Handle to a message queue. 82 * Handle to a message queue.
84 */ 83 */
85struct GNUNET_MQ_Handle 84struct GNUNET_MQ_Handle {
86{
87 /** 85 /**
88 * Handlers array, or NULL if the queue should not receive messages 86 * Handlers array, or NULL if the queue should not receive messages
89 */ 87 */
@@ -199,17 +197,17 @@ struct GNUNET_MQ_Handle
199 * @param mh message to dispatch 197 * @param mh message to dispatch
200 */ 198 */
201void 199void
202GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq, 200GNUNET_MQ_inject_message(struct GNUNET_MQ_Handle *mq,
203 const struct GNUNET_MessageHeader *mh) 201 const struct GNUNET_MessageHeader *mh)
204{ 202{
205 int ret; 203 int ret;
206 204
207 ret = GNUNET_MQ_handle_message (mq->handlers, mh); 205 ret = GNUNET_MQ_handle_message(mq->handlers, mh);
208 if (GNUNET_SYSERR == ret) 206 if (GNUNET_SYSERR == ret)
209 { 207 {
210 GNUNET_MQ_inject_error (mq, GNUNET_MQ_ERROR_MALFORMED); 208 GNUNET_MQ_inject_error(mq, GNUNET_MQ_ERROR_MALFORMED);
211 return; 209 return;
212 } 210 }
213} 211}
214 212
215 213
@@ -226,62 +224,62 @@ GNUNET_MQ_inject_message (struct GNUNET_MQ_Handle *mq,
226 * #GNUNET_SYSERR if message was rejected by check function 224 * #GNUNET_SYSERR if message was rejected by check function
227 */ 225 */
228int 226int
229GNUNET_MQ_handle_message (const struct GNUNET_MQ_MessageHandler *handlers, 227GNUNET_MQ_handle_message(const struct GNUNET_MQ_MessageHandler *handlers,
230 const struct GNUNET_MessageHeader *mh) 228 const struct GNUNET_MessageHeader *mh)
231{ 229{
232 const struct GNUNET_MQ_MessageHandler *handler; 230 const struct GNUNET_MQ_MessageHandler *handler;
233 int handled = GNUNET_NO; 231 int handled = GNUNET_NO;
234 uint16_t msize = ntohs (mh->size); 232 uint16_t msize = ntohs(mh->size);
235 uint16_t mtype = ntohs (mh->type); 233 uint16_t mtype = ntohs(mh->type);
236 234
237 LOG (GNUNET_ERROR_TYPE_DEBUG, 235 LOG(GNUNET_ERROR_TYPE_DEBUG,
238 "Received message of type %u and size %u\n", 236 "Received message of type %u and size %u\n",
239 mtype, 237 mtype,
240 msize); 238 msize);
241 239
242 if (NULL == handlers) 240 if (NULL == handlers)
243 goto done; 241 goto done;
244 for (handler = handlers; NULL != handler->cb; handler++) 242 for (handler = handlers; NULL != handler->cb; handler++)
245 {
246 if (handler->type == mtype)
247 { 243 {
248 handled = GNUNET_YES; 244 if (handler->type == mtype)
249 if ((handler->expected_size > msize) || 245 {
250 ((handler->expected_size != msize) && (NULL == handler->mv))) 246 handled = GNUNET_YES;
251 { 247 if ((handler->expected_size > msize) ||
252 /* Too small, or not an exact size and 248 ((handler->expected_size != msize) && (NULL == handler->mv)))
253 no 'mv' handler to check rest */ 249 {
254 LOG (GNUNET_ERROR_TYPE_ERROR, 250 /* Too small, or not an exact size and
255 "Received malformed message of type %u\n", 251 no 'mv' handler to check rest */
256 (unsigned int) handler->type); 252 LOG(GNUNET_ERROR_TYPE_ERROR,
257 return GNUNET_SYSERR; 253 "Received malformed message of type %u\n",
258 } 254 (unsigned int)handler->type);
259 if ((NULL == handler->mv) || 255 return GNUNET_SYSERR;
260 (GNUNET_OK == handler->mv (handler->cls, mh))) 256 }
261 { 257 if ((NULL == handler->mv) ||
262 /* message well-formed, pass to handler */ 258 (GNUNET_OK == handler->mv(handler->cls, mh)))
263 handler->cb (handler->cls, mh); 259 {
264 } 260 /* message well-formed, pass to handler */
265 else 261 handler->cb(handler->cls, mh);
266 { 262 }
267 /* Message rejected by check routine */ 263 else
268 LOG (GNUNET_ERROR_TYPE_ERROR, 264 {
269 "Received malformed message of type %u\n", 265 /* Message rejected by check routine */
270 (unsigned int) handler->type); 266 LOG(GNUNET_ERROR_TYPE_ERROR,
271 return GNUNET_SYSERR; 267 "Received malformed message of type %u\n",
272 } 268 (unsigned int)handler->type);
273 break; 269 return GNUNET_SYSERR;
270 }
271 break;
272 }
274 } 273 }
275 }
276done: 274done:
277 if (GNUNET_NO == handled) 275 if (GNUNET_NO == handled)
278 { 276 {
279 LOG (GNUNET_ERROR_TYPE_INFO, 277 LOG(GNUNET_ERROR_TYPE_INFO,
280 "No handler for message of type %u and size %u\n", 278 "No handler for message of type %u and size %u\n",
281 mtype, 279 mtype,
282 msize); 280 msize);
283 return GNUNET_NO; 281 return GNUNET_NO;
284 } 282 }
285 return GNUNET_OK; 283 return GNUNET_OK;
286} 284}
287 285
@@ -297,16 +295,16 @@ done:
297 * @param error the error type 295 * @param error the error type
298 */ 296 */
299void 297void
300GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq, enum GNUNET_MQ_Error error) 298GNUNET_MQ_inject_error(struct GNUNET_MQ_Handle *mq, enum GNUNET_MQ_Error error)
301{ 299{
302 if (NULL == mq->error_handler) 300 if (NULL == mq->error_handler)
303 { 301 {
304 LOG (GNUNET_ERROR_TYPE_WARNING, 302 LOG(GNUNET_ERROR_TYPE_WARNING,
305 "Got error %d, but no handler installed\n", 303 "Got error %d, but no handler installed\n",
306 (int) error); 304 (int)error);
307 return; 305 return;
308 } 306 }
309 mq->error_handler (mq->error_handler_cls, error); 307 mq->error_handler(mq->error_handler_cls, error);
310} 308}
311 309
312 310
@@ -318,10 +316,10 @@ GNUNET_MQ_inject_error (struct GNUNET_MQ_Handle *mq, enum GNUNET_MQ_Error error)
318 * @param mqm the message to discard 316 * @param mqm the message to discard
319 */ 317 */
320void 318void
321GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *ev) 319GNUNET_MQ_discard(struct GNUNET_MQ_Envelope *ev)
322{ 320{
323 GNUNET_assert (NULL == ev->parent_queue); 321 GNUNET_assert(NULL == ev->parent_queue);
324 GNUNET_free (ev); 322 GNUNET_free(ev);
325} 323}
326 324
327 325
@@ -332,12 +330,12 @@ GNUNET_MQ_discard (struct GNUNET_MQ_Envelope *ev)
332 * @return number of queued, non-transmitted messages 330 * @return number of queued, non-transmitted messages
333 */ 331 */
334unsigned int 332unsigned int
335GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq) 333GNUNET_MQ_get_length(struct GNUNET_MQ_Handle *mq)
336{ 334{
337 if (GNUNET_YES != mq->in_flight) 335 if (GNUNET_YES != mq->in_flight)
338 { 336 {
339 return mq->queue_length; 337 return mq->queue_length;
340 } 338 }
341 return mq->queue_length - 1; 339 return mq->queue_length - 1;
342} 340}
343 341
@@ -350,36 +348,36 @@ GNUNET_MQ_get_length (struct GNUNET_MQ_Handle *mq)
350 * @param ev the envelope with the message to send. 348 * @param ev the envelope with the message to send.
351 */ 349 */
352void 350void
353GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev) 351GNUNET_MQ_send(struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev)
354{ 352{
355 GNUNET_assert (NULL != mq); 353 GNUNET_assert(NULL != mq);
356 GNUNET_assert (NULL == ev->parent_queue); 354 GNUNET_assert(NULL == ev->parent_queue);
357 355
358 mq->queue_length++; 356 mq->queue_length++;
359 if (mq->queue_length >= 10000) 357 if (mq->queue_length >= 10000)
360 { 358 {
361 /* This would seem like a bug... */ 359 /* This would seem like a bug... */
362 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 360 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
363 "MQ with %u entries extended by message of type %u (FC broken?)\n", 361 "MQ with %u entries extended by message of type %u (FC broken?)\n",
364 (unsigned int) mq->queue_length, 362 (unsigned int)mq->queue_length,
365 (unsigned int) ntohs (ev->mh->type)); 363 (unsigned int)ntohs(ev->mh->type));
366 } 364 }
367 ev->parent_queue = mq; 365 ev->parent_queue = mq;
368 /* is the implementation busy? queue it! */ 366 /* is the implementation busy? queue it! */
369 if ((NULL != mq->current_envelope) || (NULL != mq->send_task)) 367 if ((NULL != mq->current_envelope) || (NULL != mq->send_task))
370 { 368 {
371 GNUNET_CONTAINER_DLL_insert_tail (mq->envelope_head, mq->envelope_tail, ev); 369 GNUNET_CONTAINER_DLL_insert_tail(mq->envelope_head, mq->envelope_tail, ev);
372 return; 370 return;
373 } 371 }
374 GNUNET_assert (NULL == mq->envelope_head); 372 GNUNET_assert(NULL == mq->envelope_head);
375 mq->current_envelope = ev; 373 mq->current_envelope = ev;
376 374
377 LOG (GNUNET_ERROR_TYPE_DEBUG, 375 LOG(GNUNET_ERROR_TYPE_DEBUG,
378 "sending message of type %u, queue empty (MQ: %p)\n", 376 "sending message of type %u, queue empty (MQ: %p)\n",
379 ntohs (ev->mh->type), 377 ntohs(ev->mh->type),
380 mq); 378 mq);
381 379
382 mq->send_impl (mq, ev->mh, mq->impl_state); 380 mq->send_impl(mq, ev->mh, mq->impl_state);
383} 381}
384 382
385 383
@@ -391,12 +389,12 @@ GNUNET_MQ_send (struct GNUNET_MQ_Handle *mq, struct GNUNET_MQ_Envelope *ev)
391 * @return NULL if queue is empty (or has no envelope that is not under transmission) 389 * @return NULL if queue is empty (or has no envelope that is not under transmission)
392 */ 390 */
393struct GNUNET_MQ_Envelope * 391struct GNUNET_MQ_Envelope *
394GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq) 392GNUNET_MQ_unsent_head(struct GNUNET_MQ_Handle *mq)
395{ 393{
396 struct GNUNET_MQ_Envelope *env; 394 struct GNUNET_MQ_Envelope *env;
397 395
398 env = mq->envelope_head; 396 env = mq->envelope_head;
399 GNUNET_CONTAINER_DLL_remove (mq->envelope_head, mq->envelope_tail, env); 397 GNUNET_CONTAINER_DLL_remove(mq->envelope_head, mq->envelope_tail, env);
400 mq->queue_length--; 398 mq->queue_length--;
401 env->parent_queue = NULL; 399 env->parent_queue = NULL;
402 return env; 400 return env;
@@ -411,13 +409,13 @@ GNUNET_MQ_unsent_head (struct GNUNET_MQ_Handle *mq)
411 * @return copy of @a env 409 * @return copy of @a env
412 */ 410 */
413struct GNUNET_MQ_Envelope * 411struct GNUNET_MQ_Envelope *
414GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env) 412GNUNET_MQ_env_copy(struct GNUNET_MQ_Envelope *env)
415{ 413{
416 GNUNET_assert (NULL == env->next); 414 GNUNET_assert(NULL == env->next);
417 GNUNET_assert (NULL == env->parent_queue); 415 GNUNET_assert(NULL == env->parent_queue);
418 GNUNET_assert (NULL == env->sent_cb); 416 GNUNET_assert(NULL == env->sent_cb);
419 GNUNET_assert (GNUNET_NO == env->have_custom_options); 417 GNUNET_assert(GNUNET_NO == env->have_custom_options);
420 return GNUNET_MQ_msg_copy (env->mh); 418 return GNUNET_MQ_msg_copy(env->mh);
421} 419}
422 420
423 421
@@ -429,19 +427,19 @@ GNUNET_MQ_env_copy (struct GNUNET_MQ_Envelope *env)
429 * @param ev the envelope with the message to send. 427 * @param ev the envelope with the message to send.
430 */ 428 */
431void 429void
432GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq, 430GNUNET_MQ_send_copy(struct GNUNET_MQ_Handle *mq,
433 const struct GNUNET_MQ_Envelope *ev) 431 const struct GNUNET_MQ_Envelope *ev)
434{ 432{
435 struct GNUNET_MQ_Envelope *env; 433 struct GNUNET_MQ_Envelope *env;
436 uint16_t msize; 434 uint16_t msize;
437 435
438 msize = ntohs (ev->mh->size); 436 msize = ntohs(ev->mh->size);
439 env = GNUNET_malloc (sizeof (struct GNUNET_MQ_Envelope) + msize); 437 env = GNUNET_malloc(sizeof(struct GNUNET_MQ_Envelope) + msize);
440 env->mh = (struct GNUNET_MessageHeader *) &env[1]; 438 env->mh = (struct GNUNET_MessageHeader *)&env[1];
441 env->sent_cb = ev->sent_cb; 439 env->sent_cb = ev->sent_cb;
442 env->sent_cls = ev->sent_cls; 440 env->sent_cls = ev->sent_cls;
443 GNUNET_memcpy (&env[1], ev->mh, msize); 441 GNUNET_memcpy(&env[1], ev->mh, msize);
444 GNUNET_MQ_send (mq, env); 442 GNUNET_MQ_send(mq, env);
445} 443}
446 444
447 445
@@ -453,7 +451,7 @@ GNUNET_MQ_send_copy (struct GNUNET_MQ_Handle *mq,
453 * @param cls message queue to send the next message with 451 * @param cls message queue to send the next message with
454 */ 452 */
455static void 453static void
456impl_send_continue (void *cls) 454impl_send_continue(void *cls)
457{ 455{
458 struct GNUNET_MQ_Handle *mq = cls; 456 struct GNUNET_MQ_Handle *mq = cls;
459 457
@@ -463,15 +461,15 @@ impl_send_continue (void *cls)
463 if (NULL == mq->envelope_head) 461 if (NULL == mq->envelope_head)
464 return; 462 return;
465 mq->current_envelope = mq->envelope_head; 463 mq->current_envelope = mq->envelope_head;
466 GNUNET_CONTAINER_DLL_remove (mq->envelope_head, 464 GNUNET_CONTAINER_DLL_remove(mq->envelope_head,
467 mq->envelope_tail, 465 mq->envelope_tail,
468 mq->current_envelope); 466 mq->current_envelope);
469 467
470 LOG (GNUNET_ERROR_TYPE_DEBUG, 468 LOG(GNUNET_ERROR_TYPE_DEBUG,
471 "sending message of type %u from queue\n", 469 "sending message of type %u from queue\n",
472 ntohs (mq->current_envelope->mh->type)); 470 ntohs(mq->current_envelope->mh->type));
473 471
474 mq->send_impl (mq, mq->current_envelope->mh, mq->impl_state); 472 mq->send_impl(mq, mq->current_envelope->mh, mq->impl_state);
475} 473}
476 474
477 475
@@ -483,25 +481,25 @@ impl_send_continue (void *cls)
483 * @param mq message queue to send the next message with 481 * @param mq message queue to send the next message with
484 */ 482 */
485void 483void
486GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq) 484GNUNET_MQ_impl_send_continue(struct GNUNET_MQ_Handle *mq)
487{ 485{
488 struct GNUNET_MQ_Envelope *current_envelope; 486 struct GNUNET_MQ_Envelope *current_envelope;
489 GNUNET_SCHEDULER_TaskCallback cb; 487 GNUNET_SCHEDULER_TaskCallback cb;
490 488
491 GNUNET_assert (0 < mq->queue_length); 489 GNUNET_assert(0 < mq->queue_length);
492 mq->queue_length--; 490 mq->queue_length--;
493 mq->in_flight = GNUNET_NO; 491 mq->in_flight = GNUNET_NO;
494 current_envelope = mq->current_envelope; 492 current_envelope = mq->current_envelope;
495 current_envelope->parent_queue = NULL; 493 current_envelope->parent_queue = NULL;
496 mq->current_envelope = NULL; 494 mq->current_envelope = NULL;
497 GNUNET_assert (NULL == mq->send_task); 495 GNUNET_assert(NULL == mq->send_task);
498 mq->send_task = GNUNET_SCHEDULER_add_now (&impl_send_continue, mq); 496 mq->send_task = GNUNET_SCHEDULER_add_now(&impl_send_continue, mq);
499 if (NULL != (cb = current_envelope->sent_cb)) 497 if (NULL != (cb = current_envelope->sent_cb))
500 { 498 {
501 current_envelope->sent_cb = NULL; 499 current_envelope->sent_cb = NULL;
502 cb (current_envelope->sent_cls); 500 cb(current_envelope->sent_cls);
503 } 501 }
504 GNUNET_free (current_envelope); 502 GNUNET_free(current_envelope);
505} 503}
506 504
507 505
@@ -516,7 +514,7 @@ GNUNET_MQ_impl_send_continue (struct GNUNET_MQ_Handle *mq)
516 * @param mq message queue to send the next message with 514 * @param mq message queue to send the next message with
517 */ 515 */
518void 516void
519GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq) 517GNUNET_MQ_impl_send_in_flight(struct GNUNET_MQ_Handle *mq)
520{ 518{
521 struct GNUNET_MQ_Envelope *current_envelope; 519 struct GNUNET_MQ_Envelope *current_envelope;
522 GNUNET_SCHEDULER_TaskCallback cb; 520 GNUNET_SCHEDULER_TaskCallback cb;
@@ -525,14 +523,14 @@ GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq)
525 /* call is only valid if we're actually currently sending 523 /* call is only valid if we're actually currently sending
526 * a message */ 524 * a message */
527 current_envelope = mq->current_envelope; 525 current_envelope = mq->current_envelope;
528 GNUNET_assert (NULL != current_envelope); 526 GNUNET_assert(NULL != current_envelope);
529 /* can't call cancel from now on anymore */ 527 /* can't call cancel from now on anymore */
530 current_envelope->parent_queue = NULL; 528 current_envelope->parent_queue = NULL;
531 if (NULL != (cb = current_envelope->sent_cb)) 529 if (NULL != (cb = current_envelope->sent_cb))
532 { 530 {
533 current_envelope->sent_cb = NULL; 531 current_envelope->sent_cb = NULL;
534 cb (current_envelope->sent_cls); 532 cb(current_envelope->sent_cls);
535 } 533 }
536} 534}
537 535
538 536
@@ -549,21 +547,21 @@ GNUNET_MQ_impl_send_in_flight (struct GNUNET_MQ_Handle *mq)
549 * @return a new message queue 547 * @return a new message queue
550 */ 548 */
551struct GNUNET_MQ_Handle * 549struct GNUNET_MQ_Handle *
552GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send, 550GNUNET_MQ_queue_for_callbacks(GNUNET_MQ_SendImpl send,
553 GNUNET_MQ_DestroyImpl destroy, 551 GNUNET_MQ_DestroyImpl destroy,
554 GNUNET_MQ_CancelImpl cancel, 552 GNUNET_MQ_CancelImpl cancel,
555 void *impl_state, 553 void *impl_state,
556 const struct GNUNET_MQ_MessageHandler *handlers, 554 const struct GNUNET_MQ_MessageHandler *handlers,
557 GNUNET_MQ_ErrorHandler error_handler, 555 GNUNET_MQ_ErrorHandler error_handler,
558 void *error_handler_cls) 556 void *error_handler_cls)
559{ 557{
560 struct GNUNET_MQ_Handle *mq; 558 struct GNUNET_MQ_Handle *mq;
561 559
562 mq = GNUNET_new (struct GNUNET_MQ_Handle); 560 mq = GNUNET_new(struct GNUNET_MQ_Handle);
563 mq->send_impl = send; 561 mq->send_impl = send;
564 mq->destroy_impl = destroy; 562 mq->destroy_impl = destroy;
565 mq->cancel_impl = cancel; 563 mq->cancel_impl = cancel;
566 mq->handlers = GNUNET_MQ_copy_handlers (handlers); 564 mq->handlers = GNUNET_MQ_copy_handlers(handlers);
567 mq->error_handler = error_handler; 565 mq->error_handler = error_handler;
568 mq->error_handler_cls = error_handler_cls; 566 mq->error_handler_cls = error_handler_cls;
569 mq->impl_state = impl_state; 567 mq->impl_state = impl_state;
@@ -580,7 +578,7 @@ GNUNET_MQ_queue_for_callbacks (GNUNET_MQ_SendImpl send,
580 * @param handlers_cls new closure to use 578 * @param handlers_cls new closure to use
581 */ 579 */
582void 580void
583GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq, void *handlers_cls) 581GNUNET_MQ_set_handlers_closure(struct GNUNET_MQ_Handle *mq, void *handlers_cls)
584{ 582{
585 if (NULL == mq->handlers) 583 if (NULL == mq->handlers)
586 return; 584 return;
@@ -599,10 +597,10 @@ GNUNET_MQ_set_handlers_closure (struct GNUNET_MQ_Handle *mq, void *handlers_cls)
599 * @return message to send, never NULL 597 * @return message to send, never NULL
600 */ 598 */
601const struct GNUNET_MessageHeader * 599const struct GNUNET_MessageHeader *
602GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq) 600GNUNET_MQ_impl_current(struct GNUNET_MQ_Handle *mq)
603{ 601{
604 GNUNET_assert (NULL != mq->current_envelope); 602 GNUNET_assert(NULL != mq->current_envelope);
605 GNUNET_assert (NULL != mq->current_envelope->mh); 603 GNUNET_assert(NULL != mq->current_envelope->mh);
606 return mq->current_envelope->mh; 604 return mq->current_envelope->mh;
607} 605}
608 606
@@ -622,21 +620,21 @@ GNUNET_MQ_impl_current (struct GNUNET_MQ_Handle *mq)
622 * @return message to send, never NULL 620 * @return message to send, never NULL
623 */ 621 */
624void * 622void *
625GNUNET_MQ_impl_state (struct GNUNET_MQ_Handle *mq) 623GNUNET_MQ_impl_state(struct GNUNET_MQ_Handle *mq)
626{ 624{
627 return mq->impl_state; 625 return mq->impl_state;
628} 626}
629 627
630 628
631struct GNUNET_MQ_Envelope * 629struct GNUNET_MQ_Envelope *
632GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp, uint16_t size, uint16_t type) 630GNUNET_MQ_msg_(struct GNUNET_MessageHeader **mhp, uint16_t size, uint16_t type)
633{ 631{
634 struct GNUNET_MQ_Envelope *ev; 632 struct GNUNET_MQ_Envelope *ev;
635 633
636 ev = GNUNET_malloc (size + sizeof (struct GNUNET_MQ_Envelope)); 634 ev = GNUNET_malloc(size + sizeof(struct GNUNET_MQ_Envelope));
637 ev->mh = (struct GNUNET_MessageHeader *) &ev[1]; 635 ev->mh = (struct GNUNET_MessageHeader *)&ev[1];
638 ev->mh->size = htons (size); 636 ev->mh->size = htons(size);
639 ev->mh->type = htons (type); 637 ev->mh->type = htons(type);
640 if (NULL != mhp) 638 if (NULL != mhp)
641 *mhp = ev->mh; 639 *mhp = ev->mh;
642 return ev; 640 return ev;
@@ -650,14 +648,14 @@ GNUNET_MQ_msg_ (struct GNUNET_MessageHeader **mhp, uint16_t size, uint16_t type)
650 * @return envelope containing @a hdr 648 * @return envelope containing @a hdr
651 */ 649 */
652struct GNUNET_MQ_Envelope * 650struct GNUNET_MQ_Envelope *
653GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr) 651GNUNET_MQ_msg_copy(const struct GNUNET_MessageHeader *hdr)
654{ 652{
655 struct GNUNET_MQ_Envelope *mqm; 653 struct GNUNET_MQ_Envelope *mqm;
656 uint16_t size = ntohs (hdr->size); 654 uint16_t size = ntohs(hdr->size);
657 655
658 mqm = GNUNET_malloc (sizeof (*mqm) + size); 656 mqm = GNUNET_malloc(sizeof(*mqm) + size);
659 mqm->mh = (struct GNUNET_MessageHeader *) &mqm[1]; 657 mqm->mh = (struct GNUNET_MessageHeader *)&mqm[1];
660 GNUNET_memcpy (mqm->mh, hdr, size); 658 GNUNET_memcpy(mqm->mh, hdr, size);
661 return mqm; 659 return mqm;
662} 660}
663 661
@@ -672,27 +670,27 @@ GNUNET_MQ_msg_copy (const struct GNUNET_MessageHeader *hdr)
672 * @param nested_mh the message to append to the message after base_size 670 * @param nested_mh the message to append to the message after base_size
673 */ 671 */
674struct GNUNET_MQ_Envelope * 672struct GNUNET_MQ_Envelope *
675GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp, 673GNUNET_MQ_msg_nested_mh_(struct GNUNET_MessageHeader **mhp,
676 uint16_t base_size, 674 uint16_t base_size,
677 uint16_t type, 675 uint16_t type,
678 const struct GNUNET_MessageHeader *nested_mh) 676 const struct GNUNET_MessageHeader *nested_mh)
679{ 677{
680 struct GNUNET_MQ_Envelope *mqm; 678 struct GNUNET_MQ_Envelope *mqm;
681 uint16_t size; 679 uint16_t size;
682 680
683 if (NULL == nested_mh) 681 if (NULL == nested_mh)
684 return GNUNET_MQ_msg_ (mhp, base_size, type); 682 return GNUNET_MQ_msg_(mhp, base_size, type);
685 683
686 size = base_size + ntohs (nested_mh->size); 684 size = base_size + ntohs(nested_mh->size);
687 685
688 /* check for uint16_t overflow */ 686 /* check for uint16_t overflow */
689 if (size < base_size) 687 if (size < base_size)
690 return NULL; 688 return NULL;
691 689
692 mqm = GNUNET_MQ_msg_ (mhp, size, type); 690 mqm = GNUNET_MQ_msg_(mhp, size, type);
693 GNUNET_memcpy ((char *) mqm->mh + base_size, 691 GNUNET_memcpy((char *)mqm->mh + base_size,
694 nested_mh, 692 nested_mh,
695 ntohs (nested_mh->size)); 693 ntohs(nested_mh->size));
696 694
697 return mqm; 695 return mqm;
698} 696}
@@ -705,22 +703,22 @@ GNUNET_MQ_msg_nested_mh_ (struct GNUNET_MessageHeader **mhp,
705 * @param assoc_data to associate 703 * @param assoc_data to associate
706 */ 704 */
707uint32_t 705uint32_t
708GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq, void *assoc_data) 706GNUNET_MQ_assoc_add(struct GNUNET_MQ_Handle *mq, void *assoc_data)
709{ 707{
710 uint32_t id; 708 uint32_t id;
711 709
712 if (NULL == mq->assoc_map) 710 if (NULL == mq->assoc_map)
713 { 711 {
714 mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create (8); 712 mq->assoc_map = GNUNET_CONTAINER_multihashmap32_create(8);
715 mq->assoc_id = 1; 713 mq->assoc_id = 1;
716 } 714 }
717 id = mq->assoc_id++; 715 id = mq->assoc_id++;
718 GNUNET_assert (GNUNET_OK == 716 GNUNET_assert(GNUNET_OK ==
719 GNUNET_CONTAINER_multihashmap32_put ( 717 GNUNET_CONTAINER_multihashmap32_put(
720 mq->assoc_map, 718 mq->assoc_map,
721 id, 719 id,
722 assoc_data, 720 assoc_data,
723 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); 721 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
724 return id; 722 return id;
725} 723}
726 724
@@ -733,11 +731,11 @@ GNUNET_MQ_assoc_add (struct GNUNET_MQ_Handle *mq, void *assoc_data)
733 * @return the associated data 731 * @return the associated data
734 */ 732 */
735void * 733void *
736GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq, uint32_t request_id) 734GNUNET_MQ_assoc_get(struct GNUNET_MQ_Handle *mq, uint32_t request_id)
737{ 735{
738 if (NULL == mq->assoc_map) 736 if (NULL == mq->assoc_map)
739 return NULL; 737 return NULL;
740 return GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map, request_id); 738 return GNUNET_CONTAINER_multihashmap32_get(mq->assoc_map, request_id);
741} 739}
742 740
743 741
@@ -749,14 +747,14 @@ GNUNET_MQ_assoc_get (struct GNUNET_MQ_Handle *mq, uint32_t request_id)
749 * @return the associated data 747 * @return the associated data
750 */ 748 */
751void * 749void *
752GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq, uint32_t request_id) 750GNUNET_MQ_assoc_remove(struct GNUNET_MQ_Handle *mq, uint32_t request_id)
753{ 751{
754 void *val; 752 void *val;
755 753
756 if (NULL == mq->assoc_map) 754 if (NULL == mq->assoc_map)
757 return NULL; 755 return NULL;
758 val = GNUNET_CONTAINER_multihashmap32_get (mq->assoc_map, request_id); 756 val = GNUNET_CONTAINER_multihashmap32_get(mq->assoc_map, request_id);
759 GNUNET_CONTAINER_multihashmap32_remove_all (mq->assoc_map, request_id); 757 GNUNET_CONTAINER_multihashmap32_remove_all(mq->assoc_map, request_id);
760 return val; 758 return val;
761} 759}
762 760
@@ -771,12 +769,12 @@ GNUNET_MQ_assoc_remove (struct GNUNET_MQ_Handle *mq, uint32_t request_id)
771 * @param cb_cls closure for the callback 769 * @param cb_cls closure for the callback
772 */ 770 */
773void 771void
774GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev, 772GNUNET_MQ_notify_sent(struct GNUNET_MQ_Envelope *ev,
775 GNUNET_SCHEDULER_TaskCallback cb, 773 GNUNET_SCHEDULER_TaskCallback cb,
776 void *cb_cls) 774 void *cb_cls)
777{ 775{
778 /* allow setting *OR* clearing callback */ 776 /* allow setting *OR* clearing callback */
779 GNUNET_assert ((NULL == ev->sent_cb) || (NULL == cb)); 777 GNUNET_assert((NULL == ev->sent_cb) || (NULL == cb));
780 ev->sent_cb = cb; 778 ev->sent_cb = cb;
781 ev->sent_cls = cb_cls; 779 ev->sent_cls = cb_cls;
782} 780}
@@ -786,8 +784,7 @@ GNUNET_MQ_notify_sent (struct GNUNET_MQ_Envelope *ev,
786 * Handle we return for callbacks registered to be 784 * Handle we return for callbacks registered to be
787 * notified when #GNUNET_MQ_destroy() is called on a queue. 785 * notified when #GNUNET_MQ_destroy() is called on a queue.
788 */ 786 */
789struct GNUNET_MQ_DestroyNotificationHandle 787struct GNUNET_MQ_DestroyNotificationHandle {
790{
791 /** 788 /**
792 * Kept in a DLL. 789 * Kept in a DLL.
793 */ 790 */
@@ -821,86 +818,86 @@ struct GNUNET_MQ_DestroyNotificationHandle
821 * @param mq message queue to destroy 818 * @param mq message queue to destroy
822 */ 819 */
823void 820void
824GNUNET_MQ_destroy (struct GNUNET_MQ_Handle *mq) 821GNUNET_MQ_destroy(struct GNUNET_MQ_Handle *mq)
825{ 822{
826 struct GNUNET_MQ_DestroyNotificationHandle *dnh; 823 struct GNUNET_MQ_DestroyNotificationHandle *dnh;
827 824
828 if (NULL != mq->destroy_impl) 825 if (NULL != mq->destroy_impl)
829 { 826 {
830 mq->destroy_impl (mq, mq->impl_state); 827 mq->destroy_impl(mq, mq->impl_state);
831 } 828 }
832 if (NULL != mq->send_task) 829 if (NULL != mq->send_task)
833 { 830 {
834 GNUNET_SCHEDULER_cancel (mq->send_task); 831 GNUNET_SCHEDULER_cancel(mq->send_task);
835 mq->send_task = NULL; 832 mq->send_task = NULL;
836 } 833 }
837 while (NULL != mq->envelope_head) 834 while (NULL != mq->envelope_head)
838 { 835 {
839 struct GNUNET_MQ_Envelope *ev; 836 struct GNUNET_MQ_Envelope *ev;
840 837
841 ev = mq->envelope_head; 838 ev = mq->envelope_head;
842 ev->parent_queue = NULL; 839 ev->parent_queue = NULL;
843 GNUNET_CONTAINER_DLL_remove (mq->envelope_head, mq->envelope_tail, ev); 840 GNUNET_CONTAINER_DLL_remove(mq->envelope_head, mq->envelope_tail, ev);
844 GNUNET_assert (0 < mq->queue_length); 841 GNUNET_assert(0 < mq->queue_length);
845 mq->queue_length--; 842 mq->queue_length--;
846 LOG (GNUNET_ERROR_TYPE_DEBUG, 843 LOG(GNUNET_ERROR_TYPE_DEBUG,
847 "MQ destroy drops message of type %u\n", 844 "MQ destroy drops message of type %u\n",
848 ntohs (ev->mh->type)); 845 ntohs(ev->mh->type));
849 GNUNET_MQ_discard (ev); 846 GNUNET_MQ_discard(ev);
850 } 847 }
851 if (NULL != mq->current_envelope) 848 if (NULL != mq->current_envelope)
852 { 849 {
853 /* we can only discard envelopes that 850 /* we can only discard envelopes that
854 * are not queued! */ 851 * are not queued! */
855 mq->current_envelope->parent_queue = NULL; 852 mq->current_envelope->parent_queue = NULL;
856 LOG (GNUNET_ERROR_TYPE_DEBUG, 853 LOG(GNUNET_ERROR_TYPE_DEBUG,
857 "MQ destroy drops current message of type %u\n", 854 "MQ destroy drops current message of type %u\n",
858 ntohs (mq->current_envelope->mh->type)); 855 ntohs(mq->current_envelope->mh->type));
859 GNUNET_MQ_discard (mq->current_envelope); 856 GNUNET_MQ_discard(mq->current_envelope);
860 mq->current_envelope = NULL; 857 mq->current_envelope = NULL;
861 GNUNET_assert (0 < mq->queue_length); 858 GNUNET_assert(0 < mq->queue_length);
862 mq->queue_length--; 859 mq->queue_length--;
863 } 860 }
864 GNUNET_assert (0 == mq->queue_length); 861 GNUNET_assert(0 == mq->queue_length);
865 while (NULL != (dnh = mq->dnh_head)) 862 while (NULL != (dnh = mq->dnh_head))
866 { 863 {
867 dnh->cb (dnh->cb_cls); 864 dnh->cb(dnh->cb_cls);
868 GNUNET_MQ_destroy_notify_cancel (dnh); 865 GNUNET_MQ_destroy_notify_cancel(dnh);
869 } 866 }
870 if (NULL != mq->assoc_map) 867 if (NULL != mq->assoc_map)
871 { 868 {
872 GNUNET_CONTAINER_multihashmap32_destroy (mq->assoc_map); 869 GNUNET_CONTAINER_multihashmap32_destroy(mq->assoc_map);
873 mq->assoc_map = NULL; 870 mq->assoc_map = NULL;
874 } 871 }
875 GNUNET_free_non_null (mq->handlers); 872 GNUNET_free_non_null(mq->handlers);
876 GNUNET_free (mq); 873 GNUNET_free(mq);
877} 874}
878 875
879 876
880const struct GNUNET_MessageHeader * 877const struct GNUNET_MessageHeader *
881GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh, 878GNUNET_MQ_extract_nested_mh_(const struct GNUNET_MessageHeader *mh,
882 uint16_t base_size) 879 uint16_t base_size)
883{ 880{
884 uint16_t whole_size; 881 uint16_t whole_size;
885 uint16_t nested_size; 882 uint16_t nested_size;
886 const struct GNUNET_MessageHeader *nested_msg; 883 const struct GNUNET_MessageHeader *nested_msg;
887 884
888 whole_size = ntohs (mh->size); 885 whole_size = ntohs(mh->size);
889 GNUNET_assert (whole_size >= base_size); 886 GNUNET_assert(whole_size >= base_size);
890 nested_size = whole_size - base_size; 887 nested_size = whole_size - base_size;
891 if (0 == nested_size) 888 if (0 == nested_size)
892 return NULL; 889 return NULL;
893 if (nested_size < sizeof (struct GNUNET_MessageHeader)) 890 if (nested_size < sizeof(struct GNUNET_MessageHeader))
894 { 891 {
895 GNUNET_break_op (0); 892 GNUNET_break_op(0);
896 return NULL; 893 return NULL;
897 } 894 }
898 nested_msg = (const struct GNUNET_MessageHeader *) ((char *) mh + base_size); 895 nested_msg = (const struct GNUNET_MessageHeader *)((char *)mh + base_size);
899 if (ntohs (nested_msg->size) != nested_size) 896 if (ntohs(nested_msg->size) != nested_size)
900 { 897 {
901 GNUNET_break_op (0); 898 GNUNET_break_op(0);
902 return NULL; 899 return NULL;
903 } 900 }
904 return nested_msg; 901 return nested_msg;
905} 902}
906 903
@@ -913,53 +910,53 @@ GNUNET_MQ_extract_nested_mh_ (const struct GNUNET_MessageHeader *mh,
913 * @param ev queued envelope to cancel 910 * @param ev queued envelope to cancel
914 */ 911 */
915void 912void
916GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev) 913GNUNET_MQ_send_cancel(struct GNUNET_MQ_Envelope *ev)
917{ 914{
918 struct GNUNET_MQ_Handle *mq = ev->parent_queue; 915 struct GNUNET_MQ_Handle *mq = ev->parent_queue;
919 916
920 GNUNET_assert (NULL != mq); 917 GNUNET_assert(NULL != mq);
921 GNUNET_assert (NULL != mq->cancel_impl); 918 GNUNET_assert(NULL != mq->cancel_impl);
922 919
923 mq->evacuate_called = GNUNET_NO; 920 mq->evacuate_called = GNUNET_NO;
924 921
925 if (mq->current_envelope == ev) 922 if (mq->current_envelope == ev)
926 {
927 /* complex case, we already started with transmitting
928 the message using the callbacks. */
929 GNUNET_assert (GNUNET_NO == mq->in_flight);
930 GNUNET_assert (0 < mq->queue_length);
931 mq->queue_length--;
932 mq->cancel_impl (mq, mq->impl_state);
933 /* continue sending the next message, if any */
934 mq->current_envelope = mq->envelope_head;
935 if (NULL != mq->current_envelope)
936 { 923 {
937 GNUNET_CONTAINER_DLL_remove (mq->envelope_head, 924 /* complex case, we already started with transmitting
938 mq->envelope_tail, 925 the message using the callbacks. */
939 mq->current_envelope); 926 GNUNET_assert(GNUNET_NO == mq->in_flight);
940 927 GNUNET_assert(0 < mq->queue_length);
941 LOG (GNUNET_ERROR_TYPE_DEBUG, 928 mq->queue_length--;
942 "sending canceled message of type %u queue\n", 929 mq->cancel_impl(mq, mq->impl_state);
943 ntohs (ev->mh->type)); 930 /* continue sending the next message, if any */
944 931 mq->current_envelope = mq->envelope_head;
945 mq->send_impl (mq, mq->current_envelope->mh, mq->impl_state); 932 if (NULL != mq->current_envelope)
933 {
934 GNUNET_CONTAINER_DLL_remove(mq->envelope_head,
935 mq->envelope_tail,
936 mq->current_envelope);
937
938 LOG(GNUNET_ERROR_TYPE_DEBUG,
939 "sending canceled message of type %u queue\n",
940 ntohs(ev->mh->type));
941
942 mq->send_impl(mq, mq->current_envelope->mh, mq->impl_state);
943 }
946 } 944 }
947 }
948 else 945 else
949 { 946 {
950 /* simple case, message is still waiting in the queue */ 947 /* simple case, message is still waiting in the queue */
951 GNUNET_CONTAINER_DLL_remove (mq->envelope_head, mq->envelope_tail, ev); 948 GNUNET_CONTAINER_DLL_remove(mq->envelope_head, mq->envelope_tail, ev);
952 GNUNET_assert (0 < mq->queue_length); 949 GNUNET_assert(0 < mq->queue_length);
953 mq->queue_length--; 950 mq->queue_length--;
954 } 951 }
955 952
956 if (GNUNET_YES != mq->evacuate_called) 953 if (GNUNET_YES != mq->evacuate_called)
957 { 954 {
958 ev->parent_queue = NULL; 955 ev->parent_queue = NULL;
959 ev->mh = NULL; 956 ev->mh = NULL;
960 /* also frees ev */ 957 /* also frees ev */
961 GNUNET_free (ev); 958 GNUNET_free(ev);
962 } 959 }
963} 960}
964 961
965 962
@@ -971,7 +968,7 @@ GNUNET_MQ_send_cancel (struct GNUNET_MQ_Envelope *ev)
971 * @return the current envelope 968 * @return the current envelope
972 */ 969 */
973struct GNUNET_MQ_Envelope * 970struct GNUNET_MQ_Envelope *
974GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq) 971GNUNET_MQ_get_current_envelope(struct GNUNET_MQ_Handle *mq)
975{ 972{
976 return mq->current_envelope; 973 return mq->current_envelope;
977} 974}
@@ -984,7 +981,7 @@ GNUNET_MQ_get_current_envelope (struct GNUNET_MQ_Handle *mq)
984 * @return the last envelope in the queue 981 * @return the last envelope in the queue
985 */ 982 */
986struct GNUNET_MQ_Envelope * 983struct GNUNET_MQ_Envelope *
987GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq) 984GNUNET_MQ_get_last_envelope(struct GNUNET_MQ_Handle *mq)
988{ 985{
989 if (NULL != mq->envelope_tail) 986 if (NULL != mq->envelope_tail)
990 return mq->envelope_tail; 987 return mq->envelope_tail;
@@ -1002,8 +999,8 @@ GNUNET_MQ_get_last_envelope (struct GNUNET_MQ_Handle *mq)
1002 * @param pp priorities and preferences to apply 999 * @param pp priorities and preferences to apply
1003 */ 1000 */
1004void 1001void
1005GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env, 1002GNUNET_MQ_env_set_options(struct GNUNET_MQ_Envelope *env,
1006 enum GNUNET_MQ_PriorityPreferences pp) 1003 enum GNUNET_MQ_PriorityPreferences pp)
1007{ 1004{
1008 env->priority = pp; 1005 env->priority = pp;
1009 env->have_custom_options = GNUNET_YES; 1006 env->have_custom_options = GNUNET_YES;
@@ -1017,7 +1014,7 @@ GNUNET_MQ_env_set_options (struct GNUNET_MQ_Envelope *env,
1017 * @return priorities and preferences to apply for @a env 1014 * @return priorities and preferences to apply for @a env
1018 */ 1015 */
1019enum GNUNET_MQ_PriorityPreferences 1016enum GNUNET_MQ_PriorityPreferences
1020GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env) 1017GNUNET_MQ_env_get_options(struct GNUNET_MQ_Envelope *env)
1021{ 1018{
1022 struct GNUNET_MQ_Handle *mq = env->parent_queue; 1019 struct GNUNET_MQ_Handle *mq = env->parent_queue;
1023 1020
@@ -1038,12 +1035,12 @@ GNUNET_MQ_env_get_options (struct GNUNET_MQ_Envelope *env)
1038 * @return combined priority and preferences to use 1035 * @return combined priority and preferences to use
1039 */ 1036 */
1040enum GNUNET_MQ_PriorityPreferences 1037enum GNUNET_MQ_PriorityPreferences
1041GNUNET_MQ_env_combine_options (enum GNUNET_MQ_PriorityPreferences p1, 1038GNUNET_MQ_env_combine_options(enum GNUNET_MQ_PriorityPreferences p1,
1042 enum GNUNET_MQ_PriorityPreferences p2) 1039 enum GNUNET_MQ_PriorityPreferences p2)
1043{ 1040{
1044 enum GNUNET_MQ_PriorityPreferences ret; 1041 enum GNUNET_MQ_PriorityPreferences ret;
1045 1042
1046 ret = GNUNET_MAX (p1 & GNUNET_MQ_PRIORITY_MASK, p2 & GNUNET_MQ_PRIORITY_MASK); 1043 ret = GNUNET_MAX(p1 & GNUNET_MQ_PRIORITY_MASK, p2 & GNUNET_MQ_PRIORITY_MASK);
1047 ret |= ((p1 & GNUNET_MQ_PREF_UNRELIABLE) & (p2 & GNUNET_MQ_PREF_UNRELIABLE)); 1044 ret |= ((p1 & GNUNET_MQ_PREF_UNRELIABLE) & (p2 & GNUNET_MQ_PREF_UNRELIABLE));
1048 ret |= 1045 ret |=
1049 ((p1 & GNUNET_MQ_PREF_LOW_LATENCY) | (p2 & GNUNET_MQ_PREF_LOW_LATENCY)); 1046 ((p1 & GNUNET_MQ_PREF_LOW_LATENCY) | (p2 & GNUNET_MQ_PREF_LOW_LATENCY));
@@ -1063,8 +1060,8 @@ GNUNET_MQ_env_combine_options (enum GNUNET_MQ_PriorityPreferences p1,
1063 * @param pp priorities and preferences to apply 1060 * @param pp priorities and preferences to apply
1064 */ 1061 */
1065void 1062void
1066GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq, 1063GNUNET_MQ_set_options(struct GNUNET_MQ_Handle *mq,
1067 enum GNUNET_MQ_PriorityPreferences pp) 1064 enum GNUNET_MQ_PriorityPreferences pp)
1068{ 1065{
1069 mq->priority = pp; 1066 mq->priority = pp;
1070} 1067}
@@ -1077,7 +1074,7 @@ GNUNET_MQ_set_options (struct GNUNET_MQ_Handle *mq,
1077 * @return message contained in the envelope 1074 * @return message contained in the envelope
1078 */ 1075 */
1079const struct GNUNET_MessageHeader * 1076const struct GNUNET_MessageHeader *
1080GNUNET_MQ_env_get_msg (const struct GNUNET_MQ_Envelope *env) 1077GNUNET_MQ_env_get_msg(const struct GNUNET_MQ_Envelope *env)
1081{ 1078{
1082 return env->mh; 1079 return env->mh;
1083} 1080}
@@ -1090,7 +1087,7 @@ GNUNET_MQ_env_get_msg (const struct GNUNET_MQ_Envelope *env)
1090 * @return next one, or NULL 1087 * @return next one, or NULL
1091 */ 1088 */
1092const struct GNUNET_MQ_Envelope * 1089const struct GNUNET_MQ_Envelope *
1093GNUNET_MQ_env_next (const struct GNUNET_MQ_Envelope *env) 1090GNUNET_MQ_env_next(const struct GNUNET_MQ_Envelope *env)
1094{ 1091{
1095 return env->next; 1092 return env->next;
1096} 1093}
@@ -1106,17 +1103,17 @@ GNUNET_MQ_env_next (const struct GNUNET_MQ_Envelope *env)
1106 * @return handle for #GNUNET_MQ_destroy_notify_cancel(). 1103 * @return handle for #GNUNET_MQ_destroy_notify_cancel().
1107 */ 1104 */
1108struct GNUNET_MQ_DestroyNotificationHandle * 1105struct GNUNET_MQ_DestroyNotificationHandle *
1109GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq, 1106GNUNET_MQ_destroy_notify(struct GNUNET_MQ_Handle *mq,
1110 GNUNET_SCHEDULER_TaskCallback cb, 1107 GNUNET_SCHEDULER_TaskCallback cb,
1111 void *cb_cls) 1108 void *cb_cls)
1112{ 1109{
1113 struct GNUNET_MQ_DestroyNotificationHandle *dnh; 1110 struct GNUNET_MQ_DestroyNotificationHandle *dnh;
1114 1111
1115 dnh = GNUNET_new (struct GNUNET_MQ_DestroyNotificationHandle); 1112 dnh = GNUNET_new(struct GNUNET_MQ_DestroyNotificationHandle);
1116 dnh->mq = mq; 1113 dnh->mq = mq;
1117 dnh->cb = cb; 1114 dnh->cb = cb;
1118 dnh->cb_cls = cb_cls; 1115 dnh->cb_cls = cb_cls;
1119 GNUNET_CONTAINER_DLL_insert (mq->dnh_head, mq->dnh_tail, dnh); 1116 GNUNET_CONTAINER_DLL_insert(mq->dnh_head, mq->dnh_tail, dnh);
1120 return dnh; 1117 return dnh;
1121} 1118}
1122 1119
@@ -1127,13 +1124,13 @@ GNUNET_MQ_destroy_notify (struct GNUNET_MQ_Handle *mq,
1127 * @param dnh handle for registration to cancel 1124 * @param dnh handle for registration to cancel
1128 */ 1125 */
1129void 1126void
1130GNUNET_MQ_destroy_notify_cancel ( 1127GNUNET_MQ_destroy_notify_cancel(
1131 struct GNUNET_MQ_DestroyNotificationHandle *dnh) 1128 struct GNUNET_MQ_DestroyNotificationHandle *dnh)
1132{ 1129{
1133 struct GNUNET_MQ_Handle *mq = dnh->mq; 1130 struct GNUNET_MQ_Handle *mq = dnh->mq;
1134 1131
1135 GNUNET_CONTAINER_DLL_remove (mq->dnh_head, mq->dnh_tail, dnh); 1132 GNUNET_CONTAINER_DLL_remove(mq->dnh_head, mq->dnh_tail, dnh);
1136 GNUNET_free (dnh); 1133 GNUNET_free(dnh);
1137} 1134}
1138 1135
1139 1136
@@ -1150,12 +1147,11 @@ GNUNET_MQ_destroy_notify_cancel (
1150 * @param[in|out] env element to insert at the tail 1147 * @param[in|out] env element to insert at the tail
1151 */ 1148 */
1152void 1149void
1153GNUNET_MQ_dll_insert_head (struct GNUNET_MQ_Envelope **env_head, 1150GNUNET_MQ_dll_insert_head(struct GNUNET_MQ_Envelope **env_head,
1154 struct GNUNET_MQ_Envelope **env_tail, 1151 struct GNUNET_MQ_Envelope **env_tail,
1155 struct GNUNET_MQ_Envelope *env) 1152 struct GNUNET_MQ_Envelope *env)
1156{ 1153{
1157 1154 GNUNET_CONTAINER_DLL_insert(*env_head, *env_tail, env);
1158 GNUNET_CONTAINER_DLL_insert (*env_head, *env_tail, env);
1159} 1155}
1160 1156
1161 1157
@@ -1172,11 +1168,11 @@ GNUNET_MQ_dll_insert_head (struct GNUNET_MQ_Envelope **env_head,
1172 * @param[in|out] env element to insert at the tail 1168 * @param[in|out] env element to insert at the tail
1173 */ 1169 */
1174void 1170void
1175GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head, 1171GNUNET_MQ_dll_insert_tail(struct GNUNET_MQ_Envelope **env_head,
1176 struct GNUNET_MQ_Envelope **env_tail, 1172 struct GNUNET_MQ_Envelope **env_tail,
1177 struct GNUNET_MQ_Envelope *env) 1173 struct GNUNET_MQ_Envelope *env)
1178{ 1174{
1179 GNUNET_CONTAINER_DLL_insert_tail (*env_head, *env_tail, env); 1175 GNUNET_CONTAINER_DLL_insert_tail(*env_head, *env_tail, env);
1180} 1176}
1181 1177
1182 1178
@@ -1193,11 +1189,11 @@ GNUNET_MQ_dll_insert_tail (struct GNUNET_MQ_Envelope **env_head,
1193 * @param[in|out] env element to remove from the DLL 1189 * @param[in|out] env element to remove from the DLL
1194 */ 1190 */
1195void 1191void
1196GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head, 1192GNUNET_MQ_dll_remove(struct GNUNET_MQ_Envelope **env_head,
1197 struct GNUNET_MQ_Envelope **env_tail, 1193 struct GNUNET_MQ_Envelope **env_tail,
1198 struct GNUNET_MQ_Envelope *env) 1194 struct GNUNET_MQ_Envelope *env)
1199{ 1195{
1200 GNUNET_CONTAINER_DLL_remove (*env_head, *env_tail, env); 1196 GNUNET_CONTAINER_DLL_remove(*env_head, *env_tail, env);
1201} 1197}
1202 1198
1203 1199
@@ -1212,7 +1208,7 @@ GNUNET_MQ_dll_remove (struct GNUNET_MQ_Envelope **env_head,
1212 * Needs to be freed with #GNUNET_free. 1208 * Needs to be freed with #GNUNET_free.
1213 */ 1209 */
1214struct GNUNET_MQ_MessageHandler * 1210struct GNUNET_MQ_MessageHandler *
1215GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers) 1211GNUNET_MQ_copy_handlers(const struct GNUNET_MQ_MessageHandler *handlers)
1216{ 1212{
1217 struct GNUNET_MQ_MessageHandler *copy; 1213 struct GNUNET_MQ_MessageHandler *copy;
1218 unsigned int count; 1214 unsigned int count;
@@ -1220,11 +1216,11 @@ GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1220 if (NULL == handlers) 1216 if (NULL == handlers)
1221 return NULL; 1217 return NULL;
1222 1218
1223 count = GNUNET_MQ_count_handlers (handlers); 1219 count = GNUNET_MQ_count_handlers(handlers);
1224 copy = GNUNET_new_array (count + 1, struct GNUNET_MQ_MessageHandler); 1220 copy = GNUNET_new_array(count + 1, struct GNUNET_MQ_MessageHandler);
1225 GNUNET_memcpy (copy, 1221 GNUNET_memcpy(copy,
1226 handlers, 1222 handlers,
1227 count * sizeof (struct GNUNET_MQ_MessageHandler)); 1223 count * sizeof(struct GNUNET_MQ_MessageHandler));
1228 return copy; 1224 return copy;
1229} 1225}
1230 1226
@@ -1242,25 +1238,25 @@ GNUNET_MQ_copy_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1242 * Needs to be freed with #GNUNET_free. 1238 * Needs to be freed with #GNUNET_free.
1243 */ 1239 */
1244struct GNUNET_MQ_MessageHandler * 1240struct GNUNET_MQ_MessageHandler *
1245GNUNET_MQ_copy_handlers2 (const struct GNUNET_MQ_MessageHandler *handlers, 1241GNUNET_MQ_copy_handlers2(const struct GNUNET_MQ_MessageHandler *handlers,
1246 GNUNET_MQ_MessageCallback agpl_handler, 1242 GNUNET_MQ_MessageCallback agpl_handler,
1247 void *agpl_cls) 1243 void *agpl_cls)
1248{ 1244{
1249 struct GNUNET_MQ_MessageHandler *copy; 1245 struct GNUNET_MQ_MessageHandler *copy;
1250 unsigned int count; 1246 unsigned int count;
1251 1247
1252 if (NULL == handlers) 1248 if (NULL == handlers)
1253 return NULL; 1249 return NULL;
1254 count = GNUNET_MQ_count_handlers (handlers); 1250 count = GNUNET_MQ_count_handlers(handlers);
1255 copy = GNUNET_new_array (count + 2, struct GNUNET_MQ_MessageHandler); 1251 copy = GNUNET_new_array(count + 2, struct GNUNET_MQ_MessageHandler);
1256 GNUNET_memcpy (copy, 1252 GNUNET_memcpy(copy,
1257 handlers, 1253 handlers,
1258 count * sizeof (struct GNUNET_MQ_MessageHandler)); 1254 count * sizeof(struct GNUNET_MQ_MessageHandler));
1259 copy[count].mv = NULL; 1255 copy[count].mv = NULL;
1260 copy[count].cb = agpl_handler; 1256 copy[count].cb = agpl_handler;
1261 copy[count].cls = agpl_cls; 1257 copy[count].cls = agpl_cls;
1262 copy[count].type = GNUNET_MESSAGE_TYPE_REQUEST_AGPL; 1258 copy[count].type = GNUNET_MESSAGE_TYPE_REQUEST_AGPL;
1263 copy[count].expected_size = sizeof (struct GNUNET_MessageHeader); 1259 copy[count].expected_size = sizeof(struct GNUNET_MessageHeader);
1264 return copy; 1260 return copy;
1265} 1261}
1266 1262
@@ -1272,7 +1268,7 @@ GNUNET_MQ_copy_handlers2 (const struct GNUNET_MQ_MessageHandler *handlers,
1272 * @return The number of handlers in the array. 1268 * @return The number of handlers in the array.
1273 */ 1269 */
1274unsigned int 1270unsigned int
1275GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers) 1271GNUNET_MQ_count_handlers(const struct GNUNET_MQ_MessageHandler *handlers)
1276{ 1272{
1277 unsigned int i; 1273 unsigned int i;
1278 1274
@@ -1293,19 +1289,23 @@ GNUNET_MQ_count_handlers (const struct GNUNET_MQ_MessageHandler *handlers)
1293 * @return a string or NULL if invalid 1289 * @return a string or NULL if invalid
1294 */ 1290 */
1295const char * 1291const char *
1296GNUNET_MQ_preference_to_string (enum GNUNET_MQ_PreferenceKind type) 1292GNUNET_MQ_preference_to_string(enum GNUNET_MQ_PreferenceKind type)
1297{ 1293{
1298 switch (type) 1294 switch (type)
1299 { 1295 {
1300 case GNUNET_MQ_PREFERENCE_NONE: 1296 case GNUNET_MQ_PREFERENCE_NONE:
1301 return "NONE"; 1297 return "NONE";
1302 case GNUNET_MQ_PREFERENCE_BANDWIDTH: 1298
1303 return "BANDWIDTH"; 1299 case GNUNET_MQ_PREFERENCE_BANDWIDTH:
1304 case GNUNET_MQ_PREFERENCE_LATENCY: 1300 return "BANDWIDTH";
1305 return "LATENCY"; 1301
1306 case GNUNET_MQ_PREFERENCE_RELIABILITY: 1302 case GNUNET_MQ_PREFERENCE_LATENCY:
1307 return "RELIABILITY"; 1303 return "LATENCY";
1308 }; 1304
1305 case GNUNET_MQ_PREFERENCE_RELIABILITY:
1306 return "RELIABILITY";
1307 }
1308 ;
1309 return NULL; 1309 return NULL;
1310} 1310}
1311 1311
diff --git a/src/util/mst.c b/src/util/mst.c
index bc52f2356..4ccf4988f 100644
--- a/src/util/mst.c
+++ b/src/util/mst.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/mst.c 22 * @file util/mst.c
@@ -34,15 +34,13 @@
34#define ALIGN_FACTOR 8 34#define ALIGN_FACTOR 8
35#endif 35#endif
36 36
37#define LOG(kind,...) GNUNET_log_from (kind, "util-mst", __VA_ARGS__) 37#define LOG(kind, ...) GNUNET_log_from(kind, "util-mst", __VA_ARGS__)
38 38
39 39
40/** 40/**
41 * Handle to a message stream tokenizer. 41 * Handle to a message stream tokenizer.
42 */ 42 */
43struct GNUNET_MessageStreamTokenizer 43struct GNUNET_MessageStreamTokenizer {
44{
45
46 /** 44 /**
47 * Function to call on completed messages. 45 * Function to call on completed messages.
48 */ 46 */
@@ -72,7 +70,6 @@ struct GNUNET_MessageStreamTokenizer
72 * Beginning of the buffer. Typed like this to force alignment. 70 * Beginning of the buffer. Typed like this to force alignment.
73 */ 71 */
74 struct GNUNET_MessageHeader *hdr; 72 struct GNUNET_MessageHeader *hdr;
75
76}; 73};
77 74
78 75
@@ -84,13 +81,13 @@ struct GNUNET_MessageStreamTokenizer
84 * @return handle to tokenizer 81 * @return handle to tokenizer
85 */ 82 */
86struct GNUNET_MessageStreamTokenizer * 83struct GNUNET_MessageStreamTokenizer *
87GNUNET_MST_create (GNUNET_MessageTokenizerCallback cb, 84GNUNET_MST_create(GNUNET_MessageTokenizerCallback cb,
88 void *cb_cls) 85 void *cb_cls)
89{ 86{
90 struct GNUNET_MessageStreamTokenizer *ret; 87 struct GNUNET_MessageStreamTokenizer *ret;
91 88
92 ret = GNUNET_new (struct GNUNET_MessageStreamTokenizer); 89 ret = GNUNET_new(struct GNUNET_MessageStreamTokenizer);
93 ret->hdr = GNUNET_malloc (GNUNET_MIN_MESSAGE_SIZE); 90 ret->hdr = GNUNET_malloc(GNUNET_MIN_MESSAGE_SIZE);
94 ret->curr_buf = GNUNET_MIN_MESSAGE_SIZE; 91 ret->curr_buf = GNUNET_MIN_MESSAGE_SIZE;
95 ret->cb = cb; 92 ret->cb = cb;
96 ret->cb_cls = cb_cls; 93 ret->cb_cls = cb_cls;
@@ -113,11 +110,11 @@ GNUNET_MST_create (GNUNET_MessageTokenizerCallback cb,
113 * #GNUNET_SYSERR if the data stream is corrupt 110 * #GNUNET_SYSERR if the data stream is corrupt
114 */ 111 */
115int 112int
116GNUNET_MST_from_buffer (struct GNUNET_MessageStreamTokenizer *mst, 113GNUNET_MST_from_buffer(struct GNUNET_MessageStreamTokenizer *mst,
117 const char *buf, 114 const char *buf,
118 size_t size, 115 size_t size,
119 int purge, 116 int purge,
120 int one_shot) 117 int one_shot)
121{ 118{
122 const struct GNUNET_MessageHeader *hdr; 119 const struct GNUNET_MessageHeader *hdr;
123 size_t delta; 120 size_t delta;
@@ -128,203 +125,203 @@ GNUNET_MST_from_buffer (struct GNUNET_MessageStreamTokenizer *mst,
128 int ret; 125 int ret;
129 int cbret; 126 int cbret;
130 127
131 GNUNET_assert (mst->off <= mst->pos); 128 GNUNET_assert(mst->off <= mst->pos);
132 GNUNET_assert (mst->pos <= mst->curr_buf); 129 GNUNET_assert(mst->pos <= mst->curr_buf);
133 LOG (GNUNET_ERROR_TYPE_DEBUG, 130 LOG(GNUNET_ERROR_TYPE_DEBUG,
134 "MST receives %u bytes with %u bytes already in private buffer\n", 131 "MST receives %u bytes with %u bytes already in private buffer\n",
135 (unsigned int) size, 132 (unsigned int)size,
136 (unsigned int) (mst->pos - mst->off)); 133 (unsigned int)(mst->pos - mst->off));
137 ret = GNUNET_OK; 134 ret = GNUNET_OK;
138 ibuf = (char *) mst->hdr; 135 ibuf = (char *)mst->hdr;
139 while (mst->pos > 0) 136 while (mst->pos > 0)
140 {
141do_align:
142 GNUNET_assert (mst->pos >= mst->off);
143 if ((mst->curr_buf - mst->off < sizeof (struct GNUNET_MessageHeader)) ||
144 (0 != (mst->off % ALIGN_FACTOR)))
145 {
146 /* need to align or need more space */
147 mst->pos -= mst->off;
148 memmove (ibuf,
149 &ibuf[mst->off],
150 mst->pos);
151 mst->off = 0;
152 }
153 if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
154 {
155 delta
156 = GNUNET_MIN (sizeof (struct GNUNET_MessageHeader)
157 - (mst->pos - mst->off),
158 size);
159 GNUNET_memcpy (&ibuf[mst->pos],
160 buf,
161 delta);
162 mst->pos += delta;
163 buf += delta;
164 size -= delta;
165 }
166 if (mst->pos - mst->off < sizeof (struct GNUNET_MessageHeader))
167 {
168 if (purge)
169 {
170 mst->off = 0;
171 mst->pos = 0;
172 }
173 return GNUNET_OK;
174 }
175 hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
176 want = ntohs (hdr->size);
177 if (want < sizeof (struct GNUNET_MessageHeader))
178 {
179 GNUNET_break_op (0);
180 return GNUNET_SYSERR;
181 }
182 if ( (mst->curr_buf - mst->off < want) &&
183 (mst->off > 0) )
184 {
185 /* can get more space by moving */
186 mst->pos -= mst->off;
187 memmove (ibuf,
188 &ibuf[mst->off],
189 mst->pos);
190 mst->off = 0;
191 }
192 if (mst->curr_buf < want)
193 {
194 /* need to get more space by growing buffer */
195 GNUNET_assert (0 == mst->off);
196 mst->hdr = GNUNET_realloc (mst->hdr,
197 want);
198 ibuf = (char *) mst->hdr;
199 mst->curr_buf = want;
200 }
201 hdr = (const struct GNUNET_MessageHeader *) &ibuf[mst->off];
202 if (mst->pos - mst->off < want)
203 {
204 delta = GNUNET_MIN (want - (mst->pos - mst->off),
205 size);
206 GNUNET_assert (mst->pos + delta <= mst->curr_buf);
207 GNUNET_memcpy (&ibuf[mst->pos],
208 buf,
209 delta);
210 mst->pos += delta;
211 buf += delta;
212 size -= delta;
213 }
214 if (mst->pos - mst->off < want)
215 {
216 if (purge)
217 {
218 mst->off = 0;
219 mst->pos = 0;
220 }
221 return GNUNET_OK;
222 }
223 if (one_shot == GNUNET_SYSERR)
224 { 137 {
225 /* cannot call callback again, but return value saying that 138do_align:
226 * we have another full message in the buffer */ 139 GNUNET_assert(mst->pos >= mst->off);
227 ret = GNUNET_NO; 140 if ((mst->curr_buf - mst->off < sizeof(struct GNUNET_MessageHeader)) ||
228 goto copy; 141 (0 != (mst->off % ALIGN_FACTOR)))
229 } 142 {
230 if (one_shot == GNUNET_YES) 143 /* need to align or need more space */
231 one_shot = GNUNET_SYSERR; 144 mst->pos -= mst->off;
232 mst->off += want; 145 memmove(ibuf,
233 if (GNUNET_OK != 146 &ibuf[mst->off],
234 (cbret = mst->cb (mst->cb_cls, 147 mst->pos);
235 hdr))) 148 mst->off = 0;
236 { 149 }
237 if (GNUNET_SYSERR == cbret) 150 if (mst->pos - mst->off < sizeof(struct GNUNET_MessageHeader))
238 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 151 {
239 "Failure processing message of type %u and size %u\n", 152 delta
240 ntohs (hdr->type), 153 = GNUNET_MIN(sizeof(struct GNUNET_MessageHeader)
241 ntohs (hdr->size)); 154 - (mst->pos - mst->off),
242 return GNUNET_SYSERR; 155 size);
243 } 156 GNUNET_memcpy(&ibuf[mst->pos],
244 if (mst->off == mst->pos) 157 buf,
245 { 158 delta);
246 /* reset to beginning of buffer, it's free right now! */ 159 mst->pos += delta;
247 mst->off = 0; 160 buf += delta;
248 mst->pos = 0; 161 size -= delta;
249 } 162 }
250 } 163 if (mst->pos - mst->off < sizeof(struct GNUNET_MessageHeader))
251 GNUNET_assert (0 == mst->pos); 164 {
252 while (size > 0) 165 if (purge)
253 { 166 {
254 LOG (GNUNET_ERROR_TYPE_DEBUG, 167 mst->off = 0;
255 "Server-mst has %u bytes left in inbound buffer\n", 168 mst->pos = 0;
256 (unsigned int) size); 169 }
257 if (size < sizeof (struct GNUNET_MessageHeader)) 170 return GNUNET_OK;
258 break; 171 }
259 offset = (unsigned long) buf; 172 hdr = (const struct GNUNET_MessageHeader *)&ibuf[mst->off];
260 need_align = (0 != (offset % ALIGN_FACTOR)) ? GNUNET_YES : GNUNET_NO; 173 want = ntohs(hdr->size);
261 if (GNUNET_NO == need_align) 174 if (want < sizeof(struct GNUNET_MessageHeader))
262 { 175 {
263 /* can try to do zero-copy and process directly from original buffer */ 176 GNUNET_break_op(0);
264 hdr = (const struct GNUNET_MessageHeader *) buf; 177 return GNUNET_SYSERR;
265 want = ntohs (hdr->size); 178 }
266 if (want < sizeof (struct GNUNET_MessageHeader)) 179 if ((mst->curr_buf - mst->off < want) &&
267 { 180 (mst->off > 0))
268 GNUNET_break_op (0); 181 {
269 mst->off = 0; 182 /* can get more space by moving */
270 return GNUNET_SYSERR; 183 mst->pos -= mst->off;
271 } 184 memmove(ibuf,
272 if (size < want) 185 &ibuf[mst->off],
273 break; /* or not: buffer incomplete, so copy to private buffer... */ 186 mst->pos);
187 mst->off = 0;
188 }
189 if (mst->curr_buf < want)
190 {
191 /* need to get more space by growing buffer */
192 GNUNET_assert(0 == mst->off);
193 mst->hdr = GNUNET_realloc(mst->hdr,
194 want);
195 ibuf = (char *)mst->hdr;
196 mst->curr_buf = want;
197 }
198 hdr = (const struct GNUNET_MessageHeader *)&ibuf[mst->off];
199 if (mst->pos - mst->off < want)
200 {
201 delta = GNUNET_MIN(want - (mst->pos - mst->off),
202 size);
203 GNUNET_assert(mst->pos + delta <= mst->curr_buf);
204 GNUNET_memcpy(&ibuf[mst->pos],
205 buf,
206 delta);
207 mst->pos += delta;
208 buf += delta;
209 size -= delta;
210 }
211 if (mst->pos - mst->off < want)
212 {
213 if (purge)
214 {
215 mst->off = 0;
216 mst->pos = 0;
217 }
218 return GNUNET_OK;
219 }
274 if (one_shot == GNUNET_SYSERR) 220 if (one_shot == GNUNET_SYSERR)
275 { 221 {
276 /* cannot call callback again, but return value saying that 222 /* cannot call callback again, but return value saying that
277 * we have another full message in the buffer */ 223 * we have another full message in the buffer */
278 ret = GNUNET_NO; 224 ret = GNUNET_NO;
279 goto copy; 225 goto copy;
280 } 226 }
281 if (one_shot == GNUNET_YES) 227 if (one_shot == GNUNET_YES)
282 one_shot = GNUNET_SYSERR; 228 one_shot = GNUNET_SYSERR;
229 mst->off += want;
283 if (GNUNET_OK != 230 if (GNUNET_OK !=
284 (cbret = mst->cb (mst->cb_cls, 231 (cbret = mst->cb(mst->cb_cls,
285 hdr))) 232 hdr)))
286 { 233 {
287 if (GNUNET_SYSERR == cbret) 234 if (GNUNET_SYSERR == cbret)
288 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 235 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
289 "Failure processing message of type %u and size %u\n", 236 "Failure processing message of type %u and size %u\n",
290 ntohs (hdr->type), 237 ntohs(hdr->type),
291 ntohs (hdr->size)); 238 ntohs(hdr->size));
292 return GNUNET_SYSERR; 239 return GNUNET_SYSERR;
293 } 240 }
294 buf += want; 241 if (mst->off == mst->pos)
295 size -= want; 242 {
243 /* reset to beginning of buffer, it's free right now! */
244 mst->off = 0;
245 mst->pos = 0;
246 }
296 } 247 }
297 else 248 GNUNET_assert(0 == mst->pos);
249 while (size > 0)
298 { 250 {
299 /* need to copy to private buffer to align; 251 LOG(GNUNET_ERROR_TYPE_DEBUG,
300 * yes, we go a bit more spagetti than usual here */ 252 "Server-mst has %u bytes left in inbound buffer\n",
301 goto do_align; 253 (unsigned int)size);
254 if (size < sizeof(struct GNUNET_MessageHeader))
255 break;
256 offset = (unsigned long)buf;
257 need_align = (0 != (offset % ALIGN_FACTOR)) ? GNUNET_YES : GNUNET_NO;
258 if (GNUNET_NO == need_align)
259 {
260 /* can try to do zero-copy and process directly from original buffer */
261 hdr = (const struct GNUNET_MessageHeader *)buf;
262 want = ntohs(hdr->size);
263 if (want < sizeof(struct GNUNET_MessageHeader))
264 {
265 GNUNET_break_op(0);
266 mst->off = 0;
267 return GNUNET_SYSERR;
268 }
269 if (size < want)
270 break; /* or not: buffer incomplete, so copy to private buffer... */
271 if (one_shot == GNUNET_SYSERR)
272 {
273 /* cannot call callback again, but return value saying that
274 * we have another full message in the buffer */
275 ret = GNUNET_NO;
276 goto copy;
277 }
278 if (one_shot == GNUNET_YES)
279 one_shot = GNUNET_SYSERR;
280 if (GNUNET_OK !=
281 (cbret = mst->cb(mst->cb_cls,
282 hdr)))
283 {
284 if (GNUNET_SYSERR == cbret)
285 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
286 "Failure processing message of type %u and size %u\n",
287 ntohs(hdr->type),
288 ntohs(hdr->size));
289 return GNUNET_SYSERR;
290 }
291 buf += want;
292 size -= want;
293 }
294 else
295 {
296 /* need to copy to private buffer to align;
297 * yes, we go a bit more spagetti than usual here */
298 goto do_align;
299 }
302 } 300 }
303 }
304copy: 301copy:
305 if ((size > 0) && (!purge)) 302 if ((size > 0) && (!purge))
306 {
307 if (size + mst->pos > mst->curr_buf)
308 { 303 {
309 mst->hdr = GNUNET_realloc (mst->hdr, 304 if (size + mst->pos > mst->curr_buf)
310 size + mst->pos); 305 {
311 ibuf = (char *) mst->hdr; 306 mst->hdr = GNUNET_realloc(mst->hdr,
312 mst->curr_buf = size + mst->pos; 307 size + mst->pos);
308 ibuf = (char *)mst->hdr;
309 mst->curr_buf = size + mst->pos;
310 }
311 GNUNET_assert(size + mst->pos <= mst->curr_buf);
312 GNUNET_memcpy(&ibuf[mst->pos],
313 buf,
314 size);
315 mst->pos += size;
313 } 316 }
314 GNUNET_assert (size + mst->pos <= mst->curr_buf);
315 GNUNET_memcpy (&ibuf[mst->pos],
316 buf,
317 size);
318 mst->pos += size;
319 }
320 if (purge) 317 if (purge)
321 { 318 {
322 mst->off = 0; 319 mst->off = 0;
323 mst->pos = 0; 320 mst->pos = 0;
324 } 321 }
325 LOG (GNUNET_ERROR_TYPE_DEBUG, 322 LOG(GNUNET_ERROR_TYPE_DEBUG,
326 "Server-mst leaves %u bytes in private buffer\n", 323 "Server-mst leaves %u bytes in private buffer\n",
327 (unsigned int) (mst->pos - mst->off)); 324 (unsigned int)(mst->pos - mst->off));
328 return ret; 325 return ret;
329} 326}
330 327
@@ -344,40 +341,40 @@ copy:
344 * #GNUNET_SYSERR if the data stream is corrupt 341 * #GNUNET_SYSERR if the data stream is corrupt
345 */ 342 */
346int 343int
347GNUNET_MST_read (struct GNUNET_MessageStreamTokenizer *mst, 344GNUNET_MST_read(struct GNUNET_MessageStreamTokenizer *mst,
348 struct GNUNET_NETWORK_Handle *sock, 345 struct GNUNET_NETWORK_Handle *sock,
349 int purge, 346 int purge,
350 int one_shot) 347 int one_shot)
351{ 348{
352 ssize_t ret; 349 ssize_t ret;
353 size_t left; 350 size_t left;
354 char *buf; 351 char *buf;
355 352
356 left = mst->curr_buf - mst->pos; 353 left = mst->curr_buf - mst->pos;
357 buf = (char *) mst->hdr; 354 buf = (char *)mst->hdr;
358 ret = GNUNET_NETWORK_socket_recv (sock, 355 ret = GNUNET_NETWORK_socket_recv(sock,
359 &buf[mst->pos], 356 &buf[mst->pos],
360 left); 357 left);
361 if (-1 == ret) 358 if (-1 == ret)
362 { 359 {
363 if ( (EAGAIN == errno) || 360 if ((EAGAIN == errno) ||
364 (EINTR == errno) ) 361 (EINTR == errno))
365 return GNUNET_OK; 362 return GNUNET_OK;
366 GNUNET_log_strerror (GNUNET_ERROR_TYPE_INFO, 363 GNUNET_log_strerror(GNUNET_ERROR_TYPE_INFO,
367 "recv"); 364 "recv");
368 return GNUNET_SYSERR; 365 return GNUNET_SYSERR;
369 } 366 }
370 if (0 == ret) 367 if (0 == ret)
371 { 368 {
372 /* other side closed connection, treat as error */ 369 /* other side closed connection, treat as error */
373 return GNUNET_SYSERR; 370 return GNUNET_SYSERR;
374 } 371 }
375 mst->pos += ret; 372 mst->pos += ret;
376 return GNUNET_MST_from_buffer (mst, 373 return GNUNET_MST_from_buffer(mst,
377 NULL, 374 NULL,
378 0, 375 0,
379 purge, 376 purge,
380 one_shot); 377 one_shot);
381} 378}
382 379
383 380
@@ -393,14 +390,14 @@ GNUNET_MST_read (struct GNUNET_MessageStreamTokenizer *mst,
393 * #GNUNET_SYSERR if the data stream is corrupt 390 * #GNUNET_SYSERR if the data stream is corrupt
394 */ 391 */
395int 392int
396GNUNET_MST_next (struct GNUNET_MessageStreamTokenizer *mst, 393GNUNET_MST_next(struct GNUNET_MessageStreamTokenizer *mst,
397 int one_shot) 394 int one_shot)
398{ 395{
399 return GNUNET_MST_from_buffer (mst, 396 return GNUNET_MST_from_buffer(mst,
400 NULL, 397 NULL,
401 0, 398 0,
402 GNUNET_NO, 399 GNUNET_NO,
403 one_shot); 400 one_shot);
404} 401}
405 402
406 403
@@ -410,10 +407,10 @@ GNUNET_MST_next (struct GNUNET_MessageStreamTokenizer *mst,
410 * @param mst tokenizer to destroy 407 * @param mst tokenizer to destroy
411 */ 408 */
412void 409void
413GNUNET_MST_destroy (struct GNUNET_MessageStreamTokenizer *mst) 410GNUNET_MST_destroy(struct GNUNET_MessageStreamTokenizer *mst)
414{ 411{
415 GNUNET_free (mst->hdr); 412 GNUNET_free(mst->hdr);
416 GNUNET_free (mst); 413 GNUNET_free(mst);
417} 414}
418 415
419 416
diff --git a/src/util/nc.c b/src/util/nc.c
index 7a3c5877e..ab7ef122d 100644
--- a/src/util/nc.c
+++ b/src/util/nc.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/nc.c 22 * @file util/nc.c
@@ -28,15 +28,13 @@
28#include "platform.h" 28#include "platform.h"
29#include "gnunet_util_lib.h" 29#include "gnunet_util_lib.h"
30 30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-nc", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-nc", __VA_ARGS__)
32 32
33 33
34/** 34/**
35 * Lists of subscribers we manage for notifications. 35 * Lists of subscribers we manage for notifications.
36 */ 36 */
37struct SubscriberList 37struct SubscriberList {
38{
39
40 /** 38 /**
41 * This is a doubly linked list. 39 * This is a doubly linked list.
42 */ 40 */
@@ -57,12 +55,11 @@ struct SubscriberList
57 * the MQ's destruction. 55 * the MQ's destruction.
58 */ 56 */
59 struct GNUNET_MQ_DestroyNotificationHandle *mq_nh; 57 struct GNUNET_MQ_DestroyNotificationHandle *mq_nh;
60 58
61 /** 59 /**
62 * Message queue for the subscriber. 60 * Message queue for the subscriber.
63 */ 61 */
64 struct GNUNET_MQ_Handle *mq; 62 struct GNUNET_MQ_Handle *mq;
65
66}; 63};
67 64
68 65
@@ -74,9 +71,7 @@ struct SubscriberList
74 * (notification) messages are queued up until the subscriber is able to 71 * (notification) messages are queued up until the subscriber is able to
75 * read them. 72 * read them.
76 */ 73 */
77struct GNUNET_NotificationContext 74struct GNUNET_NotificationContext {
78{
79
80 /** 75 /**
81 * Head of list of subscribers receiving notifications. 76 * Head of list of subscribers receiving notifications.
82 */ 77 */
@@ -91,7 +86,6 @@ struct GNUNET_NotificationContext
91 * Maximum number of optional messages to queue per subscriber. 86 * Maximum number of optional messages to queue per subscriber.
92 */ 87 */
93 unsigned int queue_length; 88 unsigned int queue_length;
94
95}; 89};
96 90
97 91
@@ -101,15 +95,15 @@ struct GNUNET_NotificationContext
101 * @param cls our `struct SubscriberList *` 95 * @param cls our `struct SubscriberList *`
102 */ 96 */
103static void 97static void
104handle_mq_destroy (void *cls) 98handle_mq_destroy(void *cls)
105{ 99{
106 struct SubscriberList *pos = cls; 100 struct SubscriberList *pos = cls;
107 struct GNUNET_NotificationContext *nc = pos->nc; 101 struct GNUNET_NotificationContext *nc = pos->nc;
108 102
109 GNUNET_CONTAINER_DLL_remove (nc->subscribers_head, 103 GNUNET_CONTAINER_DLL_remove(nc->subscribers_head,
110 nc->subscribers_tail, 104 nc->subscribers_tail,
111 pos); 105 pos);
112 GNUNET_free (pos); 106 GNUNET_free(pos);
113} 107}
114 108
115 109
@@ -122,11 +116,11 @@ handle_mq_destroy (void *cls)
122 * @return handle to the notification context 116 * @return handle to the notification context
123 */ 117 */
124struct GNUNET_NotificationContext * 118struct GNUNET_NotificationContext *
125GNUNET_notification_context_create (unsigned int queue_length) 119GNUNET_notification_context_create(unsigned int queue_length)
126{ 120{
127 struct GNUNET_NotificationContext *nc; 121 struct GNUNET_NotificationContext *nc;
128 122
129 nc = GNUNET_new (struct GNUNET_NotificationContext); 123 nc = GNUNET_new(struct GNUNET_NotificationContext);
130 nc->queue_length = queue_length; 124 nc->queue_length = queue_length;
131 return nc; 125 return nc;
132} 126}
@@ -138,19 +132,19 @@ GNUNET_notification_context_create (unsigned int queue_length)
138 * @param nc context to destroy. 132 * @param nc context to destroy.
139 */ 133 */
140void 134void
141GNUNET_notification_context_destroy (struct GNUNET_NotificationContext *nc) 135GNUNET_notification_context_destroy(struct GNUNET_NotificationContext *nc)
142{ 136{
143 struct SubscriberList *pos; 137 struct SubscriberList *pos;
144 138
145 while (NULL != (pos = nc->subscribers_head)) 139 while (NULL != (pos = nc->subscribers_head))
146 { 140 {
147 GNUNET_CONTAINER_DLL_remove (nc->subscribers_head, 141 GNUNET_CONTAINER_DLL_remove(nc->subscribers_head,
148 nc->subscribers_tail, 142 nc->subscribers_tail,
149 pos); 143 pos);
150 GNUNET_MQ_destroy_notify_cancel (pos->mq_nh); 144 GNUNET_MQ_destroy_notify_cancel(pos->mq_nh);
151 GNUNET_free (pos); 145 GNUNET_free(pos);
152 } 146 }
153 GNUNET_free (nc); 147 GNUNET_free(nc);
154} 148}
155 149
156 150
@@ -161,23 +155,24 @@ GNUNET_notification_context_destroy (struct GNUNET_NotificationContext *nc)
161 * @param mq message queue add 155 * @param mq message queue add
162 */ 156 */
163void 157void
164GNUNET_notification_context_add (struct GNUNET_NotificationContext *nc, 158GNUNET_notification_context_add(struct GNUNET_NotificationContext *nc,
165 struct GNUNET_MQ_Handle *mq) 159 struct GNUNET_MQ_Handle *mq)
166{ 160{
167 struct SubscriberList *cl; 161 struct SubscriberList *cl;
168 162
169 for (cl = nc->subscribers_head; NULL != cl; cl = cl->next) 163 for (cl = nc->subscribers_head; NULL != cl; cl = cl->next)
170 if (cl->mq == mq) 164 if (cl->mq == mq)
171 return; /* already present */ 165 return;
172 cl = GNUNET_new (struct SubscriberList); 166 /* already present */
173 GNUNET_CONTAINER_DLL_insert (nc->subscribers_head, 167 cl = GNUNET_new(struct SubscriberList);
174 nc->subscribers_tail, 168 GNUNET_CONTAINER_DLL_insert(nc->subscribers_head,
175 cl); 169 nc->subscribers_tail,
170 cl);
176 cl->nc = nc; 171 cl->nc = nc;
177 cl->mq = mq; 172 cl->mq = mq;
178 cl->mq_nh = GNUNET_MQ_destroy_notify (cl->mq, 173 cl->mq_nh = GNUNET_MQ_destroy_notify(cl->mq,
179 &handle_mq_destroy, 174 &handle_mq_destroy,
180 cl); 175 cl);
181} 176}
182 177
183 178
@@ -189,22 +184,22 @@ GNUNET_notification_context_add (struct GNUNET_NotificationContext *nc,
189 * @param can_drop can this message be dropped due to queue length limitations 184 * @param can_drop can this message be dropped due to queue length limitations
190 */ 185 */
191void 186void
192GNUNET_notification_context_broadcast (struct GNUNET_NotificationContext *nc, 187GNUNET_notification_context_broadcast(struct GNUNET_NotificationContext *nc,
193 const struct GNUNET_MessageHeader *msg, 188 const struct GNUNET_MessageHeader *msg,
194 int can_drop) 189 int can_drop)
195{ 190{
196 struct SubscriberList *pos; 191 struct SubscriberList *pos;
197 struct GNUNET_MQ_Envelope *env; 192 struct GNUNET_MQ_Envelope *env;
198 193
199 for (pos = nc->subscribers_head; NULL != pos; pos = pos->next) 194 for (pos = nc->subscribers_head; NULL != pos; pos = pos->next)
200 { 195 {
201 if ( (GNUNET_YES == can_drop) && 196 if ((GNUNET_YES == can_drop) &&
202 (GNUNET_MQ_get_length (pos->mq) > nc->queue_length) ) 197 (GNUNET_MQ_get_length(pos->mq) > nc->queue_length))
203 continue; 198 continue;
204 env = GNUNET_MQ_msg_copy (msg); 199 env = GNUNET_MQ_msg_copy(msg);
205 GNUNET_MQ_send (pos->mq, 200 GNUNET_MQ_send(pos->mq,
206 env); 201 env);
207 } 202 }
208} 203}
209 204
210 205
@@ -215,7 +210,7 @@ GNUNET_notification_context_broadcast (struct GNUNET_NotificationContext *nc,
215 * @return number of current subscribers 210 * @return number of current subscribers
216 */ 211 */
217unsigned int 212unsigned int
218GNUNET_notification_context_get_size (struct GNUNET_NotificationContext *nc) 213GNUNET_notification_context_get_size(struct GNUNET_NotificationContext *nc)
219{ 214{
220 unsigned int num; 215 unsigned int num;
221 struct SubscriberList *pos; 216 struct SubscriberList *pos;
diff --git a/src/util/network.c b/src/util/network.c
index 2c16fe8c9..9eff6b96e 100644
--- a/src/util/network.c
+++ b/src/util/network.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/network.c 22 * @file util/network.c
@@ -28,9 +28,9 @@
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29#include "disk.h" 29#include "disk.h"
30 30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-network", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-network", __VA_ARGS__)
32#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-network", syscall, filename) 32#define LOG_STRERROR_FILE(kind, syscall, filename) GNUNET_log_from_strerror_file(kind, "util-network", syscall, filename)
33#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-network", syscall) 33#define LOG_STRERROR(kind, syscall) GNUNET_log_from_strerror(kind, "util-network", syscall)
34 34
35#define DEBUG_NETWORK GNUNET_EXTRA_LOGGING 35#define DEBUG_NETWORK GNUNET_EXTRA_LOGGING
36 36
@@ -43,8 +43,7 @@
43/** 43/**
44 * @brief handle to a socket 44 * @brief handle to a socket
45 */ 45 */
46struct GNUNET_NETWORK_Handle 46struct GNUNET_NETWORK_Handle {
47{
48#ifndef MINGW 47#ifndef MINGW
49 int fd; 48 int fd;
50#else 49#else
@@ -70,7 +69,6 @@ struct GNUNET_NETWORK_Handle
70 * Address we were bound to, or NULL. 69 * Address we were bound to, or NULL.
71 */ 70 */
72 struct sockaddr *addr; 71 struct sockaddr *addr;
73
74}; 72};
75 73
76 74
@@ -81,7 +79,7 @@ struct GNUNET_NETWORK_Handle
81 * @return #GNUNET_OK if the PF is supported 79 * @return #GNUNET_OK if the PF is supported
82 */ 80 */
83int 81int
84GNUNET_NETWORK_test_pf (int pf) 82GNUNET_NETWORK_test_pf(int pf)
85{ 83{
86 static int cache_v4 = -1; 84 static int cache_v4 = -1;
87 static int cache_v6 = -1; 85 static int cache_v6 = -1;
@@ -90,56 +88,60 @@ GNUNET_NETWORK_test_pf (int pf)
90 int ret; 88 int ret;
91 89
92 switch (pf) 90 switch (pf)
93 { 91 {
94 case PF_INET: 92 case PF_INET:
95 if (-1 != cache_v4) 93 if (-1 != cache_v4)
96 return cache_v4; 94 return cache_v4;
97 break; 95 break;
98 case PF_INET6: 96
99 if (-1 != cache_v6) 97 case PF_INET6:
100 return cache_v6; 98 if (-1 != cache_v6)
101 break; 99 return cache_v6;
100 break;
101
102#ifdef PF_UNIX 102#ifdef PF_UNIX
103 case PF_UNIX: 103 case PF_UNIX:
104 if (-1 != cache_un) 104 if (-1 != cache_un)
105 return cache_un; 105 return cache_un;
106 break; 106 break;
107#endif 107#endif
108 } 108 }
109 s = socket (pf, SOCK_STREAM, 0); 109 s = socket(pf, SOCK_STREAM, 0);
110 if (-1 == s) 110 if (-1 == s)
111 {
112 if (EAFNOSUPPORT != errno)
113 { 111 {
114 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, 112 if (EAFNOSUPPORT != errno)
115 "socket"); 113 {
116 return GNUNET_SYSERR; 114 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING,
115 "socket");
116 return GNUNET_SYSERR;
117 }
118 ret = GNUNET_NO;
117 } 119 }
118 ret = GNUNET_NO;
119 }
120 else 120 else
121 { 121 {
122#if WINDOWS 122#if WINDOWS
123 closesocket (s); 123 closesocket(s);
124#else 124#else
125 close (s); 125 close(s);
126#endif 126#endif
127 ret = GNUNET_OK; 127 ret = GNUNET_OK;
128 } 128 }
129 switch (pf) 129 switch (pf)
130 { 130 {
131 case PF_INET: 131 case PF_INET:
132 cache_v4 = ret; 132 cache_v4 = ret;
133 break; 133 break;
134 case PF_INET6: 134
135 cache_v6 = ret; 135 case PF_INET6:
136 break; 136 cache_v6 = ret;
137 break;
138
137#ifdef PF_UNIX 139#ifdef PF_UNIX
138 case PF_UNIX: 140 case PF_UNIX:
139 cache_un = ret; 141 cache_un = ret;
140 break; 142 break;
141#endif 143#endif
142 } 144 }
143 return ret; 145 return ret;
144} 146}
145 147
@@ -154,7 +156,7 @@ GNUNET_NETWORK_test_pf (int pf)
154 * @return shortened unixpath, NULL on error 156 * @return shortened unixpath, NULL on error
155 */ 157 */
156char * 158char *
157GNUNET_NETWORK_shorten_unixpath (char *unixpath) 159GNUNET_NETWORK_shorten_unixpath(char *unixpath)
158{ 160{
159 struct sockaddr_un dummy; 161 struct sockaddr_un dummy;
160 size_t slen; 162 size_t slen;
@@ -163,26 +165,26 @@ GNUNET_NETWORK_shorten_unixpath (char *unixpath)
163 struct GNUNET_CRYPTO_HashAsciiEncoded ae; 165 struct GNUNET_CRYPTO_HashAsciiEncoded ae;
164 size_t upm; 166 size_t upm;
165 167
166 upm = sizeof (dummy.sun_path); 168 upm = sizeof(dummy.sun_path);
167 slen = strlen (unixpath); 169 slen = strlen(unixpath);
168 if (slen < upm) 170 if (slen < upm)
169 return unixpath; /* no shortening required */ 171 return unixpath; /* no shortening required */
170 GNUNET_CRYPTO_hash (unixpath, slen, &sh); 172 GNUNET_CRYPTO_hash(unixpath, slen, &sh);
171 while (16 + strlen (unixpath) >= upm) 173 while (16 + strlen(unixpath) >= upm)
172 {
173 if (NULL == (end = strrchr (unixpath, '/')))
174 { 174 {
175 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 175 if (NULL == (end = strrchr(unixpath, '/')))
176 _("Unable to shorten unix path `%s' while keeping name unique\n"), 176 {
177 unixpath); 177 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
178 GNUNET_free (unixpath); 178 _("Unable to shorten unix path `%s' while keeping name unique\n"),
179 return NULL; 179 unixpath);
180 GNUNET_free(unixpath);
181 return NULL;
182 }
183 *end = '\0';
180 } 184 }
181 *end = '\0'; 185 GNUNET_CRYPTO_hash_to_enc(&sh, &ae);
182 }
183 GNUNET_CRYPTO_hash_to_enc (&sh, &ae);
184 ae.encoding[16] = '\0'; 186 ae.encoding[16] = '\0';
185 strcat (unixpath, (char *) ae.encoding); 187 strcat(unixpath, (char *)ae.encoding);
186 return unixpath; 188 return unixpath;
187} 189}
188 190
@@ -198,50 +200,50 @@ GNUNET_NETWORK_shorten_unixpath (char *unixpath)
198 * @param un unix domain socket address to check 200 * @param un unix domain socket address to check
199 */ 201 */
200void 202void
201GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un) 203GNUNET_NETWORK_unix_precheck(const struct sockaddr_un *un)
202{ 204{
203 int s; 205 int s;
204 int eno; 206 int eno;
205 struct stat sbuf; 207 struct stat sbuf;
206 int ret; 208 int ret;
207 209
208 s = socket (AF_UNIX, SOCK_STREAM, 0); 210 s = socket(AF_UNIX, SOCK_STREAM, 0);
209 if (-1 == s) 211 if (-1 == s)
210 { 212 {
211 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, 213 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING,
212 "Failed to open AF_UNIX socket"); 214 "Failed to open AF_UNIX socket");
213 return; 215 return;
214 } 216 }
215 ret = connect (s, 217 ret = connect(s,
216 (struct sockaddr *) un, 218 (struct sockaddr *)un,
217 sizeof (struct sockaddr_un)); 219 sizeof(struct sockaddr_un));
218 eno = errno; 220 eno = errno;
219 GNUNET_break (0 == close (s)); 221 GNUNET_break(0 == close(s));
220 if (0 == ret) 222 if (0 == ret)
221 return; /* another process is listening, do not remove! */ 223 return; /* another process is listening, do not remove! */
222 if (ECONNREFUSED != eno) 224 if (ECONNREFUSED != eno)
223 return; /* some other error, likely "no such file or directory" -- all well */ 225 return; /* some other error, likely "no such file or directory" -- all well */
224 /* should unlink, but sanity checks first */ 226 /* should unlink, but sanity checks first */
225 if (0 != stat (un->sun_path, 227 if (0 != stat(un->sun_path,
226 &sbuf)) 228 &sbuf))
227 return; /* failed to 'stat', likely does not exist after all */ 229 return; /* failed to 'stat', likely does not exist after all */
228 if (S_IFSOCK != (S_IFMT & sbuf.st_mode)) 230 if (S_IFSOCK != (S_IFMT & sbuf.st_mode))
229 return; /* refuse to unlink anything except sockets */ 231 return; /* refuse to unlink anything except sockets */
230 /* finally, really unlink */ 232 /* finally, really unlink */
231 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 233 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
232 "Removing left-over `%s' from previous exeuction\n", 234 "Removing left-over `%s' from previous exeuction\n",
233 un->sun_path); 235 un->sun_path);
234 if (0 != unlink (un->sun_path)) 236 if (0 != unlink(un->sun_path))
235 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, 237 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING,
236 "unlink", 238 "unlink",
237 un->sun_path); 239 un->sun_path);
238} 240}
239#endif 241#endif
240 242
241 243
242 244
243#ifndef FD_COPY 245#ifndef FD_COPY
244#define FD_COPY(s, d) do { GNUNET_memcpy ((d), (s), sizeof (fd_set)); } while (0) 246#define FD_COPY(s, d) do { GNUNET_memcpy((d), (s), sizeof(fd_set)); } while (0)
245#endif 247#endif
246 248
247 249
@@ -253,51 +255,49 @@ GNUNET_NETWORK_unix_precheck (const struct sockaddr_un *un)
253 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 255 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
254 */ 256 */
255int 257int
256GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd, 258GNUNET_NETWORK_socket_set_blocking(struct GNUNET_NETWORK_Handle *fd,
257 int doBlock) 259 int doBlock)
258{ 260{
259
260#if MINGW 261#if MINGW
261 u_long mode; 262 u_long mode;
262 263
263 mode = !doBlock; 264 mode = !doBlock;
264 if (SOCKET_ERROR == 265 if (SOCKET_ERROR ==
265 ioctlsocket (fd->fd, 266 ioctlsocket(fd->fd,
266 FIONBIO, 267 FIONBIO,
267 &mode)) 268 &mode))
268 269
269 { 270 {
270 SetErrnoFromWinsockError (WSAGetLastError ()); 271 SetErrnoFromWinsockError(WSAGetLastError());
271 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 272 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
272 "ioctlsocket"); 273 "ioctlsocket");
273 return GNUNET_SYSERR; 274 return GNUNET_SYSERR;
274 } 275 }
275 return GNUNET_OK; 276 return GNUNET_OK;
276
277#else 277#else
278 /* not MINGW */ 278 /* not MINGW */
279 int flags = fcntl (fd->fd, F_GETFL); 279 int flags = fcntl(fd->fd, F_GETFL);
280 280
281 if (flags == -1) 281 if (flags == -1)
282 { 282 {
283 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 283 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
284 "fcntl"); 284 "fcntl");
285 return GNUNET_SYSERR; 285 return GNUNET_SYSERR;
286 } 286 }
287 if (doBlock) 287 if (doBlock)
288 flags &= ~O_NONBLOCK; 288 flags &= ~O_NONBLOCK;
289 289
290 else 290 else
291 flags |= O_NONBLOCK; 291 flags |= O_NONBLOCK;
292 if (0 != fcntl (fd->fd, 292 if (0 != fcntl(fd->fd,
293 F_SETFL, 293 F_SETFL,
294 flags)) 294 flags))
295 295
296 { 296 {
297 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 297 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
298 "fcntl"); 298 "fcntl");
299 return GNUNET_SYSERR; 299 return GNUNET_SYSERR;
300 } 300 }
301 return GNUNET_OK; 301 return GNUNET_OK;
302#endif 302#endif
303} 303}
@@ -311,27 +311,27 @@ GNUNET_NETWORK_socket_set_blocking (struct GNUNET_NETWORK_Handle *fd,
311 * @warning Not implemented on Windows 311 * @warning Not implemented on Windows
312 */ 312 */
313static int 313static int
314socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h) 314socket_set_inheritable(const struct GNUNET_NETWORK_Handle *h)
315{ 315{
316#ifndef MINGW 316#ifndef MINGW
317 int i; 317 int i;
318 i = fcntl (h->fd, F_GETFD); 318 i = fcntl(h->fd, F_GETFD);
319 if (i < 0) 319 if (i < 0)
320 return GNUNET_SYSERR; 320 return GNUNET_SYSERR;
321 if (i == (i | FD_CLOEXEC)) 321 if (i == (i | FD_CLOEXEC))
322 return GNUNET_OK; 322 return GNUNET_OK;
323 i |= FD_CLOEXEC; 323 i |= FD_CLOEXEC;
324 if (fcntl (h->fd, F_SETFD, i) < 0) 324 if (fcntl(h->fd, F_SETFD, i) < 0)
325 return GNUNET_SYSERR; 325 return GNUNET_SYSERR;
326#else 326#else
327 BOOL b; 327 BOOL b;
328 SetLastError (0); 328 SetLastError(0);
329 b = SetHandleInformation ((HANDLE) h->fd, HANDLE_FLAG_INHERIT, 0); 329 b = SetHandleInformation((HANDLE)h->fd, HANDLE_FLAG_INHERIT, 0);
330 if (!b) 330 if (!b)
331 { 331 {
332 SetErrnoFromWinsockError (WSAGetLastError ()); 332 SetErrnoFromWinsockError(WSAGetLastError());
333 return GNUNET_SYSERR; 333 return GNUNET_SYSERR;
334 } 334 }
335#endif 335#endif
336 return GNUNET_OK; 336 return GNUNET_OK;
337} 337}
@@ -344,14 +344,14 @@ socket_set_inheritable (const struct GNUNET_NETWORK_Handle *h)
344 * @param h the socket to make non-delaying 344 * @param h the socket to make non-delaying
345 */ 345 */
346static int 346static int
347socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h) 347socket_set_nosigpipe(const struct GNUNET_NETWORK_Handle *h)
348{ 348{
349 int abs_value = 1; 349 int abs_value = 1;
350 350
351 if (0 != 351 if (0 !=
352 setsockopt (h->fd, SOL_SOCKET, SO_NOSIGPIPE, 352 setsockopt(h->fd, SOL_SOCKET, SO_NOSIGPIPE,
353 (const void *) &abs_value, 353 (const void *)&abs_value,
354 sizeof (abs_value))) 354 sizeof(abs_value)))
355 return GNUNET_SYSERR; 355 return GNUNET_SYSERR;
356 return GNUNET_OK; 356 return GNUNET_OK;
357} 357}
@@ -366,29 +366,29 @@ socket_set_nosigpipe (const struct GNUNET_NETWORK_Handle *h)
366 * @param h the socket to make non-delaying 366 * @param h the socket to make non-delaying
367 */ 367 */
368static void 368static void
369socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h) 369socket_set_nodelay(const struct GNUNET_NETWORK_Handle *h)
370{ 370{
371#ifndef WINDOWS 371#ifndef WINDOWS
372 int value = 1; 372 int value = 1;
373 373
374 if (0 != 374 if (0 !=
375 setsockopt (h->fd, 375 setsockopt(h->fd,
376 IPPROTO_TCP, 376 IPPROTO_TCP,
377 TCP_NODELAY, 377 TCP_NODELAY,
378 &value, sizeof (value))) 378 &value, sizeof(value)))
379 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 379 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
380 "setsockopt"); 380 "setsockopt");
381#else 381#else
382 const char *abs_value = "1"; 382 const char *abs_value = "1";
383 383
384 if (0 != 384 if (0 !=
385 setsockopt (h->fd, 385 setsockopt(h->fd,
386 IPPROTO_TCP, 386 IPPROTO_TCP,
387 TCP_NODELAY, 387 TCP_NODELAY,
388 (const void *) abs_value, 388 (const void *)abs_value,
389 sizeof (abs_value))) 389 sizeof(abs_value)))
390 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 390 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
391 "setsockopt"); 391 "setsockopt");
392#endif 392#endif
393} 393}
394 394
@@ -406,60 +406,60 @@ socket_set_nodelay (const struct GNUNET_NETWORK_Handle *h)
406 * failed and the handle was destroyed 406 * failed and the handle was destroyed
407 */ 407 */
408static int 408static int
409initialize_network_handle (struct GNUNET_NETWORK_Handle *h, 409initialize_network_handle(struct GNUNET_NETWORK_Handle *h,
410 int af, 410 int af,
411 int type) 411 int type)
412{ 412{
413 int eno; 413 int eno;
414 414
415 h->af = af; 415 h->af = af;
416 h->type = type; 416 h->type = type;
417 if (h->fd == INVALID_SOCKET) 417 if (h->fd == INVALID_SOCKET)
418 { 418 {
419#ifdef MINGW 419#ifdef MINGW
420 SetErrnoFromWinsockError (WSAGetLastError ()); 420 SetErrnoFromWinsockError(WSAGetLastError());
421#endif 421#endif
422 eno = errno; 422 eno = errno;
423 GNUNET_free (h); 423 GNUNET_free(h);
424 errno = eno; 424 errno = eno;
425 return GNUNET_SYSERR; 425 return GNUNET_SYSERR;
426 } 426 }
427#ifndef MINGW 427#ifndef MINGW
428 if (h->fd >= FD_SETSIZE) 428 if (h->fd >= FD_SETSIZE)
429 { 429 {
430 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h)); 430 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(h));
431 errno = EMFILE; 431 errno = EMFILE;
432 return GNUNET_SYSERR; 432 return GNUNET_SYSERR;
433 } 433 }
434#endif 434#endif
435 if (GNUNET_OK != socket_set_inheritable (h)) 435 if (GNUNET_OK != socket_set_inheritable(h))
436 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 436 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
437 "socket_set_inheritable"); 437 "socket_set_inheritable");
438 438
439 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_set_blocking (h, GNUNET_NO)) 439 if (GNUNET_SYSERR == GNUNET_NETWORK_socket_set_blocking(h, GNUNET_NO))
440 { 440 {
441 eno = errno; 441 eno = errno;
442 GNUNET_break (0); 442 GNUNET_break(0);
443 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h)); 443 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(h));
444 errno = eno; 444 errno = eno;
445 return GNUNET_SYSERR; 445 return GNUNET_SYSERR;
446 } 446 }
447#ifdef DARWIN 447#ifdef DARWIN
448 if (GNUNET_SYSERR == socket_set_nosigpipe (h)) 448 if (GNUNET_SYSERR == socket_set_nosigpipe(h))
449 { 449 {
450 eno = errno; 450 eno = errno;
451 GNUNET_break (0); 451 GNUNET_break(0);
452 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (h)); 452 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(h));
453 errno = eno; 453 errno = eno;
454 return GNUNET_SYSERR; 454 return GNUNET_SYSERR;
455 } 455 }
456#endif 456#endif
457 if ( (type == SOCK_STREAM) 457 if ((type == SOCK_STREAM)
458#ifdef AF_UNIX 458#ifdef AF_UNIX
459 && (af != AF_UNIX) 459 && (af != AF_UNIX)
460#endif 460#endif
461 ) 461 )
462 socket_set_nodelay (h); 462 socket_set_nodelay(h);
463 return GNUNET_OK; 463 return GNUNET_OK;
464} 464}
465 465
@@ -473,47 +473,47 @@ initialize_network_handle (struct GNUNET_NETWORK_Handle *h,
473 * @return client socket 473 * @return client socket
474 */ 474 */
475struct GNUNET_NETWORK_Handle * 475struct GNUNET_NETWORK_Handle *
476GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc, 476GNUNET_NETWORK_socket_accept(const struct GNUNET_NETWORK_Handle *desc,
477 struct sockaddr *address, 477 struct sockaddr *address,
478 socklen_t *address_len) 478 socklen_t *address_len)
479{ 479{
480 struct GNUNET_NETWORK_Handle *ret; 480 struct GNUNET_NETWORK_Handle *ret;
481 int eno; 481 int eno;
482 482
483 ret = GNUNET_new (struct GNUNET_NETWORK_Handle); 483 ret = GNUNET_new(struct GNUNET_NETWORK_Handle);
484#if DEBUG_NETWORK 484#if DEBUG_NETWORK
485 { 485 {
486 struct sockaddr_storage name; 486 struct sockaddr_storage name;
487 socklen_t namelen = sizeof (name); 487 socklen_t namelen = sizeof(name);
488 488
489 int gsn = getsockname (desc->fd, 489 int gsn = getsockname(desc->fd,
490 (struct sockaddr *) &name, 490 (struct sockaddr *)&name,
491 &namelen); 491 &namelen);
492 492
493 if (0 == gsn) 493 if (0 == gsn)
494 LOG (GNUNET_ERROR_TYPE_DEBUG, 494 LOG(GNUNET_ERROR_TYPE_DEBUG,
495 "Accepting connection on `%s'\n", 495 "Accepting connection on `%s'\n",
496 GNUNET_a2s ((const struct sockaddr *) &name, 496 GNUNET_a2s((const struct sockaddr *)&name,
497 namelen)); 497 namelen));
498 } 498 }
499#endif 499#endif
500 ret->fd = accept (desc->fd, 500 ret->fd = accept(desc->fd,
501 address, 501 address,
502 address_len); 502 address_len);
503 if (-1 == ret->fd) 503 if (-1 == ret->fd)
504 { 504 {
505 eno = errno; 505 eno = errno;
506 GNUNET_free (ret); 506 GNUNET_free(ret);
507 errno = eno; 507 errno = eno;
508 return NULL; 508 return NULL;
509 } 509 }
510 if (GNUNET_OK != 510 if (GNUNET_OK !=
511 initialize_network_handle (ret, 511 initialize_network_handle(ret,
512 (NULL != address) ? address->sa_family : desc->af, 512 (NULL != address) ? address->sa_family : desc->af,
513 SOCK_STREAM)) 513 SOCK_STREAM))
514 { 514 {
515 return NULL; 515 return NULL;
516 } 516 }
517 return ret; 517 return ret;
518} 518}
519 519
@@ -527,9 +527,9 @@ GNUNET_NETWORK_socket_accept (const struct GNUNET_NETWORK_Handle *desc,
527 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 527 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
528 */ 528 */
529int 529int
530GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc, 530GNUNET_NETWORK_socket_bind(struct GNUNET_NETWORK_Handle *desc,
531 const struct sockaddr *address, 531 const struct sockaddr *address,
532 socklen_t address_len) 532 socklen_t address_len)
533{ 533{
534 int ret; 534 int ret;
535 535
@@ -539,63 +539,63 @@ GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
539 const int on = 1; 539 const int on = 1;
540 540
541 if (AF_INET6 == desc->af) 541 if (AF_INET6 == desc->af)
542 if (setsockopt (desc->fd, 542 if (setsockopt(desc->fd,
543 IPPROTO_IPV6, 543 IPPROTO_IPV6,
544 IPV6_V6ONLY, 544 IPV6_V6ONLY,
545 (const void *) &on, 545 (const void *)&on,
546 sizeof (on))) 546 sizeof(on)))
547 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, 547 LOG_STRERROR(GNUNET_ERROR_TYPE_DEBUG,
548 "setsockopt"); 548 "setsockopt");
549 } 549 }
550#endif 550#endif
551#endif 551#endif
552#ifndef WINDOWS 552#ifndef WINDOWS
553 if (AF_UNIX == address->sa_family) 553 if (AF_UNIX == address->sa_family)
554 GNUNET_NETWORK_unix_precheck ((const struct sockaddr_un *) address); 554 GNUNET_NETWORK_unix_precheck((const struct sockaddr_un *)address);
555 { 555 {
556 const int on = 1; 556 const int on = 1;
557 557
558 /* This is required here for TCP sockets, but only on UNIX */ 558 /* This is required here for TCP sockets, but only on UNIX */
559 if ( (SOCK_STREAM == desc->type) && 559 if ((SOCK_STREAM == desc->type) &&
560 (0 != setsockopt (desc->fd, 560 (0 != setsockopt(desc->fd,
561 SOL_SOCKET, 561 SOL_SOCKET,
562 SO_REUSEADDR, 562 SO_REUSEADDR,
563 &on, sizeof (on)))) 563 &on, sizeof(on))))
564 LOG_STRERROR (GNUNET_ERROR_TYPE_DEBUG, 564 LOG_STRERROR(GNUNET_ERROR_TYPE_DEBUG,
565 "setsockopt"); 565 "setsockopt");
566 } 566 }
567 { 567 {
568 /* set permissions of newly created non-abstract UNIX domain socket to 568 /* set permissions of newly created non-abstract UNIX domain socket to
569 "user-only"; applications can choose to relax this later */ 569 "user-only"; applications can choose to relax this later */
570 mode_t old_mask = 0; /* assigned to make compiler happy */ 570 mode_t old_mask = 0; /* assigned to make compiler happy */
571 const struct sockaddr_un *un = (const struct sockaddr_un *) address; 571 const struct sockaddr_un *un = (const struct sockaddr_un *)address;
572 int not_abstract = 0; 572 int not_abstract = 0;
573 573
574 if ((AF_UNIX == address->sa_family) 574 if ((AF_UNIX == address->sa_family)
575 && ('\0' != un->sun_path[0]) ) /* Not an abstract socket */ 575 && ('\0' != un->sun_path[0])) /* Not an abstract socket */
576 not_abstract = 1; 576 not_abstract = 1;
577 if (not_abstract) 577 if (not_abstract)
578 old_mask = umask (S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IROTH | S_IXOTH); 578 old_mask = umask(S_IWGRP | S_IRGRP | S_IXGRP | S_IWOTH | S_IROTH | S_IXOTH);
579#endif 579#endif
580 580
581 ret = bind (desc->fd, 581 ret = bind(desc->fd,
582 address, 582 address,
583 address_len); 583 address_len);
584 584
585#ifndef WINDOWS 585#ifndef WINDOWS
586 if (not_abstract) 586 if (not_abstract)
587 (void) umask (old_mask); 587 (void)umask(old_mask);
588 } 588}
589#endif 589#endif
590#ifdef MINGW 590#ifdef MINGW
591 if (SOCKET_ERROR == ret) 591 if (SOCKET_ERROR == ret)
592 SetErrnoFromWinsockError (WSAGetLastError ()); 592 SetErrnoFromWinsockError(WSAGetLastError());
593#endif 593#endif
594 if (0 != ret) 594 if (0 != ret)
595 return GNUNET_SYSERR; 595 return GNUNET_SYSERR;
596#ifndef MINGW 596#ifndef MINGW
597 desc->addr = GNUNET_malloc (address_len); 597 desc->addr = GNUNET_malloc(address_len);
598 GNUNET_memcpy (desc->addr, address, address_len); 598 GNUNET_memcpy(desc->addr, address, address_len);
599 desc->addrlen = address_len; 599 desc->addrlen = address_len;
600#endif 600#endif
601 return GNUNET_OK; 601 return GNUNET_OK;
@@ -609,72 +609,73 @@ GNUNET_NETWORK_socket_bind (struct GNUNET_NETWORK_Handle *desc,
609 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 609 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
610 */ 610 */
611int 611int
612GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc) 612GNUNET_NETWORK_socket_close(struct GNUNET_NETWORK_Handle *desc)
613{ 613{
614 int ret; 614 int ret;
615 615
616#ifdef WINDOWS 616#ifdef WINDOWS
617 DWORD error = 0; 617 DWORD error = 0;
618 618
619 SetLastError (0); 619 SetLastError(0);
620 ret = closesocket (desc->fd); 620 ret = closesocket(desc->fd);
621 error = WSAGetLastError (); 621 error = WSAGetLastError();
622 SetErrnoFromWinsockError (error); 622 SetErrnoFromWinsockError(error);
623 LOG (GNUNET_ERROR_TYPE_DEBUG, 623 LOG(GNUNET_ERROR_TYPE_DEBUG,
624 "Closed 0x%x, closesocket() returned %d, GLE is %u\n", 624 "Closed 0x%x, closesocket() returned %d, GLE is %u\n",
625 desc->fd, 625 desc->fd,
626 ret, 626 ret,
627 error); 627 error);
628#else 628#else
629 ret = close (desc->fd); 629 ret = close(desc->fd);
630#endif 630#endif
631#ifndef WINDOWS 631#ifndef WINDOWS
632 const struct sockaddr_un *un = (const struct sockaddr_un *) desc->addr; 632 const struct sockaddr_un *un = (const struct sockaddr_un *)desc->addr;
633 633
634 /* Cleanup the UNIX domain socket and its parent directories in case of non 634 /* Cleanup the UNIX domain socket and its parent directories in case of non
635 abstract sockets */ 635 abstract sockets */
636 if ( (AF_UNIX == desc->af) && 636 if ((AF_UNIX == desc->af) &&
637 (NULL != desc->addr) && 637 (NULL != desc->addr) &&
638 ('\0' != un->sun_path[0]) ) 638 ('\0' != un->sun_path[0]))
639 {
640 char *dirname = GNUNET_strndup (un->sun_path,
641 sizeof (un->sun_path));
642
643 if (0 != unlink (dirname))
644 {
645 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING,
646 "unlink",
647 dirname);
648 }
649 else
650 { 639 {
651 size_t len; 640 char *dirname = GNUNET_strndup(un->sun_path,
652 641 sizeof(un->sun_path));
653 len = strlen (dirname); 642
654 while ((len > 0) && (dirname[len] != DIR_SEPARATOR)) 643 if (0 != unlink(dirname))
655 len--;
656 dirname[len] = '\0';
657 if ((0 != len) && (0 != rmdir (dirname)))
658 {
659 switch (errno)
660 { 644 {
661 case EACCES: 645 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING,
662 case ENOTEMPTY: 646 "unlink",
663 case EPERM: 647 dirname);
664 /* these are normal and can just be ignored */
665 break;
666 default:
667 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
668 "rmdir",
669 dirname);
670 break;
671 } 648 }
672 } 649 else
650 {
651 size_t len;
652
653 len = strlen(dirname);
654 while ((len > 0) && (dirname[len] != DIR_SEPARATOR))
655 len--;
656 dirname[len] = '\0';
657 if ((0 != len) && (0 != rmdir(dirname)))
658 {
659 switch (errno)
660 {
661 case EACCES:
662 case ENOTEMPTY:
663 case EPERM:
664 /* these are normal and can just be ignored */
665 break;
666
667 default:
668 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING,
669 "rmdir",
670 dirname);
671 break;
672 }
673 }
674 }
675 GNUNET_free(dirname);
673 } 676 }
674 GNUNET_free (dirname);
675 }
676#endif 677#endif
677 GNUNET_NETWORK_socket_free_memory_only_ (desc); 678 GNUNET_NETWORK_socket_free_memory_only_(desc);
678 return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR; 679 return (ret == 0) ? GNUNET_OK : GNUNET_SYSERR;
679} 680}
680 681
@@ -685,10 +686,10 @@ GNUNET_NETWORK_socket_close (struct GNUNET_NETWORK_Handle *desc)
685 * @param desc socket 686 * @param desc socket
686 */ 687 */
687void 688void
688GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc) 689GNUNET_NETWORK_socket_free_memory_only_(struct GNUNET_NETWORK_Handle *desc)
689{ 690{
690 GNUNET_free_non_null (desc->addr); 691 GNUNET_free_non_null(desc->addr);
691 GNUNET_free (desc); 692 GNUNET_free(desc);
692} 693}
693 694
694 695
@@ -699,27 +700,28 @@ GNUNET_NETWORK_socket_free_memory_only_ (struct GNUNET_NETWORK_Handle *desc)
699 * @return NULL on error (including not supported on target platform) 700 * @return NULL on error (including not supported on target platform)
700 */ 701 */
701struct GNUNET_NETWORK_Handle * 702struct GNUNET_NETWORK_Handle *
702GNUNET_NETWORK_socket_box_native (SOCKTYPE fd) 703GNUNET_NETWORK_socket_box_native(SOCKTYPE fd)
703{ 704{
704 struct GNUNET_NETWORK_Handle *ret; 705 struct GNUNET_NETWORK_Handle *ret;
706
705#if MINGW 707#if MINGW
706 unsigned long i; 708 unsigned long i;
707 DWORD d; 709 DWORD d;
708 /* FIXME: Find a better call to check that FD is valid */ 710 /* FIXME: Find a better call to check that FD is valid */
709 if (0 != 711 if (0 !=
710 WSAIoctl (fd, FIONBIO, 712 WSAIoctl(fd, FIONBIO,
711 (void *) &i, sizeof (i), 713 (void *)&i, sizeof(i),
712 NULL, 0, &d, 714 NULL, 0, &d,
713 NULL, NULL)) 715 NULL, NULL))
714 return NULL; /* invalid FD */ 716 return NULL; /* invalid FD */
715 ret = GNUNET_new (struct GNUNET_NETWORK_Handle); 717 ret = GNUNET_new(struct GNUNET_NETWORK_Handle);
716 ret->fd = fd; 718 ret->fd = fd;
717 ret->af = AF_UNSPEC; 719 ret->af = AF_UNSPEC;
718 return ret; 720 return ret;
719#else 721#else
720 if (fcntl (fd, F_GETFD) < 0) 722 if (fcntl(fd, F_GETFD) < 0)
721 return NULL; /* invalid FD */ 723 return NULL; /* invalid FD */
722 ret = GNUNET_new (struct GNUNET_NETWORK_Handle); 724 ret = GNUNET_new(struct GNUNET_NETWORK_Handle);
723 ret->fd = fd; 725 ret->fd = fd;
724 ret->af = AF_UNSPEC; 726 ret->af = AF_UNSPEC;
725 return ret; 727 return ret;
@@ -736,22 +738,22 @@ GNUNET_NETWORK_socket_box_native (SOCKTYPE fd)
736 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 738 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
737 */ 739 */
738int 740int
739GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc, 741GNUNET_NETWORK_socket_connect(const struct GNUNET_NETWORK_Handle *desc,
740 const struct sockaddr *address, 742 const struct sockaddr *address,
741 socklen_t address_len) 743 socklen_t address_len)
742{ 744{
743 int ret; 745 int ret;
744 746
745 ret = connect (desc->fd, 747 ret = connect(desc->fd,
746 address, 748 address,
747 address_len); 749 address_len);
748#ifdef MINGW 750#ifdef MINGW
749 if (SOCKET_ERROR == ret) 751 if (SOCKET_ERROR == ret)
750 { 752 {
751 SetErrnoFromWinsockError (WSAGetLastError ()); 753 SetErrnoFromWinsockError(WSAGetLastError());
752 if (errno == EWOULDBLOCK) 754 if (errno == EWOULDBLOCK)
753 errno = EINPROGRESS; 755 errno = EINPROGRESS;
754 } 756 }
755#endif 757#endif
756 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR; 758 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
757} 759}
@@ -768,26 +770,26 @@ GNUNET_NETWORK_socket_connect (const struct GNUNET_NETWORK_Handle *desc,
768 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 770 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
769 */ 771 */
770int 772int
771GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc, 773GNUNET_NETWORK_socket_getsockopt(const struct GNUNET_NETWORK_Handle *desc,
772 int level, 774 int level,
773 int optname, 775 int optname,
774 void *optval, 776 void *optval,
775 socklen_t *optlen) 777 socklen_t *optlen)
776{ 778{
777 int ret; 779 int ret;
778 780
779 ret = getsockopt (desc->fd, 781 ret = getsockopt(desc->fd,
780 level, 782 level,
781 optname, 783 optname,
782 optval, optlen); 784 optval, optlen);
783 785
784#ifdef MINGW 786#ifdef MINGW
785 if ( (0 == ret) && 787 if ((0 == ret) &&
786 (SOL_SOCKET == level) && 788 (SOL_SOCKET == level) &&
787 (SO_ERROR == optname) ) 789 (SO_ERROR == optname))
788 *((int *) optval) = GetErrnoFromWinsockError (*((int *) optval)); 790 *((int *)optval) = GetErrnoFromWinsockError(*((int *)optval));
789 else if (SOCKET_ERROR == ret) 791 else if (SOCKET_ERROR == ret)
790 SetErrnoFromWinsockError (WSAGetLastError ()); 792 SetErrnoFromWinsockError(WSAGetLastError());
791#endif 793#endif
792 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR; 794 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
793} 795}
@@ -801,16 +803,16 @@ GNUNET_NETWORK_socket_getsockopt (const struct GNUNET_NETWORK_Handle *desc,
801 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 803 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
802 */ 804 */
803int 805int
804GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc, 806GNUNET_NETWORK_socket_listen(const struct GNUNET_NETWORK_Handle *desc,
805 int backlog) 807 int backlog)
806{ 808{
807 int ret; 809 int ret;
808 810
809 ret = listen (desc->fd, 811 ret = listen(desc->fd,
810 backlog); 812 backlog);
811#ifdef MINGW 813#ifdef MINGW
812 if (SOCKET_ERROR == ret) 814 if (SOCKET_ERROR == ret)
813 SetErrnoFromWinsockError (WSAGetLastError ()); 815 SetErrnoFromWinsockError(WSAGetLastError());
814#endif 816#endif
815 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR; 817 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
816} 818}
@@ -823,7 +825,7 @@ GNUNET_NETWORK_socket_listen (const struct GNUNET_NETWORK_Handle *desc,
823 * @returns #GNUNET_SYSERR if no data is available, or on error! 825 * @returns #GNUNET_SYSERR if no data is available, or on error!
824 */ 826 */
825ssize_t 827ssize_t
826GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc) 828GNUNET_NETWORK_socket_recvfrom_amount(const struct GNUNET_NETWORK_Handle *desc)
827{ 829{
828 int error; 830 int error;
829 831
@@ -831,20 +833,20 @@ GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc)
831#ifndef WINDOWS 833#ifndef WINDOWS
832 int pending; 834 int pending;
833 835
834 error = ioctl (desc->fd, 836 error = ioctl(desc->fd,
835 FIONREAD, 837 FIONREAD,
836 &pending); 838 &pending);
837 if (0 == error) 839 if (0 == error)
838 return (ssize_t) pending; 840 return (ssize_t)pending;
839 return GNUNET_SYSERR; 841 return GNUNET_SYSERR;
840#else 842#else
841 u_long pending; 843 u_long pending;
842 844
843 error = ioctlsocket (desc->fd, 845 error = ioctlsocket(desc->fd,
844 FIONREAD, 846 FIONREAD,
845 &pending); 847 &pending);
846 if (error != SOCKET_ERROR) 848 if (error != SOCKET_ERROR)
847 return (ssize_t) pending; 849 return (ssize_t)pending;
848 return GNUNET_SYSERR; 850 return GNUNET_SYSERR;
849#endif 851#endif
850} 852}
@@ -861,11 +863,11 @@ GNUNET_NETWORK_socket_recvfrom_amount (const struct GNUNET_NETWORK_Handle *desc)
861 * @param addrlen length of the @a src_addr 863 * @param addrlen length of the @a src_addr
862 */ 864 */
863ssize_t 865ssize_t
864GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc, 866GNUNET_NETWORK_socket_recvfrom(const struct GNUNET_NETWORK_Handle *desc,
865 void *buffer, 867 void *buffer,
866 size_t length, 868 size_t length,
867 struct sockaddr *src_addr, 869 struct sockaddr *src_addr,
868 socklen_t *addrlen) 870 socklen_t *addrlen)
869{ 871{
870 int ret; 872 int ret;
871 int flags; 873 int flags;
@@ -874,17 +876,16 @@ GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc,
874 876
875#ifdef MSG_DONTWAIT 877#ifdef MSG_DONTWAIT
876 flags |= MSG_DONTWAIT; 878 flags |= MSG_DONTWAIT;
877
878#endif 879#endif
879 ret = recvfrom (desc->fd, 880 ret = recvfrom(desc->fd,
880 buffer, 881 buffer,
881 length, 882 length,
882 flags, 883 flags,
883 src_addr, 884 src_addr,
884 addrlen); 885 addrlen);
885#ifdef MINGW 886#ifdef MINGW
886 if (SOCKET_ERROR == ret) 887 if (SOCKET_ERROR == ret)
887 SetErrnoFromWinsockError (WSAGetLastError ()); 888 SetErrnoFromWinsockError(WSAGetLastError());
888#endif 889#endif
889 return ret; 890 return ret;
890} 891}
@@ -899,9 +900,9 @@ GNUNET_NETWORK_socket_recvfrom (const struct GNUNET_NETWORK_Handle *desc,
899 * @return number of bytes received, -1 on error 900 * @return number of bytes received, -1 on error
900 */ 901 */
901ssize_t 902ssize_t
902GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc, 903GNUNET_NETWORK_socket_recv(const struct GNUNET_NETWORK_Handle *desc,
903 void *buffer, 904 void *buffer,
904 size_t length) 905 size_t length)
905{ 906{
906 int ret; 907 int ret;
907 int flags; 908 int flags;
@@ -911,13 +912,13 @@ GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc,
911#ifdef MSG_DONTWAIT 912#ifdef MSG_DONTWAIT
912 flags |= MSG_DONTWAIT; 913 flags |= MSG_DONTWAIT;
913#endif 914#endif
914 ret = recv (desc->fd, 915 ret = recv(desc->fd,
915 buffer, 916 buffer,
916 length, 917 length,
917 flags); 918 flags);
918#ifdef MINGW 919#ifdef MINGW
919 if (SOCKET_ERROR == ret) 920 if (SOCKET_ERROR == ret)
920 SetErrnoFromWinsockError (WSAGetLastError ()); 921 SetErrnoFromWinsockError(WSAGetLastError());
921#endif 922#endif
922 return ret; 923 return ret;
923} 924}
@@ -932,9 +933,9 @@ GNUNET_NETWORK_socket_recv (const struct GNUNET_NETWORK_Handle *desc,
932 * @return number of bytes sent, #GNUNET_SYSERR on error 933 * @return number of bytes sent, #GNUNET_SYSERR on error
933 */ 934 */
934ssize_t 935ssize_t
935GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc, 936GNUNET_NETWORK_socket_send(const struct GNUNET_NETWORK_Handle *desc,
936 const void *buffer, 937 const void *buffer,
937 size_t length) 938 size_t length)
938{ 939{
939 int ret; 940 int ret;
940 int flags; 941 int flags;
@@ -942,20 +943,17 @@ GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc,
942 flags = 0; 943 flags = 0;
943#ifdef MSG_DONTWAIT 944#ifdef MSG_DONTWAIT
944 flags |= MSG_DONTWAIT; 945 flags |= MSG_DONTWAIT;
945
946#endif 946#endif
947#ifdef MSG_NOSIGNAL 947#ifdef MSG_NOSIGNAL
948 flags |= MSG_NOSIGNAL; 948 flags |= MSG_NOSIGNAL;
949
950#endif 949#endif
951 ret = send (desc->fd, 950 ret = send(desc->fd,
952 buffer, 951 buffer,
953 length, 952 length,
954 flags); 953 flags);
955#ifdef MINGW 954#ifdef MINGW
956 if (SOCKET_ERROR == ret) 955 if (SOCKET_ERROR == ret)
957 SetErrnoFromWinsockError (WSAGetLastError ()); 956 SetErrnoFromWinsockError(WSAGetLastError());
958
959#endif 957#endif
960 return ret; 958 return ret;
961} 959}
@@ -973,11 +971,11 @@ GNUNET_NETWORK_socket_send (const struct GNUNET_NETWORK_Handle *desc,
973 * @return number of bytes sent, #GNUNET_SYSERR on error 971 * @return number of bytes sent, #GNUNET_SYSERR on error
974 */ 972 */
975ssize_t 973ssize_t
976GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc, 974GNUNET_NETWORK_socket_sendto(const struct GNUNET_NETWORK_Handle *desc,
977 const void *message, 975 const void *message,
978 size_t length, 976 size_t length,
979 const struct sockaddr *dest_addr, 977 const struct sockaddr *dest_addr,
980 socklen_t dest_len) 978 socklen_t dest_len)
981{ 979{
982 int ret; 980 int ret;
983 int flags; 981 int flags;
@@ -990,10 +988,10 @@ GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc,
990#ifdef MSG_NOSIGNAL 988#ifdef MSG_NOSIGNAL
991 flags |= MSG_NOSIGNAL; 989 flags |= MSG_NOSIGNAL;
992#endif 990#endif
993 ret = sendto (desc->fd, message, length, flags, dest_addr, dest_len); 991 ret = sendto(desc->fd, message, length, flags, dest_addr, dest_len);
994#ifdef MINGW 992#ifdef MINGW
995 if (SOCKET_ERROR == ret) 993 if (SOCKET_ERROR == ret)
996 SetErrnoFromWinsockError (WSAGetLastError ()); 994 SetErrnoFromWinsockError(WSAGetLastError());
997#endif 995#endif
998 return ret; 996 return ret;
999} 997}
@@ -1010,22 +1008,22 @@ GNUNET_NETWORK_socket_sendto (const struct GNUNET_NETWORK_Handle *desc,
1010 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 1008 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1011 */ 1009 */
1012int 1010int
1013GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd, 1011GNUNET_NETWORK_socket_setsockopt(struct GNUNET_NETWORK_Handle *fd,
1014 int level, 1012 int level,
1015 int option_name, 1013 int option_name,
1016 const void *option_value, 1014 const void *option_value,
1017 socklen_t option_len) 1015 socklen_t option_len)
1018{ 1016{
1019 int ret; 1017 int ret;
1020 1018
1021 ret = setsockopt (fd->fd, 1019 ret = setsockopt(fd->fd,
1022 level, 1020 level,
1023 option_name, 1021 option_name,
1024 option_value, 1022 option_value,
1025 option_len); 1023 option_len);
1026#ifdef MINGW 1024#ifdef MINGW
1027 if (SOCKET_ERROR == ret) 1025 if (SOCKET_ERROR == ret)
1028 SetErrnoFromWinsockError (WSAGetLastError ()); 1026 SetErrnoFromWinsockError(WSAGetLastError());
1029#endif 1027#endif
1030 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR; 1028 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
1031} 1029}
@@ -1042,22 +1040,22 @@ GNUNET_NETWORK_socket_setsockopt (struct GNUNET_NETWORK_Handle *fd,
1042 * @return new socket, NULL on error 1040 * @return new socket, NULL on error
1043 */ 1041 */
1044struct GNUNET_NETWORK_Handle * 1042struct GNUNET_NETWORK_Handle *
1045GNUNET_NETWORK_socket_create (int domain, 1043GNUNET_NETWORK_socket_create(int domain,
1046 int type, 1044 int type,
1047 int protocol) 1045 int protocol)
1048{ 1046{
1049 struct GNUNET_NETWORK_Handle *ret; 1047 struct GNUNET_NETWORK_Handle *ret;
1050 int fd; 1048 int fd;
1051 1049
1052 fd = socket (domain, type, protocol); 1050 fd = socket(domain, type, protocol);
1053 if (-1 == fd) 1051 if (-1 == fd)
1054 return NULL; 1052 return NULL;
1055 ret = GNUNET_new (struct GNUNET_NETWORK_Handle); 1053 ret = GNUNET_new(struct GNUNET_NETWORK_Handle);
1056 ret->fd = fd; 1054 ret->fd = fd;
1057 if (GNUNET_OK != 1055 if (GNUNET_OK !=
1058 initialize_network_handle (ret, 1056 initialize_network_handle(ret,
1059 domain, 1057 domain,
1060 type)) 1058 type))
1061 return NULL; 1059 return NULL;
1062 return ret; 1060 return ret;
1063} 1061}
@@ -1070,15 +1068,15 @@ GNUNET_NETWORK_socket_create (int domain,
1070 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 1068 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1071 */ 1069 */
1072int 1070int
1073GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc, 1071GNUNET_NETWORK_socket_shutdown(struct GNUNET_NETWORK_Handle *desc,
1074 int how) 1072 int how)
1075{ 1073{
1076 int ret; 1074 int ret;
1077 1075
1078 ret = shutdown (desc->fd, how); 1076 ret = shutdown(desc->fd, how);
1079#ifdef MINGW 1077#ifdef MINGW
1080 if (0 != ret) 1078 if (0 != ret)
1081 SetErrnoFromWinsockError (WSAGetLastError ()); 1079 SetErrnoFromWinsockError(WSAGetLastError());
1082#endif 1080#endif
1083 return (0 == ret) ? GNUNET_OK : GNUNET_SYSERR; 1081 return (0 == ret) ? GNUNET_OK : GNUNET_SYSERR;
1084} 1082}
@@ -1094,7 +1092,7 @@ GNUNET_NETWORK_socket_shutdown (struct GNUNET_NETWORK_Handle *desc,
1094 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 1092 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1095 */ 1093 */
1096int 1094int
1097GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc) 1095GNUNET_NETWORK_socket_disable_corking(struct GNUNET_NETWORK_Handle *desc)
1098{ 1096{
1099 int ret = 0; 1097 int ret = 0;
1100 1098
@@ -1103,43 +1101,43 @@ GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
1103 1101
1104 if (0 != 1102 if (0 !=
1105 (ret = 1103 (ret =
1106 setsockopt (desc->fd, 1104 setsockopt(desc->fd,
1107 SOL_SOCKET, 1105 SOL_SOCKET,
1108 SO_SNDBUF, 1106 SO_SNDBUF,
1109 (char *) &value, 1107 (char *)&value,
1110 sizeof (value)))) 1108 sizeof(value))))
1111 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 1109 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
1112 "setsockopt"); 1110 "setsockopt");
1113 if (0 != 1111 if (0 !=
1114 (ret = 1112 (ret =
1115 setsockopt (desc->fd, 1113 setsockopt(desc->fd,
1116 SOL_SOCKET, 1114 SOL_SOCKET,
1117 SO_RCVBUF, 1115 SO_RCVBUF,
1118 (char *) &value, 1116 (char *)&value,
1119 sizeof (value)))) 1117 sizeof(value))))
1120 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 1118 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
1121 "setsockopt"); 1119 "setsockopt");
1122#elif LINUX 1120#elif LINUX
1123 int value = 0; 1121 int value = 0;
1124 1122
1125 if (0 != 1123 if (0 !=
1126 (ret = 1124 (ret =
1127 setsockopt (desc->fd, 1125 setsockopt(desc->fd,
1128 SOL_SOCKET, 1126 SOL_SOCKET,
1129 SO_SNDBUF, 1127 SO_SNDBUF,
1130 &value, 1128 &value,
1131 sizeof (value)))) 1129 sizeof(value))))
1132 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 1130 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
1133 "setsockopt"); 1131 "setsockopt");
1134 if (0 != 1132 if (0 !=
1135 (ret = 1133 (ret =
1136 setsockopt (desc->fd, 1134 setsockopt(desc->fd,
1137 SOL_SOCKET, 1135 SOL_SOCKET,
1138 SO_RCVBUF, 1136 SO_RCVBUF,
1139 &value, 1137 &value,
1140 sizeof (value)))) 1138 sizeof(value))))
1141 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 1139 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
1142 "setsockopt"); 1140 "setsockopt");
1143#endif 1141#endif
1144 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR; 1142 return ret == 0 ? GNUNET_OK : GNUNET_SYSERR;
1145} 1143}
@@ -1151,9 +1149,9 @@ GNUNET_NETWORK_socket_disable_corking (struct GNUNET_NETWORK_Handle *desc)
1151 * @param fds fd set 1149 * @param fds fd set
1152 */ 1150 */
1153void 1151void
1154GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds) 1152GNUNET_NETWORK_fdset_zero(struct GNUNET_NETWORK_FDSet *fds)
1155{ 1153{
1156 FD_ZERO (&fds->sds); 1154 FD_ZERO(&fds->sds);
1157 fds->nsds = 0; 1155 fds->nsds = 0;
1158#ifdef MINGW 1156#ifdef MINGW
1159 fds->handles_pos = 0; 1157 fds->handles_pos = 0;
@@ -1168,13 +1166,13 @@ GNUNET_NETWORK_fdset_zero (struct GNUNET_NETWORK_FDSet *fds)
1168 * @param desc socket to add 1166 * @param desc socket to add
1169 */ 1167 */
1170void 1168void
1171GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds, 1169GNUNET_NETWORK_fdset_set(struct GNUNET_NETWORK_FDSet *fds,
1172 const struct GNUNET_NETWORK_Handle *desc) 1170 const struct GNUNET_NETWORK_Handle *desc)
1173{ 1171{
1174 FD_SET (desc->fd, 1172 FD_SET(desc->fd,
1175 &fds->sds); 1173 &fds->sds);
1176 fds->nsds = GNUNET_MAX (fds->nsds, 1174 fds->nsds = GNUNET_MAX(fds->nsds,
1177 desc->fd + 1); 1175 desc->fd + 1);
1178} 1176}
1179 1177
1180 1178
@@ -1186,11 +1184,11 @@ GNUNET_NETWORK_fdset_set (struct GNUNET_NETWORK_FDSet *fds,
1186 * @return 0 if the FD is not set 1184 * @return 0 if the FD is not set
1187 */ 1185 */
1188int 1186int
1189GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds, 1187GNUNET_NETWORK_fdset_isset(const struct GNUNET_NETWORK_FDSet *fds,
1190 const struct GNUNET_NETWORK_Handle *desc) 1188 const struct GNUNET_NETWORK_Handle *desc)
1191{ 1189{
1192 return FD_ISSET (desc->fd, 1190 return FD_ISSET(desc->fd,
1193 &fds->sds); 1191 &fds->sds);
1194} 1192}
1195 1193
1196 1194
@@ -1201,17 +1199,17 @@ GNUNET_NETWORK_fdset_isset (const struct GNUNET_NETWORK_FDSet *fds,
1201 * @param src the fd set to add from 1199 * @param src the fd set to add from
1202 */ 1200 */
1203void 1201void
1204GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst, 1202GNUNET_NETWORK_fdset_add(struct GNUNET_NETWORK_FDSet *dst,
1205 const struct GNUNET_NETWORK_FDSet *src) 1203 const struct GNUNET_NETWORK_FDSet *src)
1206{ 1204{
1207#ifndef MINGW 1205#ifndef MINGW
1208 int nfds; 1206 int nfds;
1209 1207
1210 for (nfds = src->nsds; nfds >= 0; nfds--) 1208 for (nfds = src->nsds; nfds >= 0; nfds--)
1211 if (FD_ISSET (nfds, &src->sds)) 1209 if (FD_ISSET(nfds, &src->sds))
1212 FD_SET (nfds, &dst->sds); 1210 FD_SET(nfds, &dst->sds);
1213 dst->nsds = GNUNET_MAX (dst->nsds, 1211 dst->nsds = GNUNET_MAX(dst->nsds,
1214 src->nsds); 1212 src->nsds);
1215#else 1213#else
1216 /* This is MinGW32-specific implementation that relies on the code that 1214 /* This is MinGW32-specific implementation that relies on the code that
1217 * winsock2.h defines for FD_SET. Namely, it relies on FD_SET checking 1215 * winsock2.h defines for FD_SET. Namely, it relies on FD_SET checking
@@ -1224,16 +1222,16 @@ GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
1224 unsigned int i; 1222 unsigned int i;
1225 1223
1226 for (i = 0; i < src->sds.fd_count; i++) 1224 for (i = 0; i < src->sds.fd_count; i++)
1227 FD_SET (src->sds.fd_array[i], 1225 FD_SET(src->sds.fd_array[i],
1228 &dst->sds); 1226 &dst->sds);
1229 dst->nsds = GNUNET_MAX (src->nsds, 1227 dst->nsds = GNUNET_MAX(src->nsds,
1230 dst->nsds); 1228 dst->nsds);
1231 1229
1232 /* also copy over `struct GNUNET_DISK_FileHandle` array */ 1230 /* also copy over `struct GNUNET_DISK_FileHandle` array */
1233 if (dst->handles_pos + src->handles_pos > dst->handles_size) 1231 if (dst->handles_pos + src->handles_pos > dst->handles_size)
1234 GNUNET_array_grow (dst->handles, 1232 GNUNET_array_grow(dst->handles,
1235 dst->handles_size, 1233 dst->handles_size,
1236 ((dst->handles_pos + src->handles_pos) << 1)); 1234 ((dst->handles_pos + src->handles_pos) << 1));
1237 for (i = 0; i < src->handles_pos; i++) 1235 for (i = 0; i < src->handles_pos; i++)
1238 dst->handles[dst->handles_pos++] = src->handles[i]; 1236 dst->handles[dst->handles_pos++] = src->handles[i];
1239#endif 1237#endif
@@ -1247,20 +1245,20 @@ GNUNET_NETWORK_fdset_add (struct GNUNET_NETWORK_FDSet *dst,
1247 * @param from source 1245 * @param from source
1248 */ 1246 */
1249void 1247void
1250GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to, 1248GNUNET_NETWORK_fdset_copy(struct GNUNET_NETWORK_FDSet *to,
1251 const struct GNUNET_NETWORK_FDSet *from) 1249 const struct GNUNET_NETWORK_FDSet *from)
1252{ 1250{
1253 FD_COPY (&from->sds, 1251 FD_COPY(&from->sds,
1254 &to->sds); 1252 &to->sds);
1255 to->nsds = from->nsds; 1253 to->nsds = from->nsds;
1256#ifdef MINGW 1254#ifdef MINGW
1257 if (from->handles_pos > to->handles_size) 1255 if (from->handles_pos > to->handles_size)
1258 GNUNET_array_grow (to->handles, 1256 GNUNET_array_grow(to->handles,
1259 to->handles_size, 1257 to->handles_size,
1260 from->handles_pos * 2); 1258 from->handles_pos * 2);
1261 GNUNET_memcpy (to->handles, 1259 GNUNET_memcpy(to->handles,
1262 from->handles, 1260 from->handles,
1263 from->handles_pos * sizeof (struct GNUNET_NETWORK_Handle *)); 1261 from->handles_pos * sizeof(struct GNUNET_NETWORK_Handle *));
1264 to->handles_pos = from->handles_pos; 1262 to->handles_pos = from->handles_pos;
1265#endif 1263#endif
1266} 1264}
@@ -1273,7 +1271,7 @@ GNUNET_NETWORK_fdset_copy (struct GNUNET_NETWORK_FDSet *to,
1273 * @return POSIX file descriptor 1271 * @return POSIX file descriptor
1274 */ 1272 */
1275int 1273int
1276GNUNET_NETWORK_get_fd (const struct GNUNET_NETWORK_Handle *desc) 1274GNUNET_NETWORK_get_fd(const struct GNUNET_NETWORK_Handle *desc)
1277{ 1275{
1278 return desc->fd; 1276 return desc->fd;
1279} 1277}
@@ -1286,7 +1284,7 @@ GNUNET_NETWORK_get_fd (const struct GNUNET_NETWORK_Handle *desc)
1286 * @return sockaddr 1284 * @return sockaddr
1287 */ 1285 */
1288struct sockaddr* 1286struct sockaddr*
1289GNUNET_NETWORK_get_addr (const struct GNUNET_NETWORK_Handle *desc) 1287GNUNET_NETWORK_get_addr(const struct GNUNET_NETWORK_Handle *desc)
1290{ 1288{
1291 return desc->addr; 1289 return desc->addr;
1292} 1290}
@@ -1299,7 +1297,7 @@ GNUNET_NETWORK_get_addr (const struct GNUNET_NETWORK_Handle *desc)
1299 * @return socklen_t for sockaddr 1297 * @return socklen_t for sockaddr
1300 */ 1298 */
1301socklen_t 1299socklen_t
1302GNUNET_NETWORK_get_addrlen (const struct GNUNET_NETWORK_Handle *desc) 1300GNUNET_NETWORK_get_addrlen(const struct GNUNET_NETWORK_Handle *desc)
1303{ 1301{
1304 return desc->addrlen; 1302 return desc->addrlen;
1305} 1303}
@@ -1313,12 +1311,12 @@ GNUNET_NETWORK_get_addrlen (const struct GNUNET_NETWORK_Handle *desc)
1313 * @param nfds the biggest socket number in from + 1 1311 * @param nfds the biggest socket number in from + 1
1314 */ 1312 */
1315void 1313void
1316GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to, 1314GNUNET_NETWORK_fdset_copy_native(struct GNUNET_NETWORK_FDSet *to,
1317 const fd_set *from, 1315 const fd_set *from,
1318 int nfds) 1316 int nfds)
1319{ 1317{
1320 FD_COPY (from, 1318 FD_COPY(from,
1321 &to->sds); 1319 &to->sds);
1322 to->nsds = nfds; 1320 to->nsds = nfds;
1323} 1321}
1324 1322
@@ -1330,13 +1328,13 @@ GNUNET_NETWORK_fdset_copy_native (struct GNUNET_NETWORK_FDSet *to,
1330 * @param nfd native FD to set 1328 * @param nfd native FD to set
1331 */ 1329 */
1332void 1330void
1333GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to, 1331GNUNET_NETWORK_fdset_set_native(struct GNUNET_NETWORK_FDSet *to,
1334 int nfd) 1332 int nfd)
1335{ 1333{
1336 GNUNET_assert ((nfd >= 0) && (nfd < FD_SETSIZE)); 1334 GNUNET_assert((nfd >= 0) && (nfd < FD_SETSIZE));
1337 FD_SET (nfd, &to->sds); 1335 FD_SET(nfd, &to->sds);
1338 to->nsds = GNUNET_MAX (nfd + 1, 1336 to->nsds = GNUNET_MAX(nfd + 1,
1339 to->nsds); 1337 to->nsds);
1340} 1338}
1341 1339
1342 1340
@@ -1348,13 +1346,13 @@ GNUNET_NETWORK_fdset_set_native (struct GNUNET_NETWORK_FDSet *to,
1348 * @return #GNUNET_YES if FD is set in the set 1346 * @return #GNUNET_YES if FD is set in the set
1349 */ 1347 */
1350int 1348int
1351GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to, 1349GNUNET_NETWORK_fdset_test_native(const struct GNUNET_NETWORK_FDSet *to,
1352 int nfd) 1350 int nfd)
1353{ 1351{
1354 if ( (-1 == nfd) || 1352 if ((-1 == nfd) ||
1355 (NULL == to) ) 1353 (NULL == to))
1356 return GNUNET_NO; 1354 return GNUNET_NO;
1357 return FD_ISSET (nfd, &to->sds) ? GNUNET_YES : GNUNET_NO; 1355 return FD_ISSET(nfd, &to->sds) ? GNUNET_YES : GNUNET_NO;
1358} 1356}
1359 1357
1360 1358
@@ -1364,26 +1362,26 @@ GNUNET_NETWORK_fdset_test_native (const struct GNUNET_NETWORK_FDSet *to,
1364 * @param h the file handle to add 1362 * @param h the file handle to add
1365 */ 1363 */
1366void 1364void
1367GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds, 1365GNUNET_NETWORK_fdset_handle_set(struct GNUNET_NETWORK_FDSet *fds,
1368 const struct GNUNET_DISK_FileHandle *h) 1366 const struct GNUNET_DISK_FileHandle *h)
1369{ 1367{
1370#ifdef MINGW 1368#ifdef MINGW
1371 if (fds->handles_pos == fds->handles_size) 1369 if (fds->handles_pos == fds->handles_size)
1372 GNUNET_array_grow (fds->handles, 1370 GNUNET_array_grow(fds->handles,
1373 fds->handles_size, 1371 fds->handles_size,
1374 fds->handles_size * 2 + 2); 1372 fds->handles_size * 2 + 2);
1375 fds->handles[fds->handles_pos++] = h; 1373 fds->handles[fds->handles_pos++] = h;
1376#else 1374#else
1377 int fd; 1375 int fd;
1378 1376
1379 GNUNET_assert (GNUNET_OK == 1377 GNUNET_assert(GNUNET_OK ==
1380 GNUNET_DISK_internal_file_handle_ (h, 1378 GNUNET_DISK_internal_file_handle_(h,
1381 &fd, 1379 &fd,
1382 sizeof (int))); 1380 sizeof(int)));
1383 FD_SET (fd, 1381 FD_SET(fd,
1384 &fds->sds); 1382 &fds->sds);
1385 fds->nsds = GNUNET_MAX (fd + 1, 1383 fds->nsds = GNUNET_MAX(fd + 1,
1386 fds->nsds); 1384 fds->nsds);
1387#endif 1385#endif
1388} 1386}
1389 1387
@@ -1394,24 +1392,24 @@ GNUNET_NETWORK_fdset_handle_set (struct GNUNET_NETWORK_FDSet *fds,
1394 * @param h the file handle to add 1392 * @param h the file handle to add
1395 */ 1393 */
1396void 1394void
1397GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds, 1395GNUNET_NETWORK_fdset_handle_set_first(struct GNUNET_NETWORK_FDSet *fds,
1398 const struct GNUNET_DISK_FileHandle *h) 1396 const struct GNUNET_DISK_FileHandle *h)
1399{ 1397{
1400#ifdef MINGW 1398#ifdef MINGW
1401 if (fds->handles_pos == fds->handles_size) 1399 if (fds->handles_pos == fds->handles_size)
1402 GNUNET_array_grow (fds->handles, 1400 GNUNET_array_grow(fds->handles,
1403 fds->handles_size, 1401 fds->handles_size,
1404 fds->handles_size * 2 + 2); 1402 fds->handles_size * 2 + 2);
1405 fds->handles[fds->handles_pos] = h; 1403 fds->handles[fds->handles_pos] = h;
1406 if (fds->handles[0] != h) 1404 if (fds->handles[0] != h)
1407 { 1405 {
1408 const struct GNUNET_DISK_FileHandle *bak = fds->handles[0]; 1406 const struct GNUNET_DISK_FileHandle *bak = fds->handles[0];
1409 fds->handles[0] = h; 1407 fds->handles[0] = h;
1410 fds->handles[fds->handles_pos] = bak; 1408 fds->handles[fds->handles_pos] = bak;
1411 } 1409 }
1412 fds->handles_pos++; 1410 fds->handles_pos++;
1413#else 1411#else
1414 GNUNET_NETWORK_fdset_handle_set (fds, h); 1412 GNUNET_NETWORK_fdset_handle_set(fds, h);
1415#endif 1413#endif
1416} 1414}
1417 1415
@@ -1424,19 +1422,19 @@ GNUNET_NETWORK_fdset_handle_set_first (struct GNUNET_NETWORK_FDSet *fds,
1424 * @return #GNUNET_YES if the file handle is part of the set 1422 * @return #GNUNET_YES if the file handle is part of the set
1425 */ 1423 */
1426int 1424int
1427GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds, 1425GNUNET_NETWORK_fdset_handle_isset(const struct GNUNET_NETWORK_FDSet *fds,
1428 const struct GNUNET_DISK_FileHandle *h) 1426 const struct GNUNET_DISK_FileHandle *h)
1429{ 1427{
1430#ifdef MINGW 1428#ifdef MINGW
1431 unsigned int i; 1429 unsigned int i;
1432 1430
1433 for (i=0;i<fds->handles_pos;i++) 1431 for (i = 0; i < fds->handles_pos; i++)
1434 if (fds->handles[i] == h) 1432 if (fds->handles[i] == h)
1435 return GNUNET_YES; 1433 return GNUNET_YES;
1436 return GNUNET_NO; 1434 return GNUNET_NO;
1437#else 1435#else
1438 return FD_ISSET (h->fd, 1436 return FD_ISSET(h->fd,
1439 &fds->sds); 1437 &fds->sds);
1440#endif 1438#endif
1441} 1439}
1442 1440
@@ -1451,12 +1449,12 @@ GNUNET_NETWORK_fdset_handle_isset (const struct GNUNET_NETWORK_FDSet *fds,
1451 * @return -1, 0 or 1, if the p1 < p2, p1==p2 or p1 > p2. 1449 * @return -1, 0 or 1, if the p1 < p2, p1==p2 or p1 > p2.
1452 */ 1450 */
1453static int 1451static int
1454ptr_cmp (const void *p1, 1452ptr_cmp(const void *p1,
1455 const void *p2) 1453 const void *p2)
1456{ 1454{
1457 if (p1 == p2) 1455 if (p1 == p2)
1458 return 0; 1456 return 0;
1459 if ((intptr_t) p1 < (intptr_t) p2) 1457 if ((intptr_t)p1 < (intptr_t)p2)
1460 return -1; 1458 return -1;
1461 return 1; 1459 return 1;
1462} 1460}
@@ -1471,23 +1469,23 @@ ptr_cmp (const void *p1,
1471 * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise 1469 * @return #GNUNET_YES if they do overlap, #GNUNET_NO otherwise
1472 */ 1470 */
1473int 1471int
1474GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1, 1472GNUNET_NETWORK_fdset_overlap(const struct GNUNET_NETWORK_FDSet *fds1,
1475 const struct GNUNET_NETWORK_FDSet *fds2) 1473 const struct GNUNET_NETWORK_FDSet *fds2)
1476{ 1474{
1477#ifndef MINGW 1475#ifndef MINGW
1478 int nfds; 1476 int nfds;
1479 1477
1480 nfds = GNUNET_MIN (fds1->nsds, 1478 nfds = GNUNET_MIN(fds1->nsds,
1481 fds2->nsds); 1479 fds2->nsds);
1482 while (nfds > 0) 1480 while (nfds > 0)
1483 { 1481 {
1484 nfds--; 1482 nfds--;
1485 if ( (FD_ISSET (nfds, 1483 if ((FD_ISSET(nfds,
1486 &fds1->sds)) && 1484 &fds1->sds)) &&
1487 (FD_ISSET (nfds, 1485 (FD_ISSET(nfds,
1488 &fds2->sds)) ) 1486 &fds2->sds)))
1489 return GNUNET_YES; 1487 return GNUNET_YES;
1490 } 1488 }
1491 return GNUNET_NO; 1489 return GNUNET_NO;
1492#else 1490#else
1493 unsigned int i; 1491 unsigned int i;
@@ -1501,37 +1499,39 @@ GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1501 return GNUNET_YES; 1499 return GNUNET_YES;
1502 1500
1503 /* take a short cut if possible */ 1501 /* take a short cut if possible */
1504 if ( (0 == fds1->handles_pos) || 1502 if ((0 == fds1->handles_pos) ||
1505 (0 == fds2->handles_pos) ) 1503 (0 == fds2->handles_pos))
1506 return GNUNET_NO; 1504 return GNUNET_NO;
1507 1505
1508 /* Sort file handles array to avoid quadratic complexity when 1506 /* Sort file handles array to avoid quadratic complexity when
1509 checking for overlap */ 1507 checking for overlap */
1510 qsort (fds1->handles, 1508 qsort(fds1->handles,
1511 fds1->handles_pos, 1509 fds1->handles_pos,
1512 sizeof (void *), 1510 sizeof(void *),
1513 &ptr_cmp); 1511 &ptr_cmp);
1514 qsort (fds2->handles, 1512 qsort(fds2->handles,
1515 fds2->handles_pos, 1513 fds2->handles_pos,
1516 sizeof (void *), 1514 sizeof(void *),
1517 &ptr_cmp); 1515 &ptr_cmp);
1518 i = 0; 1516 i = 0;
1519 j = 0; 1517 j = 0;
1520 while ( (i < fds1->handles_pos) && 1518 while ((i < fds1->handles_pos) &&
1521 (j < fds2->handles_pos) ) 1519 (j < fds2->handles_pos))
1522 {
1523 switch (ptr_cmp (fds1->handles[i],
1524 fds2->handles[j]))
1525 { 1520 {
1526 case -1: 1521 switch (ptr_cmp(fds1->handles[i],
1527 i++; 1522 fds2->handles[j]))
1528 break; 1523 {
1529 case 0: 1524 case -1:
1530 return GNUNET_YES; 1525 i++;
1531 case 1: 1526 break;
1532 j++; 1527
1528 case 0:
1529 return GNUNET_YES;
1530
1531 case 1:
1532 j++;
1533 }
1533 } 1534 }
1534 }
1535 return GNUNET_NO; 1535 return GNUNET_NO;
1536#endif 1536#endif
1537} 1537}
@@ -1543,12 +1543,12 @@ GNUNET_NETWORK_fdset_overlap (const struct GNUNET_NETWORK_FDSet *fds1,
1543 * @return a new fd set 1543 * @return a new fd set
1544 */ 1544 */
1545struct GNUNET_NETWORK_FDSet * 1545struct GNUNET_NETWORK_FDSet *
1546GNUNET_NETWORK_fdset_create () 1546GNUNET_NETWORK_fdset_create()
1547{ 1547{
1548 struct GNUNET_NETWORK_FDSet *fds; 1548 struct GNUNET_NETWORK_FDSet *fds;
1549 1549
1550 fds = GNUNET_new (struct GNUNET_NETWORK_FDSet); 1550 fds = GNUNET_new(struct GNUNET_NETWORK_FDSet);
1551 GNUNET_NETWORK_fdset_zero (fds); 1551 GNUNET_NETWORK_fdset_zero(fds);
1552 return fds; 1552 return fds;
1553} 1553}
1554 1554
@@ -1559,14 +1559,14 @@ GNUNET_NETWORK_fdset_create ()
1559 * @param fds fd set 1559 * @param fds fd set
1560 */ 1560 */
1561void 1561void
1562GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds) 1562GNUNET_NETWORK_fdset_destroy(struct GNUNET_NETWORK_FDSet *fds)
1563{ 1563{
1564#ifdef MINGW 1564#ifdef MINGW
1565 GNUNET_array_grow (fds->handles, 1565 GNUNET_array_grow(fds->handles,
1566 fds->handles_size, 1566 fds->handles_size,
1567 0); 1567 0);
1568#endif 1568#endif
1569 GNUNET_free (fds); 1569 GNUNET_free(fds);
1570} 1570}
1571 1571
1572 1572
@@ -1574,8 +1574,7 @@ GNUNET_NETWORK_fdset_destroy (struct GNUNET_NETWORK_FDSet *fds)
1574/** 1574/**
1575 * FIXME. 1575 * FIXME.
1576 */ 1576 */
1577struct _select_params 1577struct _select_params {
1578{
1579 /** 1578 /**
1580 * Read set. 1579 * Read set.
1581 */ 1580 */
@@ -1622,29 +1621,29 @@ struct _select_params
1622 * FIXME. 1621 * FIXME.
1623 */ 1622 */
1624static DWORD WINAPI 1623static DWORD WINAPI
1625_selector (LPVOID p) 1624_selector(LPVOID p)
1626{ 1625{
1627 struct _select_params *sp = p; 1626 struct _select_params *sp = p;
1628 1627
1629 while (1) 1628 while (1)
1630 {
1631 WaitForSingleObject (sp->standby,
1632 INFINITE);
1633 ResetEvent (sp->standby);
1634 sp->status = select (1,
1635 sp->r,
1636 sp->w,
1637 sp->e,
1638 sp->tv);
1639 if (FD_ISSET (sp->wakeup_socket,
1640 sp->r))
1641 { 1629 {
1642 FD_CLR (sp->wakeup_socket, 1630 WaitForSingleObject(sp->standby,
1643 sp->r); 1631 INFINITE);
1644 sp->status -= 1; 1632 ResetEvent(sp->standby);
1633 sp->status = select(1,
1634 sp->r,
1635 sp->w,
1636 sp->e,
1637 sp->tv);
1638 if (FD_ISSET(sp->wakeup_socket,
1639 sp->r))
1640 {
1641 FD_CLR(sp->wakeup_socket,
1642 sp->r);
1643 sp->status -= 1;
1644 }
1645 SetEvent(sp->wakeup);
1645 } 1646 }
1646 SetEvent (sp->wakeup);
1647 }
1648 return 0; 1647 return 0;
1649} 1648}
1650 1649
@@ -1674,7 +1673,7 @@ static struct timeval select_timeout;
1674 * initializes that thread. 1673 * initializes that thread.
1675 */ 1674 */
1676static void 1675static void
1677initialize_select_thread () 1676initialize_select_thread()
1678{ 1677{
1679 SOCKET select_listening_socket = -1; 1678 SOCKET select_listening_socket = -1;
1680 struct sockaddr_in s_in; 1679 struct sockaddr_in s_in;
@@ -1682,67 +1681,67 @@ initialize_select_thread ()
1682 int res; 1681 int res;
1683 unsigned long p; 1682 unsigned long p;
1684 1683
1685 select_standby_event = CreateEvent (NULL, TRUE, FALSE, NULL); 1684 select_standby_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1686 select_finished_event = CreateEvent (NULL, TRUE, FALSE, NULL); 1685 select_finished_event = CreateEvent(NULL, TRUE, FALSE, NULL);
1687 1686
1688 select_wakeup_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 1687 select_wakeup_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1689 1688
1690 select_listening_socket = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 1689 select_listening_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
1691 1690
1692 p = 1; 1691 p = 1;
1693 res = ioctlsocket (select_wakeup_socket, FIONBIO, &p); 1692 res = ioctlsocket(select_wakeup_socket, FIONBIO, &p);
1694 LOG (GNUNET_ERROR_TYPE_DEBUG, 1693 LOG(GNUNET_ERROR_TYPE_DEBUG,
1695 "Select thread initialization: ioctlsocket() returns %d\n", 1694 "Select thread initialization: ioctlsocket() returns %d\n",
1696 res); 1695 res);
1697 1696
1698 alen = sizeof (s_in); 1697 alen = sizeof(s_in);
1699 s_in.sin_family = AF_INET; 1698 s_in.sin_family = AF_INET;
1700 s_in.sin_port = 0; 1699 s_in.sin_port = 0;
1701 s_in.sin_addr.S_un.S_un_b.s_b1 = 127; 1700 s_in.sin_addr.S_un.S_un_b.s_b1 = 127;
1702 s_in.sin_addr.S_un.S_un_b.s_b2 = 0; 1701 s_in.sin_addr.S_un.S_un_b.s_b2 = 0;
1703 s_in.sin_addr.S_un.S_un_b.s_b3 = 0; 1702 s_in.sin_addr.S_un.S_un_b.s_b3 = 0;
1704 s_in.sin_addr.S_un.S_un_b.s_b4 = 1; 1703 s_in.sin_addr.S_un.S_un_b.s_b4 = 1;
1705 res = bind (select_listening_socket, 1704 res = bind(select_listening_socket,
1706 (const struct sockaddr *) &s_in, 1705 (const struct sockaddr *)&s_in,
1707 sizeof (s_in)); 1706 sizeof(s_in));
1708 LOG (GNUNET_ERROR_TYPE_DEBUG, 1707 LOG(GNUNET_ERROR_TYPE_DEBUG,
1709 "Select thread initialization: bind() returns %d\n", 1708 "Select thread initialization: bind() returns %d\n",
1710 res); 1709 res);
1711 1710
1712 res = getsockname (select_listening_socket, 1711 res = getsockname(select_listening_socket,
1713 (struct sockaddr *) &s_in, 1712 (struct sockaddr *)&s_in,
1714 &alen); 1713 &alen);
1715 LOG (GNUNET_ERROR_TYPE_DEBUG, 1714 LOG(GNUNET_ERROR_TYPE_DEBUG,
1716 "Select thread initialization: getsockname() returns %d\n", 1715 "Select thread initialization: getsockname() returns %d\n",
1717 res); 1716 res);
1718 1717
1719 res = listen (select_listening_socket, 1718 res = listen(select_listening_socket,
1720 SOMAXCONN); 1719 SOMAXCONN);
1721 LOG (GNUNET_ERROR_TYPE_DEBUG, 1720 LOG(GNUNET_ERROR_TYPE_DEBUG,
1722 "Select thread initialization: listen() returns %d\n", 1721 "Select thread initialization: listen() returns %d\n",
1723 res); 1722 res);
1724 res = connect (select_wakeup_socket, 1723 res = connect(select_wakeup_socket,
1725 (const struct sockaddr *) &s_in, 1724 (const struct sockaddr *)&s_in,
1726 sizeof (s_in)); 1725 sizeof(s_in));
1727 LOG (GNUNET_ERROR_TYPE_DEBUG, 1726 LOG(GNUNET_ERROR_TYPE_DEBUG,
1728 "Select thread initialization: connect() returns %d\n", 1727 "Select thread initialization: connect() returns %d\n",
1729 res); 1728 res);
1730 1729
1731 select_send_socket = accept (select_listening_socket, 1730 select_send_socket = accept(select_listening_socket,
1732 (struct sockaddr *) &s_in, 1731 (struct sockaddr *)&s_in,
1733 &alen); 1732 &alen);
1734 1733
1735 closesocket (select_listening_socket); 1734 closesocket(select_listening_socket);
1736 1735
1737 sp.wakeup = select_finished_event; 1736 sp.wakeup = select_finished_event;
1738 sp.standby = select_standby_event; 1737 sp.standby = select_standby_event;
1739 sp.wakeup_socket = select_wakeup_socket; 1738 sp.wakeup_socket = select_wakeup_socket;
1740 1739
1741 select_thread = CreateThread (NULL, 1740 select_thread = CreateThread(NULL,
1742 0, 1741 0,
1743 _selector, 1742 _selector,
1744 &sp, 1743 &sp,
1745 0, NULL); 1744 0, NULL);
1746} 1745}
1747 1746
1748 1747
@@ -1756,8 +1755,8 @@ initialize_select_thread ()
1756 * @return #GNUNET_OK if the port is available, #GNUNET_NO if not 1755 * @return #GNUNET_OK if the port is available, #GNUNET_NO if not
1757 */ 1756 */
1758int 1757int
1759GNUNET_NETWORK_test_port_free (int ipproto, 1758GNUNET_NETWORK_test_port_free(int ipproto,
1760 uint16_t port) 1759 uint16_t port)
1761{ 1760{
1762 struct GNUNET_NETWORK_Handle *socket; 1761 struct GNUNET_NETWORK_Handle *socket;
1763 int bind_status; 1762 int bind_status;
@@ -1767,13 +1766,13 @@ GNUNET_NETWORK_test_port_free (int ipproto,
1767 struct addrinfo *ret; 1766 struct addrinfo *ret;
1768 struct addrinfo *ai; 1767 struct addrinfo *ai;
1769 1768
1770 GNUNET_snprintf (open_port_str, 1769 GNUNET_snprintf(open_port_str,
1771 sizeof (open_port_str), 1770 sizeof(open_port_str),
1772 "%u", 1771 "%u",
1773 (unsigned int) port); 1772 (unsigned int)port);
1774 socktype = (IPPROTO_TCP == ipproto) ? SOCK_STREAM : SOCK_DGRAM; 1773 socktype = (IPPROTO_TCP == ipproto) ? SOCK_STREAM : SOCK_DGRAM;
1775 ret = NULL; 1774 ret = NULL;
1776 memset (&hint, 0, sizeof (hint)); 1775 memset(&hint, 0, sizeof(hint));
1777 hint.ai_family = AF_UNSPEC; /* IPv4 and IPv6 */ 1776 hint.ai_family = AF_UNSPEC; /* IPv4 and IPv6 */
1778 hint.ai_socktype = socktype; 1777 hint.ai_socktype = socktype;
1779 hint.ai_protocol = ipproto; 1778 hint.ai_protocol = ipproto;
@@ -1782,26 +1781,26 @@ GNUNET_NETWORK_test_port_free (int ipproto,
1782 hint.ai_canonname = NULL; 1781 hint.ai_canonname = NULL;
1783 hint.ai_next = NULL; 1782 hint.ai_next = NULL;
1784 hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV; /* Wild card address */ 1783 hint.ai_flags = AI_PASSIVE | AI_NUMERICSERV; /* Wild card address */
1785 GNUNET_assert (0 == getaddrinfo (NULL, 1784 GNUNET_assert(0 == getaddrinfo(NULL,
1786 open_port_str, 1785 open_port_str,
1787 &hint, 1786 &hint,
1788 &ret)); 1787 &ret));
1789 bind_status = GNUNET_NO; 1788 bind_status = GNUNET_NO;
1790 for (ai = ret; NULL != ai; ai = ai->ai_next) 1789 for (ai = ret; NULL != ai; ai = ai->ai_next)
1791 { 1790 {
1792 socket = GNUNET_NETWORK_socket_create (ai->ai_family, 1791 socket = GNUNET_NETWORK_socket_create(ai->ai_family,
1793 ai->ai_socktype, 1792 ai->ai_socktype,
1794 ai->ai_protocol); 1793 ai->ai_protocol);
1795 if (NULL == socket) 1794 if (NULL == socket)
1796 continue; 1795 continue;
1797 bind_status = GNUNET_NETWORK_socket_bind (socket, 1796 bind_status = GNUNET_NETWORK_socket_bind(socket,
1798 ai->ai_addr, 1797 ai->ai_addr,
1799 ai->ai_addrlen); 1798 ai->ai_addrlen);
1800 GNUNET_NETWORK_socket_close (socket); 1799 GNUNET_NETWORK_socket_close(socket);
1801 if (GNUNET_OK != bind_status) 1800 if (GNUNET_OK != bind_status)
1802 break; 1801 break;
1803 } 1802 }
1804 freeaddrinfo (ret); 1803 freeaddrinfo(ret);
1805 return bind_status; 1804 return bind_status;
1806} 1805}
1807 1806
@@ -1817,10 +1816,10 @@ GNUNET_NETWORK_test_port_free (int ipproto,
1817 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error 1816 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1818 */ 1817 */
1819int 1818int
1820GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds, 1819GNUNET_NETWORK_socket_select(struct GNUNET_NETWORK_FDSet *rfds,
1821 struct GNUNET_NETWORK_FDSet *wfds, 1820 struct GNUNET_NETWORK_FDSet *wfds,
1822 struct GNUNET_NETWORK_FDSet *efds, 1821 struct GNUNET_NETWORK_FDSet *efds,
1823 const struct GNUNET_TIME_Relative timeout) 1822 const struct GNUNET_TIME_Relative timeout)
1824{ 1823{
1825 int nfds; 1824 int nfds;
1826 struct timeval tv; 1825 struct timeval tv;
@@ -1830,37 +1829,37 @@ GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1830 else 1829 else
1831 nfds = 0; 1830 nfds = 0;
1832 if (NULL != wfds) 1831 if (NULL != wfds)
1833 nfds = GNUNET_MAX (nfds, 1832 nfds = GNUNET_MAX(nfds,
1834 wfds->nsds); 1833 wfds->nsds);
1835 if (NULL != efds) 1834 if (NULL != efds)
1836 nfds = GNUNET_MAX (nfds, 1835 nfds = GNUNET_MAX(nfds,
1837 efds->nsds); 1836 efds->nsds);
1838 if ((0 == nfds) && 1837 if ((0 == nfds) &&
1839 (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)) 1838 (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us))
1840 { 1839 {
1841 GNUNET_break (0); 1840 GNUNET_break(0);
1842 LOG (GNUNET_ERROR_TYPE_ERROR, 1841 LOG(GNUNET_ERROR_TYPE_ERROR,
1843 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"), 1842 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
1844 "select"); 1843 "select");
1845 } 1844 }
1846 if (timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us > (unsigned long long) LONG_MAX) 1845 if (timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us > (unsigned long long)LONG_MAX)
1847 { 1846 {
1848 tv.tv_sec = LONG_MAX; 1847 tv.tv_sec = LONG_MAX;
1849 tv.tv_usec = 999999L; 1848 tv.tv_usec = 999999L;
1850 } 1849 }
1851 else 1850 else
1852 { 1851 {
1853 tv.tv_sec = (long) (timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us); 1852 tv.tv_sec = (long)(timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us);
1854 tv.tv_usec = 1853 tv.tv_usec =
1855 (timeout.rel_value_us - 1854 (timeout.rel_value_us -
1856 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value_us)); 1855 (tv.tv_sec * GNUNET_TIME_UNIT_SECONDS.rel_value_us));
1857 } 1856 }
1858 return select (nfds, 1857 return select(nfds,
1859 (NULL != rfds) ? &rfds->sds : NULL, 1858 (NULL != rfds) ? &rfds->sds : NULL,
1860 (NULL != wfds) ? &wfds->sds : NULL, 1859 (NULL != wfds) ? &wfds->sds : NULL,
1861 (NULL != efds) ? &efds->sds : NULL, 1860 (NULL != efds) ? &efds->sds : NULL,
1862 (timeout.rel_value_us == 1861 (timeout.rel_value_us ==
1863 GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) ? NULL : &tv); 1862 GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) ? NULL : &tv);
1864} 1863}
1865 1864
1866 1865
@@ -1875,25 +1874,25 @@ GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
1875 * @return #GNUNET_YES if the pipe is ready for reading 1874 * @return #GNUNET_YES if the pipe is ready for reading
1876 */ 1875 */
1877static int 1876static int
1878pipe_read_ready (const struct GNUNET_DISK_FileHandle *fh) 1877pipe_read_ready(const struct GNUNET_DISK_FileHandle *fh)
1879{ 1878{
1880 DWORD error; 1879 DWORD error;
1881 BOOL bret; 1880 BOOL bret;
1882 DWORD waitstatus = 0; 1881 DWORD waitstatus = 0;
1883 1882
1884 SetLastError (0); 1883 SetLastError(0);
1885 bret = PeekNamedPipe (fh->h, NULL, 0, NULL, &waitstatus, NULL); 1884 bret = PeekNamedPipe(fh->h, NULL, 0, NULL, &waitstatus, NULL);
1886 error = GetLastError (); 1885 error = GetLastError();
1887 if (0 == bret) 1886 if (0 == bret)
1888 { 1887 {
1889 /* TODO: either add more errors to this condition, or eliminate it 1888 /* TODO: either add more errors to this condition, or eliminate it
1890 * entirely (failed to peek -> pipe is in serious trouble, should 1889 * entirely (failed to peek -> pipe is in serious trouble, should
1891 * be selected as readable). 1890 * be selected as readable).
1892 */ 1891 */
1893 if ( (error != ERROR_BROKEN_PIPE) && 1892 if ((error != ERROR_BROKEN_PIPE) &&
1894 (error != ERROR_INVALID_HANDLE) ) 1893 (error != ERROR_INVALID_HANDLE))
1895 return GNUNET_NO; 1894 return GNUNET_NO;
1896 } 1895 }
1897 else if (waitstatus <= 0) 1896 else if (waitstatus <= 0)
1898 return GNUNET_NO; 1897 return GNUNET_NO;
1899 return GNUNET_YES; 1898 return GNUNET_YES;
@@ -1907,11 +1906,11 @@ pipe_read_ready (const struct GNUNET_DISK_FileHandle *fh)
1907 * @return #GNUNET_YES if the pipe is having an IO exception. 1906 * @return #GNUNET_YES if the pipe is having an IO exception.
1908 */ 1907 */
1909static int 1908static int
1910pipe_except_ready (const struct GNUNET_DISK_FileHandle *fh) 1909pipe_except_ready(const struct GNUNET_DISK_FileHandle *fh)
1911{ 1910{
1912 DWORD dwBytes; 1911 DWORD dwBytes;
1913 1912
1914 if (PeekNamedPipe (fh->h, NULL, 0, NULL, &dwBytes, NULL)) 1913 if (PeekNamedPipe(fh->h, NULL, 0, NULL, &dwBytes, NULL))
1915 return GNUNET_NO; 1914 return GNUNET_NO;
1916 return GNUNET_YES; 1915 return GNUNET_YES;
1917} 1916}
@@ -1931,38 +1930,38 @@ pipe_except_ready (const struct GNUNET_DISK_FileHandle *fh)
1931 * @return number of ready handles 1930 * @return number of ready handles
1932 */ 1931 */
1933static int 1932static int
1934check_handles_status (struct GNUNET_NETWORK_FDSet *fds, 1933check_handles_status(struct GNUNET_NETWORK_FDSet *fds,
1935 int except, 1934 int except,
1936 HANDLE set_for_sure) 1935 HANDLE set_for_sure)
1937{ 1936{
1938 const struct GNUNET_DISK_FileHandle *fh; 1937 const struct GNUNET_DISK_FileHandle *fh;
1939 unsigned int roff; 1938 unsigned int roff;
1940 unsigned int woff; 1939 unsigned int woff;
1941 1940
1942 for (woff = 0, roff = 0; roff < fds->handles_pos; roff++) 1941 for (woff = 0, roff = 0; roff < fds->handles_pos; roff++)
1943 {
1944 fh = fds->handles[roff];
1945 if (fh == set_for_sure)
1946 { 1942 {
1947 fds->handles[woff++] = fh; 1943 fh = fds->handles[roff];
1948 } 1944 if (fh == set_for_sure)
1949 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_PIPE) 1945 {
1950 { 1946 fds->handles[woff++] = fh;
1951 if ((except && pipe_except_ready (fh)) || 1947 }
1952 (!except && pipe_read_ready (fh))) 1948 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_PIPE)
1953 fds->handles[woff++] = fh; 1949 {
1954 } 1950 if ((except && pipe_except_ready(fh)) ||
1955 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_FILE) 1951 (!except && pipe_read_ready(fh)))
1956 { 1952 fds->handles[woff++] = fh;
1957 if (!except) 1953 }
1958 fds->handles[woff++] = fh; 1954 else if (fh->type == GNUNET_DISK_HANLDE_TYPE_FILE)
1959 } 1955 {
1960 else 1956 if (!except)
1961 { 1957 fds->handles[woff++] = fh;
1962 if (WAIT_OBJECT_0 == WaitForSingleObject (fh->h, 0)) 1958 }
1963 fds->handles[woff++] = fh; 1959 else
1960 {
1961 if (WAIT_OBJECT_0 == WaitForSingleObject(fh->h, 0))
1962 fds->handles[woff++] = fh;
1963 }
1964 } 1964 }
1965 }
1966 fds->handles_pos = woff; 1965 fds->handles_pos = woff;
1967 return woff; 1966 return woff;
1968} 1967}
@@ -1978,10 +1977,10 @@ check_handles_status (struct GNUNET_NETWORK_FDSet *fds,
1978 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error 1977 * @return number of selected sockets or pipes, #GNUNET_SYSERR on error
1979 */ 1978 */
1980int 1979int
1981GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds, 1980GNUNET_NETWORK_socket_select(struct GNUNET_NETWORK_FDSet *rfds,
1982 struct GNUNET_NETWORK_FDSet *wfds, 1981 struct GNUNET_NETWORK_FDSet *wfds,
1983 struct GNUNET_NETWORK_FDSet *efds, 1982 struct GNUNET_NETWORK_FDSet *efds,
1984 const struct GNUNET_TIME_Relative timeout) 1983 const struct GNUNET_TIME_Relative timeout)
1985{ 1984{
1986 const struct GNUNET_DISK_FileHandle *fh; 1985 const struct GNUNET_DISK_FileHandle *fh;
1987 int nfds; 1986 int nfds;
@@ -2003,68 +2002,68 @@ GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
2003 nfds = 0; 2002 nfds = 0;
2004 handles = 0; 2003 handles = 0;
2005 if (NULL != rfds) 2004 if (NULL != rfds)
2006 { 2005 {
2007 nfds = GNUNET_MAX (nfds, rfds->nsds); 2006 nfds = GNUNET_MAX(nfds, rfds->nsds);
2008 handles += rfds->handles_pos; 2007 handles += rfds->handles_pos;
2009 } 2008 }
2010 if (NULL != wfds) 2009 if (NULL != wfds)
2011 { 2010 {
2012 nfds = GNUNET_MAX (nfds, wfds->nsds); 2011 nfds = GNUNET_MAX(nfds, wfds->nsds);
2013 handles += wfds->handles_pos; 2012 handles += wfds->handles_pos;
2014 } 2013 }
2015 if (NULL != efds) 2014 if (NULL != efds)
2016 { 2015 {
2017 nfds = GNUNET_MAX (nfds, efds->nsds); 2016 nfds = GNUNET_MAX(nfds, efds->nsds);
2018 handles += efds->handles_pos; 2017 handles += efds->handles_pos;
2019 } 2018 }
2020 2019
2021 if ((0 == nfds) && 2020 if ((0 == nfds) &&
2022 (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == timeout.rel_value_us) && 2021 (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == timeout.rel_value_us) &&
2023 (0 == handles) ) 2022 (0 == handles))
2024 { 2023 {
2025 GNUNET_break (0); 2024 GNUNET_break(0);
2026 LOG (GNUNET_ERROR_TYPE_ERROR, 2025 LOG(GNUNET_ERROR_TYPE_ERROR,
2027 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"), 2026 _("Fatal internal logic error, process hangs in `%s' (abort with CTRL-C)!\n"),
2028 "select"); 2027 "select");
2029 } 2028 }
2030#define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set)) 2029#define SAFE_FD_ISSET(fd, set) (set != NULL && FD_ISSET(fd, set))
2031 /* calculate how long we need to wait in microseconds */ 2030 /* calculate how long we need to wait in microseconds */
2032 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) 2031 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2033 { 2032 {
2034 mcs_total = INFINITE; 2033 mcs_total = INFINITE;
2035 ms_rounded = INFINITE; 2034 ms_rounded = INFINITE;
2036 } 2035 }
2037 else 2036 else
2038 { 2037 {
2039 mcs_total = timeout.rel_value_us / GNUNET_TIME_UNIT_MICROSECONDS.rel_value_us; 2038 mcs_total = timeout.rel_value_us / GNUNET_TIME_UNIT_MICROSECONDS.rel_value_us;
2040 ms_rounded = (DWORD) (mcs_total / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us); 2039 ms_rounded = (DWORD)(mcs_total / GNUNET_TIME_UNIT_MILLISECONDS.rel_value_us);
2041 if (mcs_total > 0 && ms_rounded == 0) 2040 if (mcs_total > 0 && ms_rounded == 0)
2042 ms_rounded = 1; 2041 ms_rounded = 1;
2043 } 2042 }
2044 /* select() may be used as a portable way to sleep */ 2043 /* select() may be used as a portable way to sleep */
2045 if (! (rfds || wfds || efds)) 2044 if (!(rfds || wfds || efds))
2046 { 2045 {
2047 Sleep (ms_rounded); 2046 Sleep(ms_rounded);
2048 return 0; 2047 return 0;
2049 } 2048 }
2050 2049
2051 if (NULL == select_thread) 2050 if (NULL == select_thread)
2052 initialize_select_thread (); 2051 initialize_select_thread();
2053 2052
2054 FD_ZERO (&aread); 2053 FD_ZERO(&aread);
2055 FD_ZERO (&awrite); 2054 FD_ZERO(&awrite);
2056 FD_ZERO (&aexcept); 2055 FD_ZERO(&aexcept);
2057 if (rfds) 2056 if (rfds)
2058 FD_COPY (&rfds->sds, &aread); 2057 FD_COPY(&rfds->sds, &aread);
2059 if (wfds) 2058 if (wfds)
2060 FD_COPY (&wfds->sds, &awrite); 2059 FD_COPY(&wfds->sds, &awrite);
2061 if (efds) 2060 if (efds)
2062 FD_COPY (&efds->sds, &aexcept); 2061 FD_COPY(&efds->sds, &aexcept);
2063 2062
2064 /* Start by doing a fast check on sockets and pipes (without 2063 /* Start by doing a fast check on sockets and pipes (without
2065 waiting). It is cheap, and is sufficient most of the time. By 2064 waiting). It is cheap, and is sufficient most of the time. By
2066 profiling we detected that to be true in 90% of the cases. 2065 profiling we detected that to be true in 90% of the cases.
2067 */ 2066 */
2068 2067
2069 /* Do the select now */ 2068 /* Do the select now */
2070 select_timeout.tv_sec = 0; 2069 select_timeout.tv_sec = 0;
@@ -2072,304 +2071,306 @@ GNUNET_NETWORK_socket_select (struct GNUNET_NETWORK_FDSet *rfds,
2072 2071
2073 /* Copy all the writes to the except, so we can detect connect() errors */ 2072 /* Copy all the writes to the except, so we can detect connect() errors */
2074 for (i = 0; i < awrite.fd_count; i++) 2073 for (i = 0; i < awrite.fd_count; i++)
2075 FD_SET (awrite.fd_array[i], 2074 FD_SET(awrite.fd_array[i],
2076 &aexcept); 2075 &aexcept);
2077 if ( (aread.fd_count > 0) || 2076 if ((aread.fd_count > 0) ||
2078 (awrite.fd_count > 0) || 2077 (awrite.fd_count > 0) ||
2079 (aexcept.fd_count > 0) ) 2078 (aexcept.fd_count > 0))
2080 selectret = select (1, 2079 selectret = select(1,
2081 (NULL != rfds) ? &aread : NULL, 2080 (NULL != rfds) ? &aread : NULL,
2082 (NULL != wfds) ? &awrite : NULL, 2081 (NULL != wfds) ? &awrite : NULL,
2083 &aexcept, 2082 &aexcept,
2084 &select_timeout); 2083 &select_timeout);
2085 else 2084 else
2086 selectret = 0; 2085 selectret = 0;
2087 if (-1 == selectret) 2086 if (-1 == selectret)
2088 { 2087 {
2089 /* Throw an error early on, while we still have the context. */ 2088 /* Throw an error early on, while we still have the context. */
2090 LOG (GNUNET_ERROR_TYPE_ERROR, 2089 LOG(GNUNET_ERROR_TYPE_ERROR,
2091 "W32 select(%d, %d, %d) failed: %lu\n", 2090 "W32 select(%d, %d, %d) failed: %lu\n",
2092 rfds ? aread.fd_count : 0, 2091 rfds ? aread.fd_count : 0,
2093 wfds ? awrite.fd_count : 0, 2092 wfds ? awrite.fd_count : 0,
2094 aexcept.fd_count, 2093 aexcept.fd_count,
2095 GetLastError ()); 2094 GetLastError());
2096 GNUNET_assert (0); 2095 GNUNET_assert(0);
2097 } 2096 }
2098 2097
2099 /* Check aexcept, if something is in there and we copied that 2098 /* Check aexcept, if something is in there and we copied that
2100 FD before to detect connect() errors, add it back to the 2099 FD before to detect connect() errors, add it back to the
2101 write set to report errors. */ 2100 write set to report errors. */
2102 if (NULL != wfds) 2101 if (NULL != wfds)
2103 for (i = 0; i < aexcept.fd_count; i++) 2102 for (i = 0; i < aexcept.fd_count; i++)
2104 if (FD_ISSET (aexcept.fd_array[i], 2103 if (FD_ISSET(aexcept.fd_array[i],
2105 &wfds->sds)) 2104 &wfds->sds))
2106 FD_SET (aexcept.fd_array[i], 2105 FD_SET(aexcept.fd_array[i],
2107 &awrite); 2106 &awrite);
2108 2107
2109 2108
2110 /* If our select returned something or is a 0-timed request, then 2109 /* If our select returned something or is a 0-timed request, then
2111 also check the pipes and get out of here! */ 2110 also check the pipes and get out of here! */
2112 /* Sadly, it means code duplication :( */ 2111 /* Sadly, it means code duplication :( */
2113 if ( (selectret > 0) || (0 == mcs_total) ) 2112 if ((selectret > 0) || (0 == mcs_total))
2114 { 2113 {
2115 retcode = 0; 2114 retcode = 0;
2116 2115
2117 /* Read Pipes */ 2116 /* Read Pipes */
2118 if (rfds && (rfds->handles_pos > 0)) 2117 if (rfds && (rfds->handles_pos > 0))
2119 retcode += check_handles_status (rfds, GNUNET_NO, NULL); 2118 retcode += check_handles_status(rfds, GNUNET_NO, NULL);
2120 2119
2121 /* wfds handles remain untouched, on W32 2120 /* wfds handles remain untouched, on W32
2122 we pretend our pipes are "always" write-ready */ 2121 we pretend our pipes are "always" write-ready */
2123 2122
2124 /* except pipes */ 2123 /* except pipes */
2125 if (efds && (efds->handles_pos > 0)) 2124 if (efds && (efds->handles_pos > 0))
2126 retcode += check_handles_status (efds, GNUNET_YES, NULL); 2125 retcode += check_handles_status(efds, GNUNET_YES, NULL);
2127 2126
2128 if (rfds) 2127 if (rfds)
2129 { 2128 {
2130 GNUNET_NETWORK_fdset_zero (rfds); 2129 GNUNET_NETWORK_fdset_zero(rfds);
2131 if (selectret != -1) 2130 if (selectret != -1)
2132 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, selectret); 2131 GNUNET_NETWORK_fdset_copy_native(rfds, &aread, selectret);
2133 } 2132 }
2134 if (wfds) 2133 if (wfds)
2135 { 2134 {
2136 GNUNET_NETWORK_fdset_zero (wfds); 2135 GNUNET_NETWORK_fdset_zero(wfds);
2137 if (selectret != -1) 2136 if (selectret != -1)
2138 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, selectret); 2137 GNUNET_NETWORK_fdset_copy_native(wfds, &awrite, selectret);
2139 } 2138 }
2140 if (efds) 2139 if (efds)
2141 { 2140 {
2142 GNUNET_NETWORK_fdset_zero (efds); 2141 GNUNET_NETWORK_fdset_zero(efds);
2143 if (selectret != -1) 2142 if (selectret != -1)
2144 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, selectret); 2143 GNUNET_NETWORK_fdset_copy_native(efds, &aexcept, selectret);
2144 }
2145 if (-1 == selectret)
2146 return -1;
2147 /* Add our select() FDs to the total return value */
2148 retcode += selectret;
2149 return retcode;
2145 } 2150 }
2146 if (-1 == selectret)
2147 return -1;
2148 /* Add our select() FDs to the total return value */
2149 retcode += selectret;
2150 return retcode;
2151 }
2152 2151
2153 /* If we got this far, use slower implementation that is able to do a waiting select 2152 /* If we got this far, use slower implementation that is able to do a waiting select
2154 on both sockets and pipes simultaneously */ 2153 on both sockets and pipes simultaneously */
2155 2154
2156 /* Events for pipes */ 2155 /* Events for pipes */
2157 if (! hEventReadReady) 2156 if (!hEventReadReady)
2158 hEventReadReady = CreateEvent (NULL, TRUE, TRUE, NULL); 2157 hEventReadReady = CreateEvent(NULL, TRUE, TRUE, NULL);
2159 if (! hEventPipeWrite) 2158 if (!hEventPipeWrite)
2160 hEventPipeWrite = CreateEvent (NULL, TRUE, TRUE, NULL); 2159 hEventPipeWrite = CreateEvent(NULL, TRUE, TRUE, NULL);
2161 retcode = 0; 2160 retcode = 0;
2162 2161
2163 FD_ZERO (&aread); 2162 FD_ZERO(&aread);
2164 FD_ZERO (&awrite); 2163 FD_ZERO(&awrite);
2165 FD_ZERO (&aexcept); 2164 FD_ZERO(&aexcept);
2166 if (rfds) 2165 if (rfds)
2167 FD_COPY (&rfds->sds, &aread); 2166 FD_COPY(&rfds->sds, &aread);
2168 if (wfds) 2167 if (wfds)
2169 FD_COPY (&wfds->sds, &awrite); 2168 FD_COPY(&wfds->sds, &awrite);
2170 if (efds) 2169 if (efds)
2171 FD_COPY (&efds->sds, &aexcept); 2170 FD_COPY(&efds->sds, &aexcept);
2172 /* We will first Add the PIPES to the events */ 2171 /* We will first Add the PIPES to the events */
2173 /* Track how far in `handle_array` the read pipes go, 2172 /* Track how far in `handle_array` the read pipes go,
2174 so we may by-pass them quickly if none of them 2173 so we may by-pass them quickly if none of them
2175 are selected. */ 2174 are selected. */
2176 read_pipes_off = 0; 2175 read_pipes_off = 0;
2177 if (rfds && (rfds->handles_pos > 0)) 2176 if (rfds && (rfds->handles_pos > 0))
2178 {
2179 for (i = 0; i <rfds->handles_pos; i++)
2180 { 2177 {
2181 fh = rfds->handles[i]; 2178 for (i = 0; i < rfds->handles_pos; i++)
2182 if (fh->type == GNUNET_DISK_HANLDE_TYPE_EVENT)
2183 {
2184 handle_array[nhandles++] = fh->h;
2185 continue;
2186 }
2187 if (fh->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
2188 continue;
2189 /* Read zero bytes to check the status of the pipe */
2190 if (! ReadFile (fh->h, NULL, 0, NULL, fh->oOverlapRead))
2191 {
2192 DWORD error_code = GetLastError ();
2193
2194 if (error_code == ERROR_IO_PENDING)
2195 { 2179 {
2196 /* add as unready */ 2180 fh = rfds->handles[i];
2197 handle_array[nhandles++] = fh->oOverlapRead->hEvent; 2181 if (fh->type == GNUNET_DISK_HANLDE_TYPE_EVENT)
2198 read_pipes_off++; 2182 {
2183 handle_array[nhandles++] = fh->h;
2184 continue;
2185 }
2186 if (fh->type != GNUNET_DISK_HANLDE_TYPE_PIPE)
2187 continue;
2188 /* Read zero bytes to check the status of the pipe */
2189 if (!ReadFile(fh->h, NULL, 0, NULL, fh->oOverlapRead))
2190 {
2191 DWORD error_code = GetLastError();
2192
2193 if (error_code == ERROR_IO_PENDING)
2194 {
2195 /* add as unready */
2196 handle_array[nhandles++] = fh->oOverlapRead->hEvent;
2197 read_pipes_off++;
2198 }
2199 else
2200 {
2201 /* add as ready */
2202 handle_array[nhandles++] = hEventReadReady;
2203 read_pipes_off++;
2204 }
2205 }
2206 else
2207 {
2208 /* error also counts as ready */
2209 handle_array[nhandles++] = hEventReadReady;
2210 read_pipes_off++;
2211 }
2199 } 2212 }
2200 else
2201 {
2202 /* add as ready */
2203 handle_array[nhandles++] = hEventReadReady;
2204 read_pipes_off++;
2205 }
2206 }
2207 else
2208 {
2209 /* error also counts as ready */
2210 handle_array[nhandles++] = hEventReadReady;
2211 read_pipes_off++;
2212 }
2213 } 2213 }
2214 }
2215 2214
2216 if (wfds && (wfds->handles_pos > 0)) 2215 if (wfds && (wfds->handles_pos > 0))
2217 { 2216 {
2218 LOG (GNUNET_ERROR_TYPE_DEBUG, 2217 LOG(GNUNET_ERROR_TYPE_DEBUG,
2219 "Adding the write ready event to the array as %d\n", 2218 "Adding the write ready event to the array as %d\n",
2220 nhandles); 2219 nhandles);
2221 handle_array[nhandles++] = hEventPipeWrite; 2220 handle_array[nhandles++] = hEventPipeWrite;
2222 } 2221 }
2223 2222
2224 sp.status = 0; 2223 sp.status = 0;
2225 if (nfds > 0) 2224 if (nfds > 0)
2226 {
2227 LOG (GNUNET_ERROR_TYPE_DEBUG,
2228 "Adding the socket event to the array as %d\n",
2229 nhandles);
2230 handle_array[nhandles++] = select_finished_event;
2231 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2232 { 2225 {
2233 sp.tv = NULL; 2226 LOG(GNUNET_ERROR_TYPE_DEBUG,
2234 } 2227 "Adding the socket event to the array as %d\n",
2235 else 2228 nhandles);
2236 { 2229 handle_array[nhandles++] = select_finished_event;
2237 select_timeout.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us; 2230 if (timeout.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
2238 select_timeout.tv_usec = (timeout.rel_value_us - 2231 {
2239 (select_timeout.tv_sec * 2232 sp.tv = NULL;
2240 GNUNET_TIME_UNIT_SECONDS.rel_value_us)); 2233 }
2241 sp.tv = &select_timeout; 2234 else
2235 {
2236 select_timeout.tv_sec = timeout.rel_value_us / GNUNET_TIME_UNIT_SECONDS.rel_value_us;
2237 select_timeout.tv_usec = (timeout.rel_value_us -
2238 (select_timeout.tv_sec *
2239 GNUNET_TIME_UNIT_SECONDS.rel_value_us));
2240 sp.tv = &select_timeout;
2241 }
2242 FD_SET(select_wakeup_socket, &aread);
2243 do
2244 {
2245 i = recv(select_wakeup_socket,
2246 (char *)&returnedpos,
2247 1,
2248 0);
2249 }
2250 while (i == 1);
2251 sp.r = &aread;
2252 sp.w = &awrite;
2253 sp.e = &aexcept;
2254 /* Failed connections cause sockets to be set in errorfds on W32,
2255 * but on POSIX it should set them in writefds.
2256 * First copy all awrite sockets to aexcept, later we'll
2257 * check aexcept and set its contents in awrite as well
2258 * Sockets are also set in errorfds when OOB data is available,
2259 * but we don't use OOB data.
2260 */
2261 for (i = 0; i < awrite.fd_count; i++)
2262 FD_SET(awrite.fd_array[i],
2263 &aexcept);
2264 ResetEvent(select_finished_event);
2265 SetEvent(select_standby_event);
2242 } 2266 }
2243 FD_SET (select_wakeup_socket, &aread);
2244 do
2245 {
2246 i = recv (select_wakeup_socket,
2247 (char *) &returnedpos,
2248 1,
2249 0);
2250 } while (i == 1);
2251 sp.r = &aread;
2252 sp.w = &awrite;
2253 sp.e = &aexcept;
2254 /* Failed connections cause sockets to be set in errorfds on W32,
2255 * but on POSIX it should set them in writefds.
2256 * First copy all awrite sockets to aexcept, later we'll
2257 * check aexcept and set its contents in awrite as well
2258 * Sockets are also set in errorfds when OOB data is available,
2259 * but we don't use OOB data.
2260 */
2261 for (i = 0; i < awrite.fd_count; i++)
2262 FD_SET (awrite.fd_array[i],
2263 &aexcept);
2264 ResetEvent (select_finished_event);
2265 SetEvent (select_standby_event);
2266 }
2267 2267
2268 /* NULL-terminate array */ 2268 /* NULL-terminate array */
2269 handle_array[nhandles] = NULL; 2269 handle_array[nhandles] = NULL;
2270 LOG (GNUNET_ERROR_TYPE_DEBUG, 2270 LOG(GNUNET_ERROR_TYPE_DEBUG,
2271 "nfds: %d, handles: %d, will wait: %llu mcs\n", 2271 "nfds: %d, handles: %d, will wait: %llu mcs\n",
2272 nfds, 2272 nfds,
2273 nhandles, 2273 nhandles,
2274 mcs_total); 2274 mcs_total);
2275 if (nhandles) 2275 if (nhandles)
2276 { 2276 {
2277 returncode 2277 returncode
2278 = WaitForMultipleObjects (nhandles, 2278 = WaitForMultipleObjects(nhandles,
2279 handle_array, 2279 handle_array,
2280 FALSE, 2280 FALSE,
2281 ms_rounded); 2281 ms_rounded);
2282 LOG (GNUNET_ERROR_TYPE_DEBUG, 2282 LOG(GNUNET_ERROR_TYPE_DEBUG,
2283 "WaitForMultipleObjects Returned: %d\n", 2283 "WaitForMultipleObjects Returned: %d\n",
2284 returncode); 2284 returncode);
2285 } 2285 }
2286 else if (nfds > 0) 2286 else if (nfds > 0)
2287 { 2287 {
2288 GNUNET_break (0); /* This branch shouldn't actually be executed...*/ 2288 GNUNET_break(0); /* This branch shouldn't actually be executed...*/
2289 i = (int) WaitForSingleObject (select_finished_event, 2289 i = (int)WaitForSingleObject(select_finished_event,
2290 INFINITE); 2290 INFINITE);
2291 returncode = WAIT_TIMEOUT; 2291 returncode = WAIT_TIMEOUT;
2292 } 2292 }
2293 else 2293 else
2294 { 2294 {
2295 /* Shouldn't come this far. If it does - investigate. */ 2295 /* Shouldn't come this far. If it does - investigate. */
2296 GNUNET_assert (0); 2296 GNUNET_assert(0);
2297 } 2297 }
2298 2298
2299 if (nfds > 0) 2299 if (nfds > 0)
2300 {
2301 /* Don't wake up select-thread when delay is 0, it should return immediately
2302 * and wake up by itself.
2303 */
2304 if (0 != mcs_total)
2305 i = send (select_send_socket,
2306 (const char *) &returnedpos,
2307 1,
2308 0);
2309 i = (int) WaitForSingleObject (select_finished_event,
2310 INFINITE);
2311 LOG (GNUNET_ERROR_TYPE_DEBUG,
2312 "Finished waiting for the select thread: %d %d\n",
2313 i,
2314 sp.status);
2315 if (0 != mcs_total)
2316 { 2300 {
2317 do 2301 /* Don't wake up select-thread when delay is 0, it should return immediately
2318 { 2302 * and wake up by itself.
2319 i = recv (select_wakeup_socket, 2303 */
2320 (char *) &returnedpos, 2304 if (0 != mcs_total)
2321 1, 0); 2305 i = send(select_send_socket,
2322 } while (1 == i); 2306 (const char *)&returnedpos,
2307 1,
2308 0);
2309 i = (int)WaitForSingleObject(select_finished_event,
2310 INFINITE);
2311 LOG(GNUNET_ERROR_TYPE_DEBUG,
2312 "Finished waiting for the select thread: %d %d\n",
2313 i,
2314 sp.status);
2315 if (0 != mcs_total)
2316 {
2317 do
2318 {
2319 i = recv(select_wakeup_socket,
2320 (char *)&returnedpos,
2321 1, 0);
2322 }
2323 while (1 == i);
2324 }
2325 /* Check aexcept, add its contents to awrite */
2326 for (i = 0; i < aexcept.fd_count; i++)
2327 FD_SET(aexcept.fd_array[i], &awrite);
2323 } 2328 }
2324 /* Check aexcept, add its contents to awrite */
2325 for (i = 0; i < aexcept.fd_count; i++)
2326 FD_SET (aexcept.fd_array[i], &awrite);
2327 }
2328 2329
2329 returnedpos = returncode - WAIT_OBJECT_0; 2330 returnedpos = returncode - WAIT_OBJECT_0;
2330 LOG (GNUNET_ERROR_TYPE_DEBUG, 2331 LOG(GNUNET_ERROR_TYPE_DEBUG,
2331 "return pos is: %d\n", 2332 "return pos is: %d\n",
2332 returnedpos); 2333 returnedpos);
2333 2334
2334 if (rfds) 2335 if (rfds)
2335 {
2336 /* We queued a zero-long read on each pipe to check
2337 * its state, now we must cancel these read operations.
2338 * This must be done while rfds->handles_pos is still
2339 * intact and matches the number of read handles that we
2340 * got from the caller.
2341 */
2342 for (i = 0; i < rfds->handles_pos; i++)
2343 { 2336 {
2344 fh = rfds->handles[i]; 2337 /* We queued a zero-long read on each pipe to check
2345 if (GNUNET_DISK_HANLDE_TYPE_PIPE == fh->type) 2338 * its state, now we must cancel these read operations.
2346 CancelIo (fh->h); 2339 * This must be done while rfds->handles_pos is still
2347 } 2340 * intact and matches the number of read handles that we
2341 * got from the caller.
2342 */
2343 for (i = 0; i < rfds->handles_pos; i++)
2344 {
2345 fh = rfds->handles[i];
2346 if (GNUNET_DISK_HANLDE_TYPE_PIPE == fh->type)
2347 CancelIo(fh->h);
2348 }
2348 2349
2349 /* We may have some pipes ready for reading. */ 2350 /* We may have some pipes ready for reading. */
2350 if (returnedpos < read_pipes_off) 2351 if (returnedpos < read_pipes_off)
2351 retcode += check_handles_status (rfds, GNUNET_NO, handle_array[returnedpos]); 2352 retcode += check_handles_status(rfds, GNUNET_NO, handle_array[returnedpos]);
2352 else 2353 else
2353 rfds->handles_pos = 0; 2354 rfds->handles_pos = 0;
2354 2355
2355 if (-1 != sp.status) 2356 if (-1 != sp.status)
2356 GNUNET_NETWORK_fdset_copy_native (rfds, &aread, retcode); 2357 GNUNET_NETWORK_fdset_copy_native(rfds, &aread, retcode);
2357 } 2358 }
2358 if (wfds) 2359 if (wfds)
2359 { 2360 {
2360 retcode += wfds->handles_pos; 2361 retcode += wfds->handles_pos;
2361 /* wfds handles remain untouched */ 2362 /* wfds handles remain untouched */
2362 if (-1 != sp.status) 2363 if (-1 != sp.status)
2363 GNUNET_NETWORK_fdset_copy_native (wfds, &awrite, retcode); 2364 GNUNET_NETWORK_fdset_copy_native(wfds, &awrite, retcode);
2364 } 2365 }
2365 if (efds) 2366 if (efds)
2366 { 2367 {
2367 retcode += check_handles_status (rfds, 2368 retcode += check_handles_status(rfds,
2368 GNUNET_YES, 2369 GNUNET_YES,
2369 returnedpos < nhandles ? handle_array[returnedpos] : NULL); 2370 returnedpos < nhandles ? handle_array[returnedpos] : NULL);
2370 if (-1 != sp.status) 2371 if (-1 != sp.status)
2371 GNUNET_NETWORK_fdset_copy_native (efds, &aexcept, retcode); 2372 GNUNET_NETWORK_fdset_copy_native(efds, &aexcept, retcode);
2372 } 2373 }
2373 2374
2374 if (sp.status > 0) 2375 if (sp.status > 0)
2375 retcode += sp.status; 2376 retcode += sp.status;
diff --git a/src/util/op.c b/src/util/op.c
index 8fca7553e..20a0d3b0d 100644
--- a/src/util/op.c
+++ b/src/util/op.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file 22 * @file
@@ -30,10 +30,9 @@
30#include "platform.h" 30#include "platform.h"
31#include "gnunet_util_lib.h" 31#include "gnunet_util_lib.h"
32 32
33#define LOG(kind,...) GNUNET_log_from (kind, "util-op", __VA_ARGS__) 33#define LOG(kind, ...) GNUNET_log_from(kind, "util-op", __VA_ARGS__)
34 34
35struct OperationListItem 35struct OperationListItem {
36{
37 struct OperationListItem *prev; 36 struct OperationListItem *prev;
38 struct OperationListItem *next; 37 struct OperationListItem *next;
39 38
@@ -63,8 +62,7 @@ struct OperationListItem
63 * Operations handle. 62 * Operations handle.
64 */ 63 */
65 64
66struct GNUNET_OP_Handle 65struct GNUNET_OP_Handle {
67{
68 /** 66 /**
69 * First operation in the linked list. 67 * First operation in the linked list.
70 */ 68 */
@@ -86,9 +84,9 @@ struct GNUNET_OP_Handle
86 * Create new operations handle. 84 * Create new operations handle.
87 */ 85 */
88struct GNUNET_OP_Handle * 86struct GNUNET_OP_Handle *
89GNUNET_OP_create () 87GNUNET_OP_create()
90{ 88{
91 return GNUNET_new (struct GNUNET_OP_Handle); 89 return GNUNET_new(struct GNUNET_OP_Handle);
92} 90}
93 91
94 92
@@ -96,9 +94,9 @@ GNUNET_OP_create ()
96 * Destroy operations handle. 94 * Destroy operations handle.
97 */ 95 */
98void 96void
99GNUNET_OP_destroy (struct GNUNET_OP_Handle *h) 97GNUNET_OP_destroy(struct GNUNET_OP_Handle *h)
100{ 98{
101 GNUNET_free (h); 99 GNUNET_free(h);
102} 100}
103 101
104 102
@@ -111,7 +109,7 @@ GNUNET_OP_destroy (struct GNUNET_OP_Handle *h)
111 * @return Operation ID to use. 109 * @return Operation ID to use.
112 */ 110 */
113uint64_t 111uint64_t
114GNUNET_OP_get_next_id (struct GNUNET_OP_Handle *h) 112GNUNET_OP_get_next_id(struct GNUNET_OP_Handle *h)
115{ 113{
116 return ++h->last_op_id; 114 return ++h->last_op_id;
117} 115}
@@ -128,8 +126,8 @@ GNUNET_OP_get_next_id (struct GNUNET_OP_Handle *h)
128 * @return Operation, or NULL if not found. 126 * @return Operation, or NULL if not found.
129 */ 127 */
130static struct OperationListItem * 128static struct OperationListItem *
131op_find (struct GNUNET_OP_Handle *h, 129op_find(struct GNUNET_OP_Handle *h,
132 uint64_t op_id) 130 uint64_t op_id)
133{ 131{
134 struct OperationListItem *op; 132 struct OperationListItem *op;
135 133
@@ -158,23 +156,24 @@ op_find (struct GNUNET_OP_Handle *h,
158 * #GNUNET_NO if not found. 156 * #GNUNET_NO if not found.
159 */ 157 */
160int 158int
161GNUNET_OP_get (struct GNUNET_OP_Handle *h, 159GNUNET_OP_get(struct GNUNET_OP_Handle *h,
162 uint64_t op_id, 160 uint64_t op_id,
163 GNUNET_ResultCallback *result_cb, 161 GNUNET_ResultCallback *result_cb,
164 void **cls, 162 void **cls,
165 void **ctx) 163 void **ctx)
166{ 164{
167 struct OperationListItem *op = op_find (h, op_id); 165 struct OperationListItem *op = op_find(h, op_id);
166
168 if (NULL != op) 167 if (NULL != op)
169 { 168 {
170 if (NULL != result_cb) 169 if (NULL != result_cb)
171 *result_cb = op->result_cb; 170 *result_cb = op->result_cb;
172 if (NULL != cls) 171 if (NULL != cls)
173 *cls = op->cls; 172 *cls = op->cls;
174 if (NULL != ctx) 173 if (NULL != ctx)
175 *ctx = op->ctx; 174 *ctx = op->ctx;
176 return GNUNET_YES; 175 return GNUNET_YES;
177 } 176 }
178 return GNUNET_NO; 177 return GNUNET_NO;
179} 178}
180 179
@@ -194,24 +193,24 @@ GNUNET_OP_get (struct GNUNET_OP_Handle *h,
194 * @return ID of the new operation. 193 * @return ID of the new operation.
195 */ 194 */
196uint64_t 195uint64_t
197GNUNET_OP_add (struct GNUNET_OP_Handle *h, 196GNUNET_OP_add(struct GNUNET_OP_Handle *h,
198 GNUNET_ResultCallback result_cb, 197 GNUNET_ResultCallback result_cb,
199 void *cls, 198 void *cls,
200 void *ctx) 199 void *ctx)
201{ 200{
202 struct OperationListItem *op; 201 struct OperationListItem *op;
203 202
204 op = GNUNET_new (struct OperationListItem); 203 op = GNUNET_new(struct OperationListItem);
205 op->op_id = GNUNET_OP_get_next_id (h); 204 op->op_id = GNUNET_OP_get_next_id(h);
206 op->result_cb = result_cb; 205 op->result_cb = result_cb;
207 op->cls = cls; 206 op->cls = cls;
208 op->ctx = ctx; 207 op->ctx = ctx;
209 GNUNET_CONTAINER_DLL_insert_tail (h->op_head, 208 GNUNET_CONTAINER_DLL_insert_tail(h->op_head,
210 h->op_tail, 209 h->op_tail,
211 op); 210 op);
212 LOG (GNUNET_ERROR_TYPE_DEBUG, 211 LOG(GNUNET_ERROR_TYPE_DEBUG,
213 "%p Added operation #%" PRIu64 "\n", 212 "%p Added operation #%" PRIu64 "\n",
214 h, op->op_id); 213 h, op->op_id);
215 return op->op_id; 214 return op->op_id;
216} 215}
217 216
@@ -241,38 +240,38 @@ GNUNET_OP_add (struct GNUNET_OP_Handle *h,
241 * #GNUNET_NO if the operation was not found. 240 * #GNUNET_NO if the operation was not found.
242 */ 241 */
243static int 242static int
244op_result (struct GNUNET_OP_Handle *h, 243op_result(struct GNUNET_OP_Handle *h,
245 uint64_t op_id, 244 uint64_t op_id,
246 int64_t result_code, 245 int64_t result_code,
247 const void *data, 246 const void *data,
248 uint16_t data_size, 247 uint16_t data_size,
249 void **ctx, 248 void **ctx,
250 uint8_t cancel) 249 uint8_t cancel)
251{ 250{
252 if (0 == op_id) 251 if (0 == op_id)
253 return GNUNET_NO; 252 return GNUNET_NO;
254 253
255 struct OperationListItem *op = op_find (h, op_id); 254 struct OperationListItem *op = op_find(h, op_id);
256 if (NULL == op) 255 if (NULL == op)
257 { 256 {
258 LOG (GNUNET_ERROR_TYPE_WARNING, 257 LOG(GNUNET_ERROR_TYPE_WARNING,
259 "Could not find operation #%" PRIu64 "\n", op_id); 258 "Could not find operation #%" PRIu64 "\n", op_id);
260 return GNUNET_NO; 259 return GNUNET_NO;
261 } 260 }
262 261
263 if (NULL != ctx) 262 if (NULL != ctx)
264 *ctx = op->ctx; 263 *ctx = op->ctx;
265 264
266 GNUNET_CONTAINER_DLL_remove (h->op_head, 265 GNUNET_CONTAINER_DLL_remove(h->op_head,
267 h->op_tail, 266 h->op_tail,
268 op); 267 op);
269 268
270 if ( (GNUNET_YES != cancel) && 269 if ((GNUNET_YES != cancel) &&
271 (NULL != op->result_cb) ) 270 (NULL != op->result_cb))
272 op->result_cb (op->cls, 271 op->result_cb(op->cls,
273 result_code, data, 272 result_code, data,
274 data_size); 273 data_size);
275 GNUNET_free (op); 274 GNUNET_free(op);
276 return GNUNET_YES; 275 return GNUNET_YES;
277} 276}
278 277
@@ -297,17 +296,17 @@ op_result (struct GNUNET_OP_Handle *h,
297 * #GNUNET_NO if the operation was not found. 296 * #GNUNET_NO if the operation was not found.
298 */ 297 */
299int 298int
300GNUNET_OP_result (struct GNUNET_OP_Handle *h, 299GNUNET_OP_result(struct GNUNET_OP_Handle *h,
301 uint64_t op_id, 300 uint64_t op_id,
302 int64_t result_code, 301 int64_t result_code,
303 const void *data, 302 const void *data,
304 uint16_t data_size, 303 uint16_t data_size,
305 void **ctx) 304 void **ctx)
306{ 305{
307 LOG (GNUNET_ERROR_TYPE_DEBUG, 306 LOG(GNUNET_ERROR_TYPE_DEBUG,
308 "%p Received result for operation #%" PRIu64 ": %" PRId64 " (size: %u)\n", 307 "%p Received result for operation #%" PRIu64 ": %" PRId64 " (size: %u)\n",
309 h, op_id, result_code, data_size); 308 h, op_id, result_code, data_size);
310 return op_result (h, op_id, result_code, data, data_size, ctx, GNUNET_NO); 309 return op_result(h, op_id, result_code, data, data_size, ctx, GNUNET_NO);
311} 310}
312 311
313 312
@@ -323,11 +322,11 @@ GNUNET_OP_result (struct GNUNET_OP_Handle *h,
323 * #GNUNET_NO if the operation was not found. 322 * #GNUNET_NO if the operation was not found.
324 */ 323 */
325int 324int
326GNUNET_OP_remove (struct GNUNET_OP_Handle *h, 325GNUNET_OP_remove(struct GNUNET_OP_Handle *h,
327 uint64_t op_id) 326 uint64_t op_id)
328{ 327{
329 LOG (GNUNET_ERROR_TYPE_DEBUG, 328 LOG(GNUNET_ERROR_TYPE_DEBUG,
330 "%p Cancelling operation #%" PRIu64 "\n", 329 "%p Cancelling operation #%" PRIu64 "\n",
331 h, op_id); 330 h, op_id);
332 return op_result (h, op_id, 0, NULL, 0, NULL, GNUNET_YES); 331 return op_result(h, op_id, 0, NULL, 0, NULL, GNUNET_YES);
333} 332}
diff --git a/src/util/os_installation.c b/src/util/os_installation.c
index 3e5a99811..656468707 100644
--- a/src/util/os_installation.c
+++ b/src/util/os_installation.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file src/util/os_installation.c 22 * @file src/util/os_installation.c
@@ -45,13 +45,13 @@
45 45
46 46
47#define LOG(kind, ...) \ 47#define LOG(kind, ...) \
48 GNUNET_log_from (kind, "util-os-installation", __VA_ARGS__) 48 GNUNET_log_from(kind, "util-os-installation", __VA_ARGS__)
49 49
50#define LOG_STRERROR_FILE(kind, syscall, filename) \ 50#define LOG_STRERROR_FILE(kind, syscall, filename) \
51 GNUNET_log_from_strerror_file (kind, \ 51 GNUNET_log_from_strerror_file(kind, \
52 "util-os-installation", \ 52 "util-os-installation", \
53 syscall, \ 53 syscall, \
54 filename) 54 filename)
55 55
56 56
57/** 57/**
@@ -91,7 +91,7 @@ static int gettextinit = 0;
91 * Return default project data used by 'libgnunetutil' for GNUnet. 91 * Return default project data used by 'libgnunetutil' for GNUnet.
92 */ 92 */
93const struct GNUNET_OS_ProjectData * 93const struct GNUNET_OS_ProjectData *
94GNUNET_OS_project_data_default (void) 94GNUNET_OS_project_data_default(void)
95{ 95{
96 return &default_pd; 96 return &default_pd;
97} 97}
@@ -101,16 +101,16 @@ GNUNET_OS_project_data_default (void)
101 * @return current project data. 101 * @return current project data.
102 */ 102 */
103const struct GNUNET_OS_ProjectData * 103const struct GNUNET_OS_ProjectData *
104GNUNET_OS_project_data_get () 104GNUNET_OS_project_data_get()
105{ 105{
106 if (0 == gettextinit) 106 if (0 == gettextinit)
107 { 107 {
108 char *path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR); 108 char *path = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LOCALEDIR);
109 if (NULL != path) 109 if (NULL != path)
110 bindtextdomain (PACKAGE, path); 110 bindtextdomain(PACKAGE, path);
111 GNUNET_free (path); 111 GNUNET_free(path);
112 gettextinit = 1; 112 gettextinit = 1;
113 } 113 }
114 return current_pd; 114 return current_pd;
115} 115}
116 116
@@ -121,17 +121,17 @@ GNUNET_OS_project_data_get ()
121 * @param pd project data used to determine paths 121 * @param pd project data used to determine paths
122 */ 122 */
123void 123void
124GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd) 124GNUNET_OS_init(const struct GNUNET_OS_ProjectData *pd)
125{ 125{
126 if (0 == gettextinit) 126 if (0 == gettextinit)
127 { 127 {
128 char *path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR); 128 char *path = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LOCALEDIR);
129 if (NULL != path) 129 if (NULL != path)
130 bindtextdomain (PACKAGE, path); 130 bindtextdomain(PACKAGE, path);
131 GNUNET_free (path); 131 GNUNET_free(path);
132 gettextinit = 1; 132 gettextinit = 1;
133 } 133 }
134 GNUNET_assert (NULL != pd); 134 GNUNET_assert(NULL != pd);
135 current_pd = pd; 135 current_pd = pd;
136} 136}
137 137
@@ -143,7 +143,7 @@ GNUNET_OS_init (const struct GNUNET_OS_ProjectData *pd)
143 * @return NULL on error 143 * @return NULL on error
144 */ 144 */
145static char * 145static char *
146get_path_from_proc_maps () 146get_path_from_proc_maps()
147{ 147{
148 char fn[64]; 148 char fn[64];
149 char line[1024]; 149 char line[1024];
@@ -151,22 +151,22 @@ get_path_from_proc_maps ()
151 FILE *f; 151 FILE *f;
152 char *lgu; 152 char *lgu;
153 153
154 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/maps", getpid ()); 154 GNUNET_snprintf(fn, sizeof(fn), "/proc/%u/maps", getpid());
155 if (NULL == (f = fopen (fn, "r"))) 155 if (NULL == (f = fopen(fn, "r")))
156 return NULL; 156 return NULL;
157 while (NULL != fgets (line, sizeof (line), f)) 157 while (NULL != fgets(line, sizeof(line), f))
158 {
159 if ((1 == SSCANF (line,
160 "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s",
161 dir)) &&
162 (NULL != (lgu = strstr (dir, current_pd->libname))))
163 { 158 {
164 lgu[0] = '\0'; 159 if ((1 == SSCANF(line,
165 fclose (f); 160 "%*x-%*x %*c%*c%*c%*c %*x %*2x:%*2x %*u%*[ ]%1023s",
166 return GNUNET_strdup (dir); 161 dir)) &&
162 (NULL != (lgu = strstr(dir, current_pd->libname))))
163 {
164 lgu[0] = '\0';
165 fclose(f);
166 return GNUNET_strdup(dir);
167 }
167 } 168 }
168 } 169 fclose(f);
169 fclose (f);
170 return NULL; 170 return NULL;
171} 171}
172 172
@@ -177,37 +177,37 @@ get_path_from_proc_maps ()
177 * @return NULL on error 177 * @return NULL on error
178 */ 178 */
179static char * 179static char *
180get_path_from_proc_exe () 180get_path_from_proc_exe()
181{ 181{
182 char fn[64]; 182 char fn[64];
183 char lnk[1024]; 183 char lnk[1024];
184 ssize_t size; 184 ssize_t size;
185 char *lep; 185 char *lep;
186 186
187 GNUNET_snprintf (fn, sizeof (fn), "/proc/%u/exe", getpid ()); 187 GNUNET_snprintf(fn, sizeof(fn), "/proc/%u/exe", getpid());
188 size = readlink (fn, lnk, sizeof (lnk) - 1); 188 size = readlink(fn, lnk, sizeof(lnk) - 1);
189 if (size <= 0) 189 if (size <= 0)
190 { 190 {
191 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "readlink", fn); 191 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "readlink", fn);
192 return NULL; 192 return NULL;
193 } 193 }
194 GNUNET_assert (((size_t) size) < sizeof (lnk)); 194 GNUNET_assert(((size_t)size) < sizeof(lnk));
195 lnk[size] = '\0'; 195 lnk[size] = '\0';
196 while ((lnk[size] != '/') && (size > 0)) 196 while ((lnk[size] != '/') && (size > 0))
197 size--; 197 size--;
198 GNUNET_asprintf (&lep, "/%s/libexec/", current_pd->project_dirname); 198 GNUNET_asprintf(&lep, "/%s/libexec/", current_pd->project_dirname);
199 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */ 199 /* test for being in lib/gnunet/libexec/ or lib/MULTIARCH/gnunet/libexec */
200 if ((((size_t) size) > strlen (lep)) && 200 if ((((size_t)size) > strlen(lep)) &&
201 (0 == strcmp (lep, &lnk[size - strlen (lep)]))) 201 (0 == strcmp(lep, &lnk[size - strlen(lep)])))
202 size -= strlen (lep) - 1; 202 size -= strlen(lep) - 1;
203 GNUNET_free (lep); 203 GNUNET_free(lep);
204 if ((size < 4) || (lnk[size - 4] != '/')) 204 if ((size < 4) || (lnk[size - 4] != '/'))
205 { 205 {
206 /* not installed in "/bin/" -- binary path probably useless */ 206 /* not installed in "/bin/" -- binary path probably useless */
207 return NULL; 207 return NULL;
208 } 208 }
209 lnk[size] = '\0'; 209 lnk[size] = '\0';
210 return GNUNET_strdup (lnk); 210 return GNUNET_strdup(lnk);
211} 211}
212#endif 212#endif
213 213
@@ -222,20 +222,23 @@ static HINSTANCE dll_instance;
222 * and hInstance saving. 222 * and hInstance saving.
223 */ 223 */
224BOOL WINAPI 224BOOL WINAPI
225DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) 225DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
226{ 226{
227 switch (fdwReason) 227 switch (fdwReason)
228 { 228 {
229 case DLL_PROCESS_ATTACH: 229 case DLL_PROCESS_ATTACH:
230 dll_instance = hinstDLL; 230 dll_instance = hinstDLL;
231 break; 231 break;
232 case DLL_THREAD_ATTACH: 232
233 break; 233 case DLL_THREAD_ATTACH:
234 case DLL_THREAD_DETACH: 234 break;
235 break; 235
236 case DLL_PROCESS_DETACH: 236 case DLL_THREAD_DETACH:
237 break; 237 break;
238 } 238
239 case DLL_PROCESS_DETACH:
240 break;
241 }
239 return TRUE; 242 return TRUE;
240} 243}
241 244
@@ -246,7 +249,7 @@ DllMain (HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
246 * @return NULL on error 249 * @return NULL on error
247 */ 250 */
248static char * 251static char *
249get_path_from_module_filename () 252get_path_from_module_filename()
250{ 253{
251 size_t pathlen = 512; 254 size_t pathlen = 512;
252 DWORD real_pathlen; 255 DWORD real_pathlen;
@@ -261,15 +264,16 @@ get_path_from_module_filename ()
261 * it fits, or we exceed the threshold. 264 * it fits, or we exceed the threshold.
262 */ 265 */
263 do 266 do
264 { 267 {
265 pathlen = pathlen * 2; 268 pathlen = pathlen * 2;
266 modulepath = GNUNET_realloc (modulepath, pathlen * sizeof (wchar_t)); 269 modulepath = GNUNET_realloc(modulepath, pathlen * sizeof(wchar_t));
267 SetLastError (0); 270 SetLastError(0);
268 real_pathlen = 271 real_pathlen =
269 GetModuleFileNameW (dll_instance, modulepath, pathlen * sizeof (wchar_t)); 272 GetModuleFileNameW(dll_instance, modulepath, pathlen * sizeof(wchar_t));
270 } while (real_pathlen >= pathlen && pathlen < 16 * 1024); 273 }
274 while (real_pathlen >= pathlen && pathlen < 16 * 1024);
271 if (real_pathlen >= pathlen) 275 if (real_pathlen >= pathlen)
272 GNUNET_assert (0); 276 GNUNET_assert(0);
273 /* To be safe */ 277 /* To be safe */
274 modulepath[real_pathlen] = '\0'; 278 modulepath[real_pathlen] = '\0';
275 279
@@ -281,45 +285,45 @@ get_path_from_module_filename ()
281 /* Now modulepath holds full path to the directory where libgnunetutil is. 285 /* Now modulepath holds full path to the directory where libgnunetutil is.
282 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>. 286 * This directory should look like <GNUNET_PREFIX>/bin or <GNUNET_PREFIX>.
283 */ 287 */
284 if (wcschr (modulepath, L'/') || wcschr (modulepath, L'\\')) 288 if (wcschr(modulepath, L'/') || wcschr(modulepath, L'\\'))
285 {
286 /* At least one directory component (i.e. we're not in a root directory) */
287 wchar_t *dirname = idx;
288 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
289 dirname--;
290 *dirname = L'\0';
291 if (dirname > modulepath)
292 { 289 {
293 dirname++; 290 /* At least one directory component (i.e. we're not in a root directory) */
294 /* Now modulepath holds full path to the parent directory of the directory 291 wchar_t *dirname = idx;
295 * where libgnunetutil is. 292 while ((dirname > modulepath) && (*dirname != L'\\') && (*dirname != L'/'))
296 * dirname holds the name of the directory where libgnunetutil is.
297 */
298 if (wcsicmp (dirname, L"bin") == 0)
299 {
300 /* pass */
301 }
302 else
303 {
304 /* Roll back our changes to modulepath */
305 dirname--; 293 dirname--;
306 *dirname = L'/'; 294 *dirname = L'\0';
307 } 295 if (dirname > modulepath)
296 {
297 dirname++;
298 /* Now modulepath holds full path to the parent directory of the directory
299 * where libgnunetutil is.
300 * dirname holds the name of the directory where libgnunetutil is.
301 */
302 if (wcsicmp(dirname, L"bin") == 0)
303 {
304 /* pass */
305 }
306 else
307 {
308 /* Roll back our changes to modulepath */
309 dirname--;
310 *dirname = L'/';
311 }
312 }
308 } 313 }
309 }
310 314
311 /* modulepath is GNUNET_PREFIX */ 315 /* modulepath is GNUNET_PREFIX */
312 u8_string = 316 u8_string =
313 u16_to_u8 (modulepath, wcslen (modulepath), NULL, &u8_string_length); 317 u16_to_u8(modulepath, wcslen(modulepath), NULL, &u8_string_length);
314 if (NULL == u8_string) 318 if (NULL == u8_string)
315 GNUNET_assert (0); 319 GNUNET_assert(0);
316 320
317 upath = GNUNET_malloc (u8_string_length + 1); 321 upath = GNUNET_malloc(u8_string_length + 1);
318 GNUNET_memcpy (upath, u8_string, u8_string_length); 322 GNUNET_memcpy(upath, u8_string, u8_string_length);
319 upath[u8_string_length] = '\0'; 323 upath[u8_string_length] = '\0';
320 324
321 free (u8_string); 325 free(u8_string);
322 GNUNET_free (modulepath); 326 GNUNET_free(modulepath);
323 327
324 return upath; 328 return upath;
325} 329}
@@ -343,7 +347,7 @@ typedef int (*MyNSGetExecutablePathProto) (char *buf, size_t *bufsize);
343 * @return NULL on error 347 * @return NULL on error
344 */ 348 */
345static char * 349static char *
346get_path_from_NSGetExecutablePath () 350get_path_from_NSGetExecutablePath()
347{ 351{
348 static char zero = '\0'; 352 static char zero = '\0';
349 char *path; 353 char *path;
@@ -352,22 +356,22 @@ get_path_from_NSGetExecutablePath ()
352 356
353 path = NULL; 357 path = NULL;
354 if (NULL == 358 if (NULL ==
355 (func = (MyNSGetExecutablePathProto) dlsym (RTLD_DEFAULT, 359 (func = (MyNSGetExecutablePathProto)dlsym(RTLD_DEFAULT,
356 "_NSGetExecutablePath"))) 360 "_NSGetExecutablePath")))
357 return NULL; 361 return NULL;
358 path = &zero; 362 path = &zero;
359 len = 0; 363 len = 0;
360 /* get the path len, including the trailing \0 */ 364 /* get the path len, including the trailing \0 */
361 (void) func (path, &len); 365 (void)func(path, &len);
362 if (0 == len) 366 if (0 == len)
363 return NULL; 367 return NULL;
364 path = GNUNET_malloc (len); 368 path = GNUNET_malloc(len);
365 if (0 != func (path, &len)) 369 if (0 != func(path, &len))
366 { 370 {
367 GNUNET_free (path); 371 GNUNET_free(path);
368 return NULL; 372 return NULL;
369 } 373 }
370 len = strlen (path); 374 len = strlen(path);
371 while ((path[len] != '/') && (len > 0)) 375 while ((path[len] != '/') && (len > 0))
372 len--; 376 len--;
373 path[len] = '\0'; 377 path[len] = '\0';
@@ -381,7 +385,7 @@ get_path_from_NSGetExecutablePath ()
381 * @return NULL on error 385 * @return NULL on error
382 */ 386 */
383static char * 387static char *
384get_path_from_dyld_image () 388get_path_from_dyld_image()
385{ 389{
386 const char *path; 390 const char *path;
387 char *p; 391 char *p;
@@ -389,23 +393,23 @@ get_path_from_dyld_image ()
389 unsigned int i; 393 unsigned int i;
390 int c; 394 int c;
391 395
392 c = _dyld_image_count (); 396 c = _dyld_image_count();
393 for (i = 0; i < c; i++) 397 for (i = 0; i < c; i++)
394 { 398 {
395 if (((const void *) _dyld_get_image_header (i)) != 399 if (((const void *)_dyld_get_image_header(i)) !=
396 ((const void *) &_mh_dylib_header)) 400 ((const void *)&_mh_dylib_header))
397 continue; 401 continue;
398 path = _dyld_get_image_name (i); 402 path = _dyld_get_image_name(i);
399 if ((NULL == path) || (0 == strlen (path))) 403 if ((NULL == path) || (0 == strlen(path)))
400 continue; 404 continue;
401 p = GNUNET_strdup (path); 405 p = GNUNET_strdup(path);
402 s = p + strlen (p); 406 s = p + strlen(p);
403 while ((s > p) && ('/' != *s)) 407 while ((s > p) && ('/' != *s))
404 s--; 408 s--;
405 s++; 409 s++;
406 *s = '\0'; 410 *s = '\0';
407 return p; 411 return p;
408 } 412 }
409 return NULL; 413 return NULL;
410} 414}
411#endif 415#endif
@@ -419,7 +423,7 @@ get_path_from_dyld_image ()
419 * @return path to binary, NULL if not found 423 * @return path to binary, NULL if not found
420 */ 424 */
421static char * 425static char *
422get_path_from_PATH (const char *binary) 426get_path_from_PATH(const char *binary)
423{ 427{
424 char *path; 428 char *path;
425 char *pos; 429 char *pos;
@@ -427,39 +431,39 @@ get_path_from_PATH (const char *binary)
427 char *buf; 431 char *buf;
428 const char *p; 432 const char *p;
429 433
430 if (NULL == (p = getenv ("PATH"))) 434 if (NULL == (p = getenv("PATH")))
431 return NULL; 435 return NULL;
432#if WINDOWS 436#if WINDOWS
433 /* On W32 look in CWD first. */ 437 /* On W32 look in CWD first. */
434 GNUNET_asprintf (&path, ".%c%s", PATH_SEPARATOR, p); 438 GNUNET_asprintf(&path, ".%c%s", PATH_SEPARATOR, p);
435#else 439#else
436 path = GNUNET_strdup (p); /* because we write on it */ 440 path = GNUNET_strdup(p); /* because we write on it */
437#endif 441#endif
438 buf = GNUNET_malloc (strlen (path) + strlen (binary) + 1 + 1); 442 buf = GNUNET_malloc(strlen(path) + strlen(binary) + 1 + 1);
439 pos = path; 443 pos = path;
440 while (NULL != (end = strchr (pos, PATH_SEPARATOR))) 444 while (NULL != (end = strchr(pos, PATH_SEPARATOR)))
441 {
442 *end = '\0';
443 sprintf (buf, "%s/%s", pos, binary);
444 if (GNUNET_DISK_file_test (buf) == GNUNET_YES)
445 { 445 {
446 pos = GNUNET_strdup (pos); 446 *end = '\0';
447 GNUNET_free (buf); 447 sprintf(buf, "%s/%s", pos, binary);
448 GNUNET_free (path); 448 if (GNUNET_DISK_file_test(buf) == GNUNET_YES)
449 {
450 pos = GNUNET_strdup(pos);
451 GNUNET_free(buf);
452 GNUNET_free(path);
453 return pos;
454 }
455 pos = end + 1;
456 }
457 sprintf(buf, "%s/%s", pos, binary);
458 if (GNUNET_YES == GNUNET_DISK_file_test(buf))
459 {
460 pos = GNUNET_strdup(pos);
461 GNUNET_free(buf);
462 GNUNET_free(path);
449 return pos; 463 return pos;
450 } 464 }
451 pos = end + 1; 465 GNUNET_free(buf);
452 } 466 GNUNET_free(path);
453 sprintf (buf, "%s/%s", pos, binary);
454 if (GNUNET_YES == GNUNET_DISK_file_test (buf))
455 {
456 pos = GNUNET_strdup (pos);
457 GNUNET_free (buf);
458 GNUNET_free (path);
459 return pos;
460 }
461 GNUNET_free (buf);
462 GNUNET_free (path);
463 return NULL; 467 return NULL;
464} 468}
465 469
@@ -471,16 +475,16 @@ get_path_from_PATH (const char *binary)
471 * @return NULL on error (environment variable not set) 475 * @return NULL on error (environment variable not set)
472 */ 476 */
473static char * 477static char *
474get_path_from_GNUNET_PREFIX () 478get_path_from_GNUNET_PREFIX()
475{ 479{
476 const char *p; 480 const char *p;
477 481
478 if ((NULL != current_pd->env_varname) && 482 if ((NULL != current_pd->env_varname) &&
479 (NULL != (p = getenv (current_pd->env_varname)))) 483 (NULL != (p = getenv(current_pd->env_varname))))
480 return GNUNET_strdup (p); 484 return GNUNET_strdup(p);
481 if ((NULL != current_pd->env_varname_alt) && 485 if ((NULL != current_pd->env_varname_alt) &&
482 (NULL != (p = getenv (current_pd->env_varname_alt)))) 486 (NULL != (p = getenv(current_pd->env_varname_alt))))
483 return GNUNET_strdup (p); 487 return GNUNET_strdup(p);
484 return NULL; 488 return NULL;
485} 489}
486 490
@@ -492,41 +496,41 @@ get_path_from_GNUNET_PREFIX ()
492 * @return a pointer to the executable path, or NULL on error 496 * @return a pointer to the executable path, or NULL on error
493 */ 497 */
494static char * 498static char *
495os_get_gnunet_path () 499os_get_gnunet_path()
496{ 500{
497 char *ret; 501 char *ret;
498 502
499 if (NULL != (ret = get_path_from_GNUNET_PREFIX ())) 503 if (NULL != (ret = get_path_from_GNUNET_PREFIX()))
500 return ret; 504 return ret;
501#if LINUX 505#if LINUX
502 if (NULL != (ret = get_path_from_proc_maps ())) 506 if (NULL != (ret = get_path_from_proc_maps()))
503 return ret; 507 return ret;
504 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */ 508 /* try path *first*, before /proc/exe, as /proc/exe can be wrong */
505 if ((NULL != current_pd->binary_name) && 509 if ((NULL != current_pd->binary_name) &&
506 (NULL != (ret = get_path_from_PATH (current_pd->binary_name)))) 510 (NULL != (ret = get_path_from_PATH(current_pd->binary_name))))
507 return ret; 511 return ret;
508 if (NULL != (ret = get_path_from_proc_exe ())) 512 if (NULL != (ret = get_path_from_proc_exe()))
509 return ret; 513 return ret;
510#endif 514#endif
511#if WINDOWS 515#if WINDOWS
512 if (NULL != (ret = get_path_from_module_filename ())) 516 if (NULL != (ret = get_path_from_module_filename()))
513 return ret; 517 return ret;
514#endif 518#endif
515#if DARWIN 519#if DARWIN
516 if (NULL != (ret = get_path_from_dyld_image ())) 520 if (NULL != (ret = get_path_from_dyld_image()))
517 return ret; 521 return ret;
518 if (NULL != (ret = get_path_from_NSGetExecutablePath ())) 522 if (NULL != (ret = get_path_from_NSGetExecutablePath()))
519 return ret; 523 return ret;
520#endif 524#endif
521 if ((NULL != current_pd->binary_name) && 525 if ((NULL != current_pd->binary_name) &&
522 (NULL != (ret = get_path_from_PATH (current_pd->binary_name)))) 526 (NULL != (ret = get_path_from_PATH(current_pd->binary_name))))
523 return ret; 527 return ret;
524 /* other attempts here */ 528 /* other attempts here */
525 LOG (GNUNET_ERROR_TYPE_ERROR, 529 LOG(GNUNET_ERROR_TYPE_ERROR,
526 _ ( 530 _(
527 "Could not determine installation path for %s. Set `%s' environment variable.\n"), 531 "Could not determine installation path for %s. Set `%s' environment variable.\n"),
528 current_pd->project_dirname, 532 current_pd->project_dirname,
529 current_pd->env_varname); 533 current_pd->env_varname);
530 return NULL; 534 return NULL;
531} 535}
532 536
@@ -536,20 +540,20 @@ os_get_gnunet_path ()
536 * @return a pointer to the executable path, or NULL on error 540 * @return a pointer to the executable path, or NULL on error
537 */ 541 */
538static char * 542static char *
539os_get_exec_path () 543os_get_exec_path()
540{ 544{
541 char *ret = NULL; 545 char *ret = NULL;
542 546
543#if LINUX 547#if LINUX
544 if (NULL != (ret = get_path_from_proc_exe ())) 548 if (NULL != (ret = get_path_from_proc_exe()))
545 return ret; 549 return ret;
546#endif 550#endif
547#if WINDOWS 551#if WINDOWS
548 if (NULL != (ret = get_path_from_module_filename ())) 552 if (NULL != (ret = get_path_from_module_filename()))
549 return ret; 553 return ret;
550#endif 554#endif
551#if DARWIN 555#if DARWIN
552 if (NULL != (ret = get_path_from_NSGetExecutablePath ())) 556 if (NULL != (ret = get_path_from_NSGetExecutablePath()))
553 return ret; 557 return ret;
554#endif 558#endif
555 /* other attempts here */ 559 /* other attempts here */
@@ -563,7 +567,7 @@ os_get_exec_path ()
563 * @return a pointer to the dir path (to be freed by the caller) 567 * @return a pointer to the dir path (to be freed by the caller)
564 */ 568 */
565char * 569char *
566GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind) 570GNUNET_OS_installation_get_path(enum GNUNET_OS_InstallationPathKind dirkind)
567{ 571{
568 size_t n; 572 size_t n;
569 char *dirname; 573 char *dirname;
@@ -575,207 +579,215 @@ GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
575 579
576 /* if wanted, try to get the current app's bin/ */ 580 /* if wanted, try to get the current app's bin/ */
577 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX) 581 if (dirkind == GNUNET_OS_IPK_SELF_PREFIX)
578 execpath = os_get_exec_path (); 582 execpath = os_get_exec_path();
579 583
580 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some 584 /* try to get GNUnet's bin/ or lib/, or if previous was unsuccessful some
581 * guess for the current app */ 585 * guess for the current app */
582 if (NULL == execpath) 586 if (NULL == execpath)
583 execpath = os_get_gnunet_path (); 587 execpath = os_get_gnunet_path();
584 588
585 if (NULL == execpath) 589 if (NULL == execpath)
586 return NULL; 590 return NULL;
587 591
588 n = strlen (execpath); 592 n = strlen(execpath);
589 if (0 == n) 593 if (0 == n)
590 { 594 {
591 /* should never happen, but better safe than sorry */ 595 /* should never happen, but better safe than sorry */
592 GNUNET_free (execpath); 596 GNUNET_free(execpath);
593 return NULL; 597 return NULL;
594 } 598 }
595 /* remove filename itself */ 599 /* remove filename itself */
596 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1])) 600 while ((n > 1) && (DIR_SEPARATOR == execpath[n - 1]))
597 execpath[--n] = '\0'; 601 execpath[--n] = '\0';
598 602
599 isbasedir = 1; 603 isbasedir = 1;
600 if ((n > 6) && ((0 == strcasecmp (&execpath[n - 6], "/lib32")) || 604 if ((n > 6) && ((0 == strcasecmp(&execpath[n - 6], "/lib32")) ||
601 (0 == strcasecmp (&execpath[n - 6], "/lib64")))) 605 (0 == strcasecmp(&execpath[n - 6], "/lib64"))))
602 { 606 {
603 if ((GNUNET_OS_IPK_LIBDIR != dirkind) && 607 if ((GNUNET_OS_IPK_LIBDIR != dirkind) &&
604 (GNUNET_OS_IPK_LIBEXECDIR != dirkind)) 608 (GNUNET_OS_IPK_LIBEXECDIR != dirkind))
609 {
610 /* strip '/lib32' or '/lib64' */
611 execpath[n - 6] = '\0';
612 n -= 6;
613 }
614 else
615 isbasedir = 0;
616 }
617 else if ((n > 4) && ((0 == strcasecmp(&execpath[n - 4], "/bin")) ||
618 (0 == strcasecmp(&execpath[n - 4], "/lib"))))
605 { 619 {
606 /* strip '/lib32' or '/lib64' */ 620 /* strip '/bin' or '/lib' */
607 execpath[n - 6] = '\0'; 621 execpath[n - 4] = '\0';
608 n -= 6; 622 n -= 4;
609 } 623 }
610 else
611 isbasedir = 0;
612 }
613 else if ((n > 4) && ((0 == strcasecmp (&execpath[n - 4], "/bin")) ||
614 (0 == strcasecmp (&execpath[n - 4], "/lib"))))
615 {
616 /* strip '/bin' or '/lib' */
617 execpath[n - 4] = '\0';
618 n -= 4;
619 }
620 multiarch = NULL; 624 multiarch = NULL;
621 if (NULL != (libdir = strstr (execpath, "/lib/"))) 625 if (NULL != (libdir = strstr(execpath, "/lib/")))
622 { 626 {
623 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/"; 627 /* test for multi-arch path of the form "PREFIX/lib/MULTIARCH/";
624 here we need to re-add 'multiarch' to lib and libexec paths later! */ 628 here we need to re-add 'multiarch' to lib and libexec paths later! */
625 multiarch = &libdir[5]; 629 multiarch = &libdir[5];
626 if (NULL == strchr (multiarch, '/')) 630 if (NULL == strchr(multiarch, '/'))
627 libdir[0] = 631 libdir[0] =
628 '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */ 632 '\0'; /* Debian multiarch format, cut of from 'execpath' but preserve in multicarch */
629 else 633 else
630 multiarch = 634 multiarch =
631 NULL; /* maybe not, multiarch still has a '/', which is not OK */ 635 NULL; /* maybe not, multiarch still has a '/', which is not OK */
632 } 636 }
633 /* in case this was a directory named foo-bin, remove "foo-" */ 637 /* in case this was a directory named foo-bin, remove "foo-" */
634 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR)) 638 while ((n > 1) && (execpath[n - 1] == DIR_SEPARATOR))
635 execpath[--n] = '\0'; 639 execpath[--n] = '\0';
636 switch (dirkind) 640 switch (dirkind)
637 {
638 case GNUNET_OS_IPK_PREFIX:
639 case GNUNET_OS_IPK_SELF_PREFIX:
640 dirname = GNUNET_strdup (DIR_SEPARATOR_STR);
641 break;
642 case GNUNET_OS_IPK_BINDIR:
643 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
644 break;
645 case GNUNET_OS_IPK_LIBDIR:
646 if (isbasedir)
647 {
648 GNUNET_asprintf (&tmp,
649 "%s%s%s%s%s%s%s",
650 execpath,
651 DIR_SEPARATOR_STR "lib",
652 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
653 (NULL != multiarch) ? multiarch : "",
654 DIR_SEPARATOR_STR,
655 current_pd->project_dirname,
656 DIR_SEPARATOR_STR);
657 if (GNUNET_YES == GNUNET_DISK_directory_test (tmp, GNUNET_YES))
658 {
659 GNUNET_free (execpath);
660 return tmp;
661 }
662 GNUNET_free (tmp);
663 tmp = NULL;
664 dirname = NULL;
665 if (4 == sizeof (void *))
666 {
667 GNUNET_asprintf (&dirname,
668 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR
669 "%s" DIR_SEPARATOR_STR,
670 current_pd->project_dirname);
671 GNUNET_asprintf (&tmp, "%s%s", execpath, dirname);
672 }
673 if (8 == sizeof (void *))
674 {
675 GNUNET_asprintf (&dirname,
676 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR
677 "%s" DIR_SEPARATOR_STR,
678 current_pd->project_dirname);
679 GNUNET_asprintf (&tmp, "%s%s", execpath, dirname);
680 }
681
682 if ((NULL != tmp) &&
683 (GNUNET_YES == GNUNET_DISK_directory_test (tmp, GNUNET_YES)))
684 {
685 GNUNET_free (execpath);
686 GNUNET_free_non_null (dirname);
687 return tmp;
688 }
689 GNUNET_free (tmp);
690 GNUNET_free_non_null (dirname);
691 }
692 GNUNET_asprintf (&dirname,
693 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
694 current_pd->project_dirname);
695 break;
696 case GNUNET_OS_IPK_DATADIR:
697 GNUNET_asprintf (&dirname,
698 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
699 "%s" DIR_SEPARATOR_STR,
700 current_pd->project_dirname);
701 break;
702 case GNUNET_OS_IPK_LOCALEDIR:
703 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
704 "locale" DIR_SEPARATOR_STR);
705 break;
706 case GNUNET_OS_IPK_ICONDIR:
707 dirname = GNUNET_strdup (DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
708 "icons" DIR_SEPARATOR_STR);
709 break;
710 case GNUNET_OS_IPK_DOCDIR:
711 GNUNET_asprintf (&dirname,
712 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
713 "doc" DIR_SEPARATOR_STR
714 "%s" DIR_SEPARATOR_STR,
715 current_pd->project_dirname);
716 break;
717 case GNUNET_OS_IPK_LIBEXECDIR:
718 if (isbasedir)
719 { 641 {
720 GNUNET_asprintf (&dirname, 642 case GNUNET_OS_IPK_PREFIX:
721 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR 643 case GNUNET_OS_IPK_SELF_PREFIX:
722 "libexec" DIR_SEPARATOR_STR, 644 dirname = GNUNET_strdup(DIR_SEPARATOR_STR);
723 current_pd->project_dirname); 645 break;
724 GNUNET_asprintf (&tmp, 646
725 "%s%s%s%s", 647 case GNUNET_OS_IPK_BINDIR:
726 execpath, 648 dirname = GNUNET_strdup(DIR_SEPARATOR_STR "bin" DIR_SEPARATOR_STR);
727 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR, 649 break;
728 (NULL != multiarch) ? multiarch : "", 650
729 dirname); 651 case GNUNET_OS_IPK_LIBDIR:
730 if (GNUNET_YES == GNUNET_DISK_directory_test (tmp, GNUNET_YES)) 652 if (isbasedir)
731 { 653 {
732 GNUNET_free (execpath); 654 GNUNET_asprintf(&tmp,
733 GNUNET_free (dirname); 655 "%s%s%s%s%s%s%s",
734 return tmp; 656 execpath,
735 } 657 DIR_SEPARATOR_STR "lib",
736 GNUNET_free (tmp); 658 (NULL != multiarch) ? DIR_SEPARATOR_STR : "",
737 tmp = NULL; 659 (NULL != multiarch) ? multiarch : "",
738 dirname = NULL; 660 DIR_SEPARATOR_STR,
739 if (4 == sizeof (void *)) 661 current_pd->project_dirname,
740 { 662 DIR_SEPARATOR_STR);
741 GNUNET_asprintf (&dirname, 663 if (GNUNET_YES == GNUNET_DISK_directory_test(tmp, GNUNET_YES))
742 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR 664 {
743 "%s" DIR_SEPARATOR_STR 665 GNUNET_free(execpath);
744 "libexec" DIR_SEPARATOR_STR, 666 return tmp;
745 current_pd->project_dirname); 667 }
746 GNUNET_asprintf (&tmp, "%s%s", execpath, dirname); 668 GNUNET_free(tmp);
747 } 669 tmp = NULL;
748 if (8 == sizeof (void *)) 670 dirname = NULL;
749 { 671 if (4 == sizeof(void *))
750 GNUNET_asprintf (&dirname, 672 {
751 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR 673 GNUNET_asprintf(&dirname,
752 "%s" DIR_SEPARATOR_STR 674 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR
753 "libexec" DIR_SEPARATOR_STR, 675 "%s" DIR_SEPARATOR_STR,
754 current_pd->project_dirname); 676 current_pd->project_dirname);
755 GNUNET_asprintf (&tmp, "%s%s", execpath, dirname); 677 GNUNET_asprintf(&tmp, "%s%s", execpath, dirname);
756 } 678 }
757 if ((NULL != tmp) && 679 if (8 == sizeof(void *))
758 (GNUNET_YES == GNUNET_DISK_directory_test (tmp, GNUNET_YES))) 680 {
759 { 681 GNUNET_asprintf(&dirname,
760 GNUNET_free (execpath); 682 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR
761 GNUNET_free_non_null (dirname); 683 "%s" DIR_SEPARATOR_STR,
762 return tmp; 684 current_pd->project_dirname);
763 } 685 GNUNET_asprintf(&tmp, "%s%s", execpath, dirname);
764 GNUNET_free (tmp); 686 }
765 GNUNET_free_non_null (dirname); 687
688 if ((NULL != tmp) &&
689 (GNUNET_YES == GNUNET_DISK_directory_test(tmp, GNUNET_YES)))
690 {
691 GNUNET_free(execpath);
692 GNUNET_free_non_null(dirname);
693 return tmp;
694 }
695 GNUNET_free(tmp);
696 GNUNET_free_non_null(dirname);
697 }
698 GNUNET_asprintf(&dirname,
699 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR,
700 current_pd->project_dirname);
701 break;
702
703 case GNUNET_OS_IPK_DATADIR:
704 GNUNET_asprintf(&dirname,
705 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
706 "%s" DIR_SEPARATOR_STR,
707 current_pd->project_dirname);
708 break;
709
710 case GNUNET_OS_IPK_LOCALEDIR:
711 dirname = GNUNET_strdup(DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
712 "locale" DIR_SEPARATOR_STR);
713 break;
714
715 case GNUNET_OS_IPK_ICONDIR:
716 dirname = GNUNET_strdup(DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
717 "icons" DIR_SEPARATOR_STR);
718 break;
719
720 case GNUNET_OS_IPK_DOCDIR:
721 GNUNET_asprintf(&dirname,
722 DIR_SEPARATOR_STR "share" DIR_SEPARATOR_STR
723 "doc" DIR_SEPARATOR_STR
724 "%s" DIR_SEPARATOR_STR,
725 current_pd->project_dirname);
726 break;
727
728 case GNUNET_OS_IPK_LIBEXECDIR:
729 if (isbasedir)
730 {
731 GNUNET_asprintf(&dirname,
732 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR
733 "libexec" DIR_SEPARATOR_STR,
734 current_pd->project_dirname);
735 GNUNET_asprintf(&tmp,
736 "%s%s%s%s",
737 execpath,
738 DIR_SEPARATOR_STR "lib" DIR_SEPARATOR_STR,
739 (NULL != multiarch) ? multiarch : "",
740 dirname);
741 if (GNUNET_YES == GNUNET_DISK_directory_test(tmp, GNUNET_YES))
742 {
743 GNUNET_free(execpath);
744 GNUNET_free(dirname);
745 return tmp;
746 }
747 GNUNET_free(tmp);
748 tmp = NULL;
749 dirname = NULL;
750 if (4 == sizeof(void *))
751 {
752 GNUNET_asprintf(&dirname,
753 DIR_SEPARATOR_STR "lib32" DIR_SEPARATOR_STR
754 "%s" DIR_SEPARATOR_STR
755 "libexec" DIR_SEPARATOR_STR,
756 current_pd->project_dirname);
757 GNUNET_asprintf(&tmp, "%s%s", execpath, dirname);
758 }
759 if (8 == sizeof(void *))
760 {
761 GNUNET_asprintf(&dirname,
762 DIR_SEPARATOR_STR "lib64" DIR_SEPARATOR_STR
763 "%s" DIR_SEPARATOR_STR
764 "libexec" DIR_SEPARATOR_STR,
765 current_pd->project_dirname);
766 GNUNET_asprintf(&tmp, "%s%s", execpath, dirname);
767 }
768 if ((NULL != tmp) &&
769 (GNUNET_YES == GNUNET_DISK_directory_test(tmp, GNUNET_YES)))
770 {
771 GNUNET_free(execpath);
772 GNUNET_free_non_null(dirname);
773 return tmp;
774 }
775 GNUNET_free(tmp);
776 GNUNET_free_non_null(dirname);
777 }
778 GNUNET_asprintf(&dirname,
779 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR
780 "libexec" DIR_SEPARATOR_STR,
781 current_pd->project_dirname);
782 break;
783
784 default:
785 GNUNET_free(execpath);
786 return NULL;
766 } 787 }
767 GNUNET_asprintf (&dirname, 788 GNUNET_asprintf(&tmp, "%s%s", execpath, dirname);
768 DIR_SEPARATOR_STR "%s" DIR_SEPARATOR_STR 789 GNUNET_free(dirname);
769 "libexec" DIR_SEPARATOR_STR, 790 GNUNET_free(execpath);
770 current_pd->project_dirname);
771 break;
772 default:
773 GNUNET_free (execpath);
774 return NULL;
775 }
776 GNUNET_asprintf (&tmp, "%s%s", execpath, dirname);
777 GNUNET_free (dirname);
778 GNUNET_free (execpath);
779 return tmp; 791 return tmp;
780} 792}
781 793
@@ -789,7 +801,7 @@ GNUNET_OS_installation_get_path (enum GNUNET_OS_InstallationPathKind dirkind)
789 * @return full path to the binary, if possible, otherwise copy of 'progname' 801 * @return full path to the binary, if possible, otherwise copy of 'progname'
790 */ 802 */
791char * 803char *
792GNUNET_OS_get_libexec_binary_path (const char *progname) 804GNUNET_OS_get_libexec_binary_path(const char *progname)
793{ 805{
794 static char *cache; 806 static char *cache;
795 char *libexecdir; 807 char *libexecdir;
@@ -797,15 +809,15 @@ GNUNET_OS_get_libexec_binary_path (const char *progname)
797 809
798 if ((DIR_SEPARATOR == progname[0]) || 810 if ((DIR_SEPARATOR == progname[0]) ||
799 (GNUNET_YES == 811 (GNUNET_YES ==
800 GNUNET_STRINGS_path_is_absolute (progname, GNUNET_NO, NULL, NULL))) 812 GNUNET_STRINGS_path_is_absolute(progname, GNUNET_NO, NULL, NULL)))
801 return GNUNET_strdup (progname); 813 return GNUNET_strdup(progname);
802 if (NULL != cache) 814 if (NULL != cache)
803 libexecdir = cache; 815 libexecdir = cache;
804 else 816 else
805 libexecdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBEXECDIR); 817 libexecdir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LIBEXECDIR);
806 if (NULL == libexecdir) 818 if (NULL == libexecdir)
807 return GNUNET_strdup (progname); 819 return GNUNET_strdup(progname);
808 GNUNET_asprintf (&binary, "%s%s", libexecdir, progname); 820 GNUNET_asprintf(&binary, "%s%s", libexecdir, progname);
809 cache = libexecdir; 821 cache = libexecdir;
810 return binary; 822 return binary;
811} 823}
@@ -824,8 +836,8 @@ GNUNET_OS_get_libexec_binary_path (const char *progname)
824 * otherwise 836 * otherwise
825 */ 837 */
826char * 838char *
827GNUNET_OS_get_suid_binary_path (const struct GNUNET_CONFIGURATION_Handle *cfg, 839GNUNET_OS_get_suid_binary_path(const struct GNUNET_CONFIGURATION_Handle *cfg,
828 const char *progname) 840 const char *progname)
829{ 841{
830 static char *cache; 842 static char *cache;
831 char *binary = NULL; 843 char *binary = NULL;
@@ -833,26 +845,26 @@ GNUNET_OS_get_suid_binary_path (const struct GNUNET_CONFIGURATION_Handle *cfg,
833 size_t path_len; 845 size_t path_len;
834 846
835 if (GNUNET_YES == 847 if (GNUNET_YES ==
836 GNUNET_STRINGS_path_is_absolute (progname, GNUNET_NO, NULL, NULL)) 848 GNUNET_STRINGS_path_is_absolute(progname, GNUNET_NO, NULL, NULL))
837 { 849 {
838 return GNUNET_strdup (progname); 850 return GNUNET_strdup(progname);
839 } 851 }
840 if (NULL != cache) 852 if (NULL != cache)
841 path = cache; 853 path = cache;
842 else 854 else
843 GNUNET_CONFIGURATION_get_value_string (cfg, 855 GNUNET_CONFIGURATION_get_value_string(cfg,
844 "PATHS", 856 "PATHS",
845 "SUID_BINARY_PATH", 857 "SUID_BINARY_PATH",
846 &path); 858 &path);
847 if ((NULL == path) || (0 == strlen (path))) 859 if ((NULL == path) || (0 == strlen(path)))
848 return GNUNET_OS_get_libexec_binary_path (progname); 860 return GNUNET_OS_get_libexec_binary_path(progname);
849 path_len = strlen (path); 861 path_len = strlen(path);
850 GNUNET_asprintf (&binary, 862 GNUNET_asprintf(&binary,
851 "%s%s%s", 863 "%s%s%s",
852 path, 864 path,
853 (path[path_len - 1] == DIR_SEPARATOR) ? "" 865 (path[path_len - 1] == DIR_SEPARATOR) ? ""
854 : DIR_SEPARATOR_STR, 866 : DIR_SEPARATOR_STR,
855 progname); 867 progname);
856 cache = path; 868 cache = path;
857 return binary; 869 return binary;
858} 870}
@@ -875,143 +887,144 @@ GNUNET_OS_get_suid_binary_path (const struct GNUNET_CONFIGURATION_Handle *cfg,
875 * #GNUNET_SYSERR on error (no such binary or not executable) 887 * #GNUNET_SYSERR on error (no such binary or not executable)
876 */ 888 */
877int 889int
878GNUNET_OS_check_helper_binary (const char *binary, 890GNUNET_OS_check_helper_binary(const char *binary,
879 int check_suid, 891 int check_suid,
880 const char *params) 892 const char *params)
881{ 893{
882 struct stat statbuf; 894 struct stat statbuf;
883 char *p; 895 char *p;
884 char *pf; 896 char *pf;
897
885#ifdef MINGW 898#ifdef MINGW
886 char *binaryexe; 899 char *binaryexe;
887 900
888 GNUNET_asprintf (&binaryexe, "%s.exe", binary); 901 GNUNET_asprintf(&binaryexe, "%s.exe", binary);
889 if ((GNUNET_YES == 902 if ((GNUNET_YES ==
890 GNUNET_STRINGS_path_is_absolute (binaryexe, GNUNET_NO, NULL, NULL)) || 903 GNUNET_STRINGS_path_is_absolute(binaryexe, GNUNET_NO, NULL, NULL)) ||
891 (0 == strncmp (binary, "./", 2))) 904 (0 == strncmp(binary, "./", 2)))
892 p = GNUNET_strdup (binaryexe); 905 p = GNUNET_strdup(binaryexe);
893 else 906 else
894 {
895 p = get_path_from_PATH (binaryexe);
896 if (NULL != p)
897 { 907 {
898 GNUNET_asprintf (&pf, "%s/%s", p, binaryexe); 908 p = get_path_from_PATH(binaryexe);
899 GNUNET_free (p); 909 if (NULL != p)
900 p = pf; 910 {
911 GNUNET_asprintf(&pf, "%s/%s", p, binaryexe);
912 GNUNET_free(p);
913 p = pf;
914 }
901 } 915 }
902 } 916 GNUNET_free(binaryexe);
903 GNUNET_free (binaryexe);
904#else 917#else
905 if ((GNUNET_YES == 918 if ((GNUNET_YES ==
906 GNUNET_STRINGS_path_is_absolute (binary, GNUNET_NO, NULL, NULL)) || 919 GNUNET_STRINGS_path_is_absolute(binary, GNUNET_NO, NULL, NULL)) ||
907 (0 == strncmp (binary, "./", 2))) 920 (0 == strncmp(binary, "./", 2)))
908 { 921 {
909 p = GNUNET_strdup (binary); 922 p = GNUNET_strdup(binary);
910 } 923 }
911 else 924 else
912 {
913 p = get_path_from_PATH (binary);
914 if (NULL != p)
915 { 925 {
916 GNUNET_asprintf (&pf, "%s/%s", p, binary); 926 p = get_path_from_PATH(binary);
917 GNUNET_free (p); 927 if (NULL != p)
918 p = pf; 928 {
929 GNUNET_asprintf(&pf, "%s/%s", p, binary);
930 GNUNET_free(p);
931 p = pf;
932 }
919 } 933 }
920 }
921#endif 934#endif
922 if (NULL == p) 935 if (NULL == p)
923 {
924 LOG (GNUNET_ERROR_TYPE_INFO,
925 _ ("Could not find binary `%s' in PATH!\n"),
926 binary);
927 return GNUNET_SYSERR;
928 }
929 if (0 != access (p, X_OK))
930 {
931 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "access", p);
932 GNUNET_free (p);
933 return GNUNET_SYSERR;
934 }
935#ifndef MINGW
936 if (0 == getuid ())
937 {
938 /* as we run as root, we don't insist on SUID */
939 GNUNET_free (p);
940 return GNUNET_YES;
941 }
942#endif
943 if (0 != stat (p, &statbuf))
944 {
945 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "stat", p);
946 GNUNET_free (p);
947 return GNUNET_SYSERR;
948 }
949 if (check_suid)
950 {
951#ifndef MINGW
952 (void) params;
953 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
954 { 936 {
955 GNUNET_free (p); 937 LOG(GNUNET_ERROR_TYPE_INFO,
956 return GNUNET_YES; 938 _("Could not find binary `%s' in PATH!\n"),
939 binary);
940 return GNUNET_SYSERR;
957 } 941 }
958 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 942 if (0 != access(p, X_OK))
959 _ ("Binary `%s' exists, but is not SUID\n"),
960 p);
961 /* binary exists, but not SUID */
962#else
963 STARTUPINFO start;
964 char parameters[512];
965 PROCESS_INFORMATION proc;
966 DWORD exit_value;
967
968 GNUNET_snprintf (parameters, sizeof (parameters), "-d %s", params);
969 memset (&start, 0, sizeof (start));
970 start.cb = sizeof (start);
971 memset (&proc, 0, sizeof (proc));
972
973
974 // Start the child process.
975 if (! (CreateProcess (
976 p, // current windows (2k3 and up can handle / instead of \ in paths))
977 parameters, // execute dryrun/priviliege checking mode
978 NULL, // Process handle not inheritable
979 NULL, // Thread handle not inheritable
980 FALSE, // Set handle inheritance to FALSE
981 CREATE_DEFAULT_ERROR_MODE, // No creation flags
982 NULL, // Use parent's environment block
983 NULL, // Use parent's starting directory
984 &start, // Pointer to STARTUPINFO structure
985 &proc) // Pointer to PROCESS_INFORMATION structure
986 ))
987 { 943 {
988 LOG (GNUNET_ERROR_TYPE_ERROR, 944 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "access", p);
989 _ ("CreateProcess failed for binary %s (%d).\n"), 945 GNUNET_free(p);
990 p,
991 GetLastError ());
992 return GNUNET_SYSERR; 946 return GNUNET_SYSERR;
993 } 947 }
994 948#ifndef MINGW
995 // Wait until child process exits. 949 if (0 == getuid())
996 WaitForSingleObject (proc.hProcess, INFINITE); 950 {
997 951 /* as we run as root, we don't insist on SUID */
998 if (! GetExitCodeProcess (proc.hProcess, &exit_value)) 952 GNUNET_free(p);
953 return GNUNET_YES;
954 }
955#endif
956 if (0 != stat(p, &statbuf))
999 { 957 {
1000 LOG (GNUNET_ERROR_TYPE_ERROR, 958 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "stat", p);
1001 _ ("GetExitCodeProcess failed for binary %s (%d).\n"), 959 GNUNET_free(p);
1002 p,
1003 GetLastError ());
1004 return GNUNET_SYSERR; 960 return GNUNET_SYSERR;
1005 } 961 }
1006 // Close process and thread handles. 962 if (check_suid)
1007 CloseHandle (proc.hProcess); 963 {
1008 CloseHandle (proc.hThread); 964#ifndef MINGW
1009 965 (void)params;
1010 if (! exit_value) 966 if ((0 != (statbuf.st_mode & S_ISUID)) && (0 == statbuf.st_uid))
1011 return GNUNET_YES; 967 {
968 GNUNET_free(p);
969 return GNUNET_YES;
970 }
971 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
972 _("Binary `%s' exists, but is not SUID\n"),
973 p);
974 /* binary exists, but not SUID */
975#else
976 STARTUPINFO start;
977 char parameters[512];
978 PROCESS_INFORMATION proc;
979 DWORD exit_value;
980
981 GNUNET_snprintf(parameters, sizeof(parameters), "-d %s", params);
982 memset(&start, 0, sizeof(start));
983 start.cb = sizeof(start);
984 memset(&proc, 0, sizeof(proc));
985
986
987 // Start the child process.
988 if (!(CreateProcess(
989 p, // current windows (2k3 and up can handle / instead of \ in paths))
990 parameters, // execute dryrun/priviliege checking mode
991 NULL, // Process handle not inheritable
992 NULL, // Thread handle not inheritable
993 FALSE, // Set handle inheritance to FALSE
994 CREATE_DEFAULT_ERROR_MODE, // No creation flags
995 NULL, // Use parent's environment block
996 NULL, // Use parent's starting directory
997 &start, // Pointer to STARTUPINFO structure
998 &proc) // Pointer to PROCESS_INFORMATION structure
999 ))
1000 {
1001 LOG(GNUNET_ERROR_TYPE_ERROR,
1002 _("CreateProcess failed for binary %s (%d).\n"),
1003 p,
1004 GetLastError());
1005 return GNUNET_SYSERR;
1006 }
1007
1008 // Wait until child process exits.
1009 WaitForSingleObject(proc.hProcess, INFINITE);
1010
1011 if (!GetExitCodeProcess(proc.hProcess, &exit_value))
1012 {
1013 LOG(GNUNET_ERROR_TYPE_ERROR,
1014 _("GetExitCodeProcess failed for binary %s (%d).\n"),
1015 p,
1016 GetLastError());
1017 return GNUNET_SYSERR;
1018 }
1019 // Close process and thread handles.
1020 CloseHandle(proc.hProcess);
1021 CloseHandle(proc.hThread);
1022
1023 if (!exit_value)
1024 return GNUNET_YES;
1012#endif 1025#endif
1013 } 1026 }
1014 GNUNET_free (p); 1027 GNUNET_free(p);
1015 return GNUNET_NO; 1028 return GNUNET_NO;
1016} 1029}
1017 1030
diff --git a/src/util/os_network.c b/src/util/os_network.c
index 9008c5c5a..6bf9d1846 100644
--- a/src/util/os_network.c
+++ b/src/util/os_network.c
@@ -17,7 +17,7 @@
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/os_network.c 22 * @file util/os_network.c
23 * @brief function to determine available network interfaces 23 * @brief function to determine available network interfaces
@@ -31,11 +31,11 @@
31#include "gnunet_util_lib.h" 31#include "gnunet_util_lib.h"
32 32
33 33
34#define LOG(kind,...) GNUNET_log_from (kind, "util-os-network", __VA_ARGS__) 34#define LOG(kind, ...) GNUNET_log_from(kind, "util-os-network", __VA_ARGS__)
35#define LOG_STRERROR_FILE(kind,syscall,filename) GNUNET_log_from_strerror_file (kind, "util-os-network", syscall, filename) 35#define LOG_STRERROR_FILE(kind, syscall, filename) GNUNET_log_from_strerror_file(kind, "util-os-network", syscall, filename)
36 36
37 37
38#if ! (HAVE_GETIFADDRS && HAVE_FREEIFADDRS) && !MINGW 38#if !(HAVE_GETIFADDRS && HAVE_FREEIFADDRS) && !MINGW
39/** 39/**
40 * Try to enumerate all network interfaces using 'ifconfig'. 40 * Try to enumerate all network interfaces using 'ifconfig'.
41 * 41 *
@@ -44,8 +44,8 @@
44 * @return #GNUNET_OK if it worked 44 * @return #GNUNET_OK if it worked
45 */ 45 */
46static int 46static int
47try_ifconfig (GNUNET_OS_NetworkInterfaceProcessor proc, 47try_ifconfig(GNUNET_OS_NetworkInterfaceProcessor proc,
48 void *proc_cls) 48 void *proc_cls)
49{ 49{
50 int i; 50 int i;
51 char line[1024]; 51 char line[1024];
@@ -70,159 +70,159 @@ try_ifconfig (GNUNET_OS_NetworkInterfaceProcessor proc,
70 static char *pcall; 70 static char *pcall;
71 71
72 if (NULL == pcall) 72 if (NULL == pcall)
73 { 73 {
74 const char *sbin_ifconfig; 74 const char *sbin_ifconfig;
75 75
76#ifdef IFCONFIG 76#ifdef IFCONFIG
77 if (0 == access (IFCONFIG, X_OK)) 77 if (0 == access(IFCONFIG, X_OK))
78 sbin_ifconfig = IFCONFIG; 78 sbin_ifconfig = IFCONFIG;
79 else 79 else
80#endif 80#endif
81 if (0 == access ("/sbin/ifconfig", X_OK)) 81 if (0 == access("/sbin/ifconfig", X_OK))
82 sbin_ifconfig = "/sbin/ifconfig"; 82 sbin_ifconfig = "/sbin/ifconfig";
83 else if (0 == access ("/usr/sbin/ifconfig", X_OK)) 83 else if (0 == access("/usr/sbin/ifconfig", X_OK))
84 sbin_ifconfig = "/usr/sbin/ifconfig"; 84 sbin_ifconfig = "/usr/sbin/ifconfig";
85 else 85 else
86 sbin_ifconfig = "ifconfig"; 86 sbin_ifconfig = "ifconfig";
87 GNUNET_asprintf (&pcall, 87 GNUNET_asprintf(&pcall,
88 "%s -a 2> /dev/null", 88 "%s -a 2> /dev/null",
89 sbin_ifconfig); 89 sbin_ifconfig);
90 } 90 }
91 f = popen (pcall, "r"); 91 f = popen(pcall, "r");
92 if (NULL == f) 92 if (NULL == f)
93 { 93 {
94 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, 94 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
95 "popen", 95 "popen",
96 "ifconfig"); 96 "ifconfig");
97 97
98 return GNUNET_SYSERR; 98 return GNUNET_SYSERR;
99 } 99 }
100 100
101 have_ifc = GNUNET_NO; 101 have_ifc = GNUNET_NO;
102 ifc[11] = '\0'; 102 ifc[11] = '\0';
103 while (NULL != fgets (line, sizeof (line), f)) 103 while (NULL != fgets(line, sizeof(line), f))
104 {
105 if (strlen (line) == 0)
106 { 104 {
107 have_ifc = GNUNET_NO; 105 if (strlen(line) == 0)
108 continue; 106 {
109 } 107 have_ifc = GNUNET_NO;
110 if (!isspace (line[0])) 108 continue;
111 { 109 }
112 have_ifc = (1 == SSCANF (line, "%11s", ifc)) ? GNUNET_YES : GNUNET_NO; 110 if (!isspace(line[0]))
113 /* would end with ':' on OSX, fix it! */ 111 {
114 if (ifc[strlen (ifc) - 1] == ':') 112 have_ifc = (1 == SSCANF(line, "%11s", ifc)) ? GNUNET_YES : GNUNET_NO;
115 ifc[strlen (ifc) - 1] = '\0'; 113 /* would end with ':' on OSX, fix it! */
116 continue; 114 if (ifc[strlen(ifc) - 1] == ':')
117 } 115 ifc[strlen(ifc) - 1] = '\0';
118 if (!have_ifc) 116 continue;
119 continue; /* strange input, hope for the best */ 117 }
118 if (!have_ifc)
119 continue; /* strange input, hope for the best */
120 120
121 /* make parsing of ipv6 addresses easier */ 121 /* make parsing of ipv6 addresses easier */
122 for (replace = line; *replace != '\0'; replace++) 122 for (replace = line; *replace != '\0'; replace++)
123 { 123 {
124 if (*replace == '/') 124 if (*replace == '/')
125 *replace = ' '; 125 *replace = ' ';
126 } 126 }
127 prefixlen = -1; 127 prefixlen = -1;
128 128
129 start = line; 129 start = line;
130 while (('\0' != *start) && (isspace (*start))) 130 while (('\0' != *start) && (isspace(*start)))
131 start++; 131 start++;
132 132
133 /* Zero-out stack allocated values */ 133 /* Zero-out stack allocated values */
134 memset (addrstr, 0, 128); 134 memset(addrstr, 0, 128);
135 memset (netmaskstr, 0, 128); 135 memset(netmaskstr, 0, 128);
136 memset (bcstr, 0, 128); 136 memset(bcstr, 0, 128);
137 prefixlen = 0; 137 prefixlen = 0;
138 138
139 if ( /* Linux */ 139 if ( /* Linux */
140 (3 == SSCANF (start, "inet addr:%127s Bcast:%127s Mask:%127s", addrstr, bcstr, netmaskstr)) || 140 (3 == SSCANF(start, "inet addr:%127s Bcast:%127s Mask:%127s", addrstr, bcstr, netmaskstr)) ||
141 (2 == SSCANF (start, "inet addr:%127s Mask:%127s", addrstr, netmaskstr)) || 141 (2 == SSCANF(start, "inet addr:%127s Mask:%127s", addrstr, netmaskstr)) ||
142 (2 == SSCANF (start, "inet6 addr:%127s %d", addrstr, &prefixlen)) || 142 (2 == SSCANF(start, "inet6 addr:%127s %d", addrstr, &prefixlen)) ||
143 /* Solaris, OS X */ 143 /* Solaris, OS X */
144 (1 == SSCANF (start, "inet %127s", addrstr)) || 144 (1 == SSCANF(start, "inet %127s", addrstr)) ||
145 (1 == SSCANF (start, "inet6 %127s", addrstr))) 145 (1 == SSCANF(start, "inet6 %127s", addrstr)))
146 { 146 {
147 /* IPv4 */ 147 /* IPv4 */
148 if (1 == inet_pton (AF_INET, addrstr, &v4)) 148 if (1 == inet_pton(AF_INET, addrstr, &v4))
149 { 149 {
150 memset (&a4, 0, sizeof (a4)); 150 memset(&a4, 0, sizeof(a4));
151 a4.sin_family = AF_INET; 151 a4.sin_family = AF_INET;
152#if HAVE_SOCKADDR_IN_SIN_LEN 152#if HAVE_SOCKADDR_IN_SIN_LEN
153 a4.sin_len = (u_char) sizeof (struct sockaddr_in); 153 a4.sin_len = (u_char)sizeof(struct sockaddr_in);
154#endif 154#endif
155 a4.sin_addr = v4; 155 a4.sin_addr = v4;
156 156
157 pass_bcaddr = NULL; 157 pass_bcaddr = NULL;
158 pass_netmask = NULL; 158 pass_netmask = NULL;
159 if (1 == inet_pton (AF_INET, bcstr, &v4)) 159 if (1 == inet_pton(AF_INET, bcstr, &v4))
160 { 160 {
161 memset (&bcaddr, 0, sizeof (bcaddr)); 161 memset(&bcaddr, 0, sizeof(bcaddr));
162 bcaddr.sin_family = AF_INET; 162 bcaddr.sin_family = AF_INET;
163#if HAVE_SOCKADDR_IN_SIN_LEN 163#if HAVE_SOCKADDR_IN_SIN_LEN
164 bcaddr.sin_len = (u_char) sizeof (struct sockaddr_in); 164 bcaddr.sin_len = (u_char)sizeof(struct sockaddr_in);
165#endif 165#endif
166 bcaddr.sin_addr = v4; 166 bcaddr.sin_addr = v4;
167 pass_bcaddr = (struct sockaddr *) &bcaddr; 167 pass_bcaddr = (struct sockaddr *)&bcaddr;
168 } 168 }
169 if (1 == inet_pton (AF_INET, netmaskstr, &v4)) 169 if (1 == inet_pton(AF_INET, netmaskstr, &v4))
170 { 170 {
171 memset (&netmask, 0, sizeof (netmask)); 171 memset(&netmask, 0, sizeof(netmask));
172 netmask.sin_family = AF_INET; 172 netmask.sin_family = AF_INET;
173#if HAVE_SOCKADDR_IN_SIN_LEN 173#if HAVE_SOCKADDR_IN_SIN_LEN
174 netmask.sin_len = (u_char) sizeof (struct sockaddr_in); 174 netmask.sin_len = (u_char)sizeof(struct sockaddr_in);
175#endif 175#endif
176 netmask.sin_addr = v4; 176 netmask.sin_addr = v4;
177 pass_netmask = (struct sockaddr *) &netmask; 177 pass_netmask = (struct sockaddr *)&netmask;
178 } 178 }
179 179
180 180
181 if (GNUNET_OK != 181 if (GNUNET_OK !=
182 proc (proc_cls, ifc, 0 == strcmp (ifc, GNUNET_DEFAULT_INTERFACE), 182 proc(proc_cls, ifc, 0 == strcmp(ifc, GNUNET_DEFAULT_INTERFACE),
183 (const struct sockaddr *) &a4, 183 (const struct sockaddr *)&a4,
184 pass_bcaddr, pass_netmask, sizeof (a4))) 184 pass_bcaddr, pass_netmask, sizeof(a4)))
185 break; 185 break;
186 continue; 186 continue;
187 } 187 }
188 /* IPv6 */ 188 /* IPv6 */
189 if (1 == inet_pton (AF_INET6, addrstr, &v6)) 189 if (1 == inet_pton(AF_INET6, addrstr, &v6))
190 { 190 {
191 memset (&a6, 0, sizeof (a6)); 191 memset(&a6, 0, sizeof(a6));
192 a6.sin6_family = AF_INET6; 192 a6.sin6_family = AF_INET6;
193#if HAVE_SOCKADDR_IN_SIN_LEN 193#if HAVE_SOCKADDR_IN_SIN_LEN
194 a6.sin6_len = (u_char) sizeof (struct sockaddr_in6); 194 a6.sin6_len = (u_char)sizeof(struct sockaddr_in6);
195#endif 195#endif
196 a6.sin6_addr = v6; 196 a6.sin6_addr = v6;
197 197
198 pass_netmask = NULL; 198 pass_netmask = NULL;
199 if (prefixlen != -1) 199 if (prefixlen != -1)
200 { 200 {
201 memset (v6.s6_addr, 0, sizeof (v6.s6_addr)); 201 memset(v6.s6_addr, 0, sizeof(v6.s6_addr));
202 for (i = 0; i < prefixlen; i++) 202 for (i = 0; i < prefixlen; i++)
203 { 203 {
204 v6.s6_addr[i >> 3] |= 1 << (i & 7); 204 v6.s6_addr[i >> 3] |= 1 << (i & 7);
205 } 205 }
206 memset (&netmask6, 0, sizeof (netmask6)); 206 memset(&netmask6, 0, sizeof(netmask6));
207 netmask6.sin6_family = AF_INET6; 207 netmask6.sin6_family = AF_INET6;
208#if HAVE_SOCKADDR_IN_SIN_LEN 208#if HAVE_SOCKADDR_IN_SIN_LEN
209 netmask6.sin6_len = (u_char) sizeof (struct sockaddr_in6); 209 netmask6.sin6_len = (u_char)sizeof(struct sockaddr_in6);
210#endif 210#endif
211 netmask6.sin6_addr = v6; 211 netmask6.sin6_addr = v6;
212 212
213 pass_netmask = (struct sockaddr *) &netmask6; 213 pass_netmask = (struct sockaddr *)&netmask6;
214 }
215
216 if (GNUNET_OK !=
217 proc(proc_cls, ifc, 0 == strcmp(ifc, GNUNET_DEFAULT_INTERFACE),
218 (const struct sockaddr *)&a6,
219 NULL, pass_netmask, sizeof(a6)))
220 break;
221 continue;
222 }
214 } 223 }
215
216 if (GNUNET_OK !=
217 proc (proc_cls, ifc, 0 == strcmp (ifc, GNUNET_DEFAULT_INTERFACE),
218 (const struct sockaddr *) &a6,
219 NULL, pass_netmask, sizeof (a6)))
220 break;
221 continue;
222 }
223 } 224 }
224 } 225 pclose(f);
225 pclose (f);
226 return GNUNET_OK; 226 return GNUNET_OK;
227} 227}
228 228
@@ -235,8 +235,8 @@ try_ifconfig (GNUNET_OS_NetworkInterfaceProcessor proc,
235 * @return #GNUNET_OK if it worked 235 * @return #GNUNET_OK if it worked
236 */ 236 */
237static int 237static int
238try_ip (GNUNET_OS_NetworkInterfaceProcessor proc, 238try_ip(GNUNET_OS_NetworkInterfaceProcessor proc,
239 void *proc_cls) 239 void *proc_cls)
240{ 240{
241 char line[1024]; 241 char line[1024];
242 char *replace; 242 char *replace;
@@ -255,124 +255,124 @@ try_ip (GNUNET_OS_NetworkInterfaceProcessor proc,
255 static char *pcall; 255 static char *pcall;
256 256
257 if (NULL == pcall) 257 if (NULL == pcall)
258 { 258 {
259 const char *sbin_ip; 259 const char *sbin_ip;
260 260
261#ifdef IFCONFIG 261#ifdef IFCONFIG
262 if (0 == access (PATH_TO_IP, X_OK)) 262 if (0 == access(PATH_TO_IP, X_OK))
263 sbin_ip = PATH_TO_IP; 263 sbin_ip = PATH_TO_IP;
264 else 264 else
265#endif 265#endif
266 if (0 == access ("/sbin/ip", X_OK)) 266 if (0 == access("/sbin/ip", X_OK))
267 sbin_ip = "/sbin/ip"; 267 sbin_ip = "/sbin/ip";
268 else if (0 == access ("/usr/sbin/ip", X_OK)) 268 else if (0 == access("/usr/sbin/ip", X_OK))
269 sbin_ip = "/usr/sbin/ip"; 269 sbin_ip = "/usr/sbin/ip";
270 else 270 else
271 sbin_ip = "if"; 271 sbin_ip = "if";
272 GNUNET_asprintf (&pcall, 272 GNUNET_asprintf(&pcall,
273 "%s -o add 2> /dev/null", 273 "%s -o add 2> /dev/null",
274 sbin_ip); 274 sbin_ip);
275 } 275 }
276 f = popen (pcall, "r"); 276 f = popen(pcall, "r");
277 if (! f) 277 if (!f)
278 {
279 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
280 "popen",
281 "ip");
282 return GNUNET_SYSERR;
283 }
284
285 while (NULL != fgets (line, sizeof (line), f))
286 {
287 /* make parsing easier */
288 for (replace = line; *replace != '\0'; replace++)
289 { 278 {
290 if (*replace == '/') 279 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
291 *replace = ' '; 280 "popen",
281 "ip");
282 return GNUNET_SYSERR;
292 } 283 }
293 /* Zero-out stack allocated values */ 284
294 memset (ifname, 0, 64); 285 while (NULL != fgets(line, sizeof(line), f))
295 memset (afstr, 0, 6); 286 {
296 memset (addrstr, 0, 128); 287 /* make parsing easier */
297 if (4 != SSCANF (line, 288 for (replace = line; *replace != '\0'; replace++)
298 "%*u: %63s %5s %127s %6u", 289 {
299 ifname, 290 if (*replace == '/')
300 afstr, 291 *replace = ' ';
301 addrstr, 292 }
302 &prefixlen)) 293 /* Zero-out stack allocated values */
303 continue; 294 memset(ifname, 0, 64);
304 /* IPv4 */ 295 memset(afstr, 0, 6);
305 if ( (0 == strcasecmp ("inet", 296 memset(addrstr, 0, 128);
297 if (4 != SSCANF(line,
298 "%*u: %63s %5s %127s %6u",
299 ifname,
300 afstr,
301 addrstr,
302 &prefixlen))
303 continue;
304 /* IPv4 */
305 if ((0 == strcasecmp("inet",
306 afstr)) && 306 afstr)) &&
307 (1 == inet_pton (AF_INET, 307 (1 == inet_pton(AF_INET,
308 addrstr, 308 addrstr,
309 &v4)) ) 309 &v4)))
310 { 310 {
311 memset (&a4, 0, sizeof (a4)); 311 memset(&a4, 0, sizeof(a4));
312 a4.sin_family = AF_INET; 312 a4.sin_family = AF_INET;
313#if HAVE_SOCKADDR_IN_SIN_LEN 313#if HAVE_SOCKADDR_IN_SIN_LEN
314 a4.sin_len = (u_char) sizeof (struct sockaddr_in); 314 a4.sin_len = (u_char)sizeof(struct sockaddr_in);
315#endif 315#endif
316 a4.sin_addr = v4; 316 a4.sin_addr = v4;
317 317
318 memset (&v4.s_addr, 0, sizeof (v4.s_addr)); 318 memset(&v4.s_addr, 0, sizeof(v4.s_addr));
319 for (i = 0; i < prefixlen; i++) 319 for (i = 0; i < prefixlen; i++)
320 v4.s_addr |= 1 << (i & 7); 320 v4.s_addr |= 1 << (i & 7);
321 memset (&netmask, 0, sizeof (netmask)); 321 memset(&netmask, 0, sizeof(netmask));
322 netmask.sin_family = AF_INET; 322 netmask.sin_family = AF_INET;
323#if HAVE_SOCKADDR_IN_SIN_LEN 323#if HAVE_SOCKADDR_IN_SIN_LEN
324 netmask.sin_len = (u_char) sizeof (struct sockaddr_in); 324 netmask.sin_len = (u_char)sizeof(struct sockaddr_in);
325#endif 325#endif
326 netmask.sin_addr = v4; 326 netmask.sin_addr = v4;
327 327
328 if (GNUNET_OK != 328 if (GNUNET_OK !=
329 proc (proc_cls, 329 proc(proc_cls,
330 ifname, 330 ifname,
331 (0 == strcmp (ifname, 331 (0 == strcmp(ifname,
332 GNUNET_DEFAULT_INTERFACE)), 332 GNUNET_DEFAULT_INTERFACE)),
333 (const struct sockaddr *) &a4, 333 (const struct sockaddr *)&a4,
334 NULL, 334 NULL,
335 (const struct sockaddr *) &netmask, 335 (const struct sockaddr *)&netmask,
336 sizeof (a4))) 336 sizeof(a4)))
337 break; 337 break;
338 } 338 }
339 /* IPv6 */ 339 /* IPv6 */
340 if ( (0 == strcasecmp ("inet6", 340 if ((0 == strcasecmp("inet6",
341 afstr)) && 341 afstr)) &&
342 (1 == inet_pton (AF_INET6, 342 (1 == inet_pton(AF_INET6,
343 addrstr, 343 addrstr,
344 &v6)) ) 344 &v6)))
345 { 345 {
346 memset (&a6, 0, sizeof (a6)); 346 memset(&a6, 0, sizeof(a6));
347 a6.sin6_family = AF_INET6; 347 a6.sin6_family = AF_INET6;
348#if HAVE_SOCKADDR_IN_SIN_LEN 348#if HAVE_SOCKADDR_IN_SIN_LEN
349 a6.sin6_len = (u_char) sizeof (struct sockaddr_in6); 349 a6.sin6_len = (u_char)sizeof(struct sockaddr_in6);
350#endif 350#endif
351 a6.sin6_addr = v6; 351 a6.sin6_addr = v6;
352 352
353 memset (v6.s6_addr, 0, sizeof (v6.s6_addr)); 353 memset(v6.s6_addr, 0, sizeof(v6.s6_addr));
354 for (i = 0; i < prefixlen; i++) 354 for (i = 0; i < prefixlen; i++)
355 v6.s6_addr[i >> 3] |= 1 << (i & 7); 355 v6.s6_addr[i >> 3] |= 1 << (i & 7);
356 memset (&netmask6, 0, sizeof (netmask6)); 356 memset(&netmask6, 0, sizeof(netmask6));
357 netmask6.sin6_family = AF_INET6; 357 netmask6.sin6_family = AF_INET6;
358#if HAVE_SOCKADDR_IN_SIN_LEN 358#if HAVE_SOCKADDR_IN_SIN_LEN
359 netmask6.sin6_len = (u_char) sizeof (struct sockaddr_in6); 359 netmask6.sin6_len = (u_char)sizeof(struct sockaddr_in6);
360#endif 360#endif
361 netmask6.sin6_addr = v6; 361 netmask6.sin6_addr = v6;
362 362
363 if (GNUNET_OK != 363 if (GNUNET_OK !=
364 proc (proc_cls, 364 proc(proc_cls,
365 ifname, 365 ifname,
366 (0 == strcmp (ifname, 366 (0 == strcmp(ifname,
367 GNUNET_DEFAULT_INTERFACE)), 367 GNUNET_DEFAULT_INTERFACE)),
368 (const struct sockaddr *) &a6, 368 (const struct sockaddr *)&a6,
369 NULL, 369 NULL,
370 (const struct sockaddr *) &netmask6, 370 (const struct sockaddr *)&netmask6,
371 sizeof (a6))) 371 sizeof(a6)))
372 break; 372 break;
373 }
373 } 374 }
374 } 375 pclose(f);
375 pclose (f);
376 return GNUNET_OK; 376 return GNUNET_OK;
377} 377}
378#endif 378#endif
@@ -385,8 +385,8 @@ try_ip (GNUNET_OS_NetworkInterfaceProcessor proc,
385 * @param proc_cls closure for @a proc 385 * @param proc_cls closure for @a proc
386 */ 386 */
387void 387void
388GNUNET_OS_network_interfaces_list (GNUNET_OS_NetworkInterfaceProcessor proc, 388GNUNET_OS_network_interfaces_list(GNUNET_OS_NetworkInterfaceProcessor proc,
389 void *proc_cls) 389 void *proc_cls)
390{ 390{
391#ifdef MINGW 391#ifdef MINGW
392 int r; 392 int r;
@@ -394,67 +394,65 @@ GNUNET_OS_network_interfaces_list (GNUNET_OS_NetworkInterfaceProcessor proc,
394 struct EnumNICs3_results *results = NULL; 394 struct EnumNICs3_results *results = NULL;
395 int results_count; 395 int results_count;
396 396
397 r = EnumNICs3 (&results, &results_count); 397 r = EnumNICs3(&results, &results_count);
398 if (r != GNUNET_OK) 398 if (r != GNUNET_OK)
399 return; 399 return;
400 400
401 for (i = 0; i < results_count; i++) 401 for (i = 0; i < results_count; i++)
402 { 402 {
403 if (GNUNET_OK != 403 if (GNUNET_OK !=
404 proc (proc_cls, results[i].pretty_name, results[i].is_default, 404 proc(proc_cls, results[i].pretty_name, results[i].is_default,
405 (const struct sockaddr *) &results[i].address, 405 (const struct sockaddr *)&results[i].address,
406 results[i]. 406 results[i].
407 flags & ENUMNICS3_BCAST_OK ? 407 flags & ENUMNICS3_BCAST_OK ?
408 (const struct sockaddr *) &results[i].broadcast : NULL, 408 (const struct sockaddr *)&results[i].broadcast : NULL,
409 results[i].flags & ENUMNICS3_MASK_OK ? 409 results[i].flags & ENUMNICS3_MASK_OK ?
410 (const struct sockaddr *) &results[i].mask : NULL, 410 (const struct sockaddr *)&results[i].mask : NULL,
411 results[i].addr_size)) 411 results[i].addr_size))
412 break; 412 break;
413 } 413 }
414 EnumNICs3_free (results); 414 EnumNICs3_free(results);
415 return; 415 return;
416
417#elif HAVE_GETIFADDRS && HAVE_FREEIFADDRS 416#elif HAVE_GETIFADDRS && HAVE_FREEIFADDRS
418
419 struct ifaddrs *ifa_first; 417 struct ifaddrs *ifa_first;
420 struct ifaddrs *ifa_ptr; 418 struct ifaddrs *ifa_ptr;
421 socklen_t alen; 419 socklen_t alen;
422 420
423 if (getifaddrs (&ifa_first) == 0) 421 if (getifaddrs(&ifa_first) == 0)
424 {
425 for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next)
426 { 422 {
427 if (ifa_ptr->ifa_name != NULL && ifa_ptr->ifa_addr != NULL && 423 for (ifa_ptr = ifa_first; ifa_ptr != NULL; ifa_ptr = ifa_ptr->ifa_next)
428 (ifa_ptr->ifa_flags & IFF_UP) != 0) 424 {
429 { 425 if (ifa_ptr->ifa_name != NULL && ifa_ptr->ifa_addr != NULL &&
430 if ((ifa_ptr->ifa_addr->sa_family != AF_INET) && 426 (ifa_ptr->ifa_flags & IFF_UP) != 0)
431 (ifa_ptr->ifa_addr->sa_family != AF_INET6)) 427 {
432 continue; 428 if ((ifa_ptr->ifa_addr->sa_family != AF_INET) &&
433 if (ifa_ptr->ifa_addr->sa_family == AF_INET) 429 (ifa_ptr->ifa_addr->sa_family != AF_INET6))
434 alen = sizeof (struct sockaddr_in); 430 continue;
435 else 431 if (ifa_ptr->ifa_addr->sa_family == AF_INET)
436 alen = sizeof (struct sockaddr_in6); 432 alen = sizeof(struct sockaddr_in);
437 if (GNUNET_OK != 433 else
438 proc (proc_cls, ifa_ptr->ifa_name, 434 alen = sizeof(struct sockaddr_in6);
439 0 == strcmp (ifa_ptr->ifa_name, GNUNET_DEFAULT_INTERFACE), 435 if (GNUNET_OK !=
440 ifa_ptr->ifa_addr, ifa_ptr->ifa_broadaddr, 436 proc(proc_cls, ifa_ptr->ifa_name,
441 ifa_ptr->ifa_netmask, alen)) 437 0 == strcmp(ifa_ptr->ifa_name, GNUNET_DEFAULT_INTERFACE),
442 break; 438 ifa_ptr->ifa_addr, ifa_ptr->ifa_broadaddr,
443 } 439 ifa_ptr->ifa_netmask, alen))
440 break;
441 }
442 }
443 freeifaddrs(ifa_first);
444 } 444 }
445 freeifaddrs (ifa_first);
446 }
447#else 445#else
448 if (GNUNET_OK == 446 if (GNUNET_OK ==
449 try_ip (proc, 447 try_ip(proc,
450 proc_cls)) 448 proc_cls))
451 return; 449 return;
452 if (GNUNET_OK == 450 if (GNUNET_OK ==
453 try_ifconfig (proc, 451 try_ifconfig(proc,
454 proc_cls)) 452 proc_cls))
455 return; 453 return;
456 LOG (GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK, 454 LOG(GNUNET_ERROR_TYPE_WARNING | GNUNET_ERROR_TYPE_BULK,
457 "Failed to enumerate network interfaces\n"); 455 "Failed to enumerate network interfaces\n");
458#endif 456#endif
459} 457}
460 458
diff --git a/src/util/os_priority.c b/src/util/os_priority.c
index 17baa0df8..e4f2371e7 100644
--- a/src/util/os_priority.c
+++ b/src/util/os_priority.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/os_priority.c 22 * @file util/os_priority.c
@@ -29,19 +29,18 @@
29#include "disk.h" 29#include "disk.h"
30#include <unistr.h> 30#include <unistr.h>
31 31
32#define LOG(kind, ...) GNUNET_log_from (kind, "util-os-priority", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-os-priority", __VA_ARGS__)
33 33
34#define LOG_STRERROR(kind, syscall) \ 34#define LOG_STRERROR(kind, syscall) \
35 GNUNET_log_from_strerror (kind, "util-os-priority", syscall) 35 GNUNET_log_from_strerror(kind, "util-os-priority", syscall)
36 36
37#define LOG_STRERROR_FILE(kind, syscall, filename) \ 37#define LOG_STRERROR_FILE(kind, syscall, filename) \
38 GNUNET_log_from_strerror_file (kind, "util-os-priority", syscall, filename) 38 GNUNET_log_from_strerror_file(kind, "util-os-priority", syscall, filename)
39 39
40#define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE" 40#define GNUNET_OS_CONTROL_PIPE "GNUNET_OS_CONTROL_PIPE"
41 41
42 42
43struct GNUNET_OS_Process 43struct GNUNET_OS_Process {
44{
45 /** 44 /**
46 * PID of the process. 45 * PID of the process.
47 */ 46 */
@@ -84,13 +83,13 @@ static struct GNUNET_SCHEDULER_Task *spch;
84 * @param cls the `struct GNUNET_DISK_FileHandle` of the control pipe 83 * @param cls the `struct GNUNET_DISK_FileHandle` of the control pipe
85 */ 84 */
86static void 85static void
87shutdown_pch (void *cls) 86shutdown_pch(void *cls)
88{ 87{
89 struct GNUNET_DISK_FileHandle *control_pipe = cls; 88 struct GNUNET_DISK_FileHandle *control_pipe = cls;
90 89
91 GNUNET_SCHEDULER_cancel (pch); 90 GNUNET_SCHEDULER_cancel(pch);
92 pch = NULL; 91 pch = NULL;
93 GNUNET_DISK_file_close (control_pipe); 92 GNUNET_DISK_file_close(control_pipe);
94 control_pipe = NULL; 93 control_pipe = NULL;
95} 94}
96 95
@@ -101,7 +100,7 @@ shutdown_pch (void *cls)
101 * @param cls the `struct GNUNET_DISK_FileHandle` of the control pipe 100 * @param cls the `struct GNUNET_DISK_FileHandle` of the control pipe
102 */ 101 */
103static void 102static void
104parent_control_handler (void *cls) 103parent_control_handler(void *cls)
105{ 104{
106 struct GNUNET_DISK_FileHandle *control_pipe = cls; 105 struct GNUNET_DISK_FileHandle *control_pipe = cls;
107 char sig; 106 char sig;
@@ -109,29 +108,29 @@ parent_control_handler (void *cls)
109 ssize_t ret; 108 ssize_t ret;
110 109
111 pch = NULL; 110 pch = NULL;
112 ret = GNUNET_DISK_file_read (control_pipe, &sig, sizeof (sig)); 111 ret = GNUNET_DISK_file_read(control_pipe, &sig, sizeof(sig));
113 if (sizeof (sig) != ret) 112 if (sizeof(sig) != ret)
114 { 113 {
115 if (-1 == ret) 114 if (-1 == ret)
116 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read"); 115 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "GNUNET_DISK_file_read");
117 LOG (GNUNET_ERROR_TYPE_DEBUG, "Closing control pipe\n"); 116 LOG(GNUNET_ERROR_TYPE_DEBUG, "Closing control pipe\n");
118 GNUNET_DISK_file_close (control_pipe); 117 GNUNET_DISK_file_close(control_pipe);
119 control_pipe = NULL; 118 control_pipe = NULL;
120 GNUNET_SCHEDULER_cancel (spch); 119 GNUNET_SCHEDULER_cancel(spch);
121 spch = NULL; 120 spch = NULL;
122 return; 121 return;
123 } 122 }
124 pipe_fd = getenv (GNUNET_OS_CONTROL_PIPE); 123 pipe_fd = getenv(GNUNET_OS_CONTROL_PIPE);
125 GNUNET_assert ((NULL == pipe_fd) || (strlen (pipe_fd) <= 0)); 124 GNUNET_assert((NULL == pipe_fd) || (strlen(pipe_fd) <= 0));
126 LOG (GNUNET_ERROR_TYPE_DEBUG, 125 LOG(GNUNET_ERROR_TYPE_DEBUG,
127 "Got control code %d from parent via pipe %s\n", 126 "Got control code %d from parent via pipe %s\n",
128 sig, 127 sig,
129 pipe_fd); 128 pipe_fd);
130 pch = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 129 pch = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
131 control_pipe, 130 control_pipe,
132 &parent_control_handler, 131 &parent_control_handler,
133 control_pipe); 132 control_pipe);
134 GNUNET_SIGNAL_raise ((int) sig); 133 GNUNET_SIGNAL_raise((int)sig);
135} 134}
136 135
137 136
@@ -144,71 +143,71 @@ parent_control_handler (void *cls)
144 * @param cls closure (unused) 143 * @param cls closure (unused)
145 */ 144 */
146void 145void
147GNUNET_OS_install_parent_control_handler (void *cls) 146GNUNET_OS_install_parent_control_handler(void *cls)
148{ 147{
149 const char *env_buf; 148 const char *env_buf;
150 char *env_buf_end; 149 char *env_buf_end;
151 struct GNUNET_DISK_FileHandle *control_pipe; 150 struct GNUNET_DISK_FileHandle *control_pipe;
152 uint64_t pipe_fd; 151 uint64_t pipe_fd;
153 152
154 (void) cls; 153 (void)cls;
155 if (NULL != pch) 154 if (NULL != pch)
156 { 155 {
157 /* already done, we've been called twice... */ 156 /* already done, we've been called twice... */
158 GNUNET_break (0); 157 GNUNET_break(0);
159 return; 158 return;
160 } 159 }
161 env_buf = getenv (GNUNET_OS_CONTROL_PIPE); 160 env_buf = getenv(GNUNET_OS_CONTROL_PIPE);
162 if ((NULL == env_buf) || (strlen (env_buf) <= 0)) 161 if ((NULL == env_buf) || (strlen(env_buf) <= 0))
163 { 162 {
164 LOG (GNUNET_ERROR_TYPE_DEBUG, 163 LOG(GNUNET_ERROR_TYPE_DEBUG,
165 "Not installing a handler because $%s is empty\n", 164 "Not installing a handler because $%s is empty\n",
166 GNUNET_OS_CONTROL_PIPE); 165 GNUNET_OS_CONTROL_PIPE);
167 putenv (GNUNET_OS_CONTROL_PIPE "="); 166 putenv(GNUNET_OS_CONTROL_PIPE "=");
168 return; 167 return;
169 } 168 }
170 errno = 0; 169 errno = 0;
171 pipe_fd = strtoull (env_buf, &env_buf_end, 16); 170 pipe_fd = strtoull(env_buf, &env_buf_end, 16);
172 if ((0 != errno) || (env_buf == env_buf_end)) 171 if ((0 != errno) || (env_buf == env_buf_end))
173 { 172 {
174 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "strtoull", env_buf); 173 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "strtoull", env_buf);
175 putenv (GNUNET_OS_CONTROL_PIPE "="); 174 putenv(GNUNET_OS_CONTROL_PIPE "=");
176 return; 175 return;
177 } 176 }
178#if ! defined(WINDOWS) 177#if !defined(WINDOWS)
179 if (pipe_fd >= FD_SETSIZE) 178 if (pipe_fd >= FD_SETSIZE)
180#else 179#else
181 if ((FILE_TYPE_UNKNOWN == GetFileType ((HANDLE) (uintptr_t) pipe_fd)) && 180 if ((FILE_TYPE_UNKNOWN == GetFileType((HANDLE)(uintptr_t)pipe_fd)) &&
182 (0 != GetLastError ())) 181 (0 != GetLastError()))
183#endif 182#endif
184 { 183 {
185 LOG (GNUNET_ERROR_TYPE_ERROR, 184 LOG(GNUNET_ERROR_TYPE_ERROR,
186 "GNUNET_OS_CONTROL_PIPE `%s' contains garbage?\n", 185 "GNUNET_OS_CONTROL_PIPE `%s' contains garbage?\n",
187 env_buf); 186 env_buf);
188 putenv (GNUNET_OS_CONTROL_PIPE "="); 187 putenv(GNUNET_OS_CONTROL_PIPE "=");
189 return; 188 return;
190 } 189 }
191#if WINDOWS 190#if WINDOWS
192 control_pipe = 191 control_pipe =
193 GNUNET_DISK_get_handle_from_w32_handle ((HANDLE) (uintptr_t) pipe_fd); 192 GNUNET_DISK_get_handle_from_w32_handle((HANDLE)(uintptr_t)pipe_fd);
194#else 193#else
195 control_pipe = GNUNET_DISK_get_handle_from_int_fd ((int) pipe_fd); 194 control_pipe = GNUNET_DISK_get_handle_from_int_fd((int)pipe_fd);
196#endif 195#endif
197 if (NULL == control_pipe) 196 if (NULL == control_pipe)
198 { 197 {
199 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "open", env_buf); 198 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "open", env_buf);
200 putenv (GNUNET_OS_CONTROL_PIPE "="); 199 putenv(GNUNET_OS_CONTROL_PIPE "=");
201 return; 200 return;
202 } 201 }
203 LOG (GNUNET_ERROR_TYPE_DEBUG, 202 LOG(GNUNET_ERROR_TYPE_DEBUG,
204 "Adding parent control handler pipe `%s' to the scheduler\n", 203 "Adding parent control handler pipe `%s' to the scheduler\n",
205 env_buf); 204 env_buf);
206 pch = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 205 pch = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
207 control_pipe, 206 control_pipe,
208 &parent_control_handler, 207 &parent_control_handler,
209 control_pipe); 208 control_pipe);
210 spch = GNUNET_SCHEDULER_add_shutdown (&shutdown_pch, control_pipe); 209 spch = GNUNET_SCHEDULER_add_shutdown(&shutdown_pch, control_pipe);
211 putenv (GNUNET_OS_CONTROL_PIPE "="); 210 putenv(GNUNET_OS_CONTROL_PIPE "=");
212} 211}
213 212
214 213
@@ -221,11 +220,11 @@ GNUNET_OS_install_parent_control_handler (void *cls)
221 * @return pointer to the process sturcutre for this process 220 * @return pointer to the process sturcutre for this process
222 */ 221 */
223struct GNUNET_OS_Process * 222struct GNUNET_OS_Process *
224GNUNET_OS_process_current () 223GNUNET_OS_process_current()
225{ 224{
226#if WINDOWS 225#if WINDOWS
227 current_process.pid = GetCurrentProcessId (); 226 current_process.pid = GetCurrentProcessId();
228 current_process.handle = GetCurrentProcess (); 227 current_process.handle = GetCurrentProcess();
229#else 228#else
230 current_process.pid = 0; 229 current_process.pid = 0;
231#endif 230#endif
@@ -241,92 +240,92 @@ GNUNET_OS_process_current ()
241 * @return 0 on success, -1 on error 240 * @return 0 on success, -1 on error
242 */ 241 */
243int 242int
244GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig) 243GNUNET_OS_process_kill(struct GNUNET_OS_Process *proc, int sig)
245{ 244{
246 int ret; 245 int ret;
247 char csig; 246 char csig;
248 247
249 csig = (char) sig; 248 csig = (char)sig;
250 if (NULL != proc->control_pipe) 249 if (NULL != proc->control_pipe)
251 { 250 {
252 LOG (GNUNET_ERROR_TYPE_DEBUG, 251 LOG(GNUNET_ERROR_TYPE_DEBUG,
253 "Sending signal %d to pid: %u via pipe\n", 252 "Sending signal %d to pid: %u via pipe\n",
254 sig, 253 sig,
255 proc->pid); 254 proc->pid);
256 ret = GNUNET_DISK_file_write (proc->control_pipe, &csig, sizeof (csig)); 255 ret = GNUNET_DISK_file_write(proc->control_pipe, &csig, sizeof(csig));
257 if (sizeof (csig) == ret) 256 if (sizeof(csig) == ret)
258 return 0; 257 return 0;
259 } 258 }
260 /* pipe failed or non-existent, try other methods */ 259 /* pipe failed or non-existent, try other methods */
261 switch (sig) 260 switch (sig)
262 { 261 {
263#if ! defined(WINDOWS) 262#if !defined(WINDOWS)
264 case SIGHUP: 263 case SIGHUP:
265#endif 264#endif
266 case SIGINT: 265 case SIGINT:
267 case SIGKILL: 266 case SIGKILL:
268 case SIGTERM: 267 case SIGTERM:
269#if (SIGTERM != GNUNET_TERM_SIG) 268#if (SIGTERM != GNUNET_TERM_SIG)
270 case GNUNET_TERM_SIG: 269 case GNUNET_TERM_SIG:
271#endif 270#endif
272#if defined(WINDOWS) && ! defined(__CYGWIN__) 271#if defined(WINDOWS) && !defined(__CYGWIN__)
273 {
274 DWORD exitcode;
275 int must_kill = GNUNET_YES;
276 if (0 != GetExitCodeProcess (proc->handle, &exitcode))
277 must_kill = (exitcode == STILL_ACTIVE) ? GNUNET_YES : GNUNET_NO;
278 if (GNUNET_YES == must_kill)
279 {
280 if (0 == SafeTerminateProcess (proc->handle, 0, 0))
281 { 272 {
282 DWORD error_code = GetLastError (); 273 DWORD exitcode;
283 if ((error_code != WAIT_TIMEOUT) && 274 int must_kill = GNUNET_YES;
284 (error_code != ERROR_PROCESS_ABORTED)) 275 if (0 != GetExitCodeProcess(proc->handle, &exitcode))
285 { 276 must_kill = (exitcode == STILL_ACTIVE) ? GNUNET_YES : GNUNET_NO;
286 LOG ((error_code == ERROR_ACCESS_DENIED) ? GNUNET_ERROR_TYPE_INFO 277 if (GNUNET_YES == must_kill)
287 : GNUNET_ERROR_TYPE_WARNING,
288 "SafeTermiateProcess failed with code %lu\n",
289 error_code);
290 /* The problem here is that a process that is already dying
291 * might cause SafeTerminateProcess to fail with
292 * ERROR_ACCESS_DENIED, but the process WILL die eventually.
293 * If we really had a permissions problem, hanging up (which
294 * is what will happen in process_wait() in that case) is
295 * a valid option.
296 */
297 if (ERROR_ACCESS_DENIED == error_code)
298 {
299 errno = 0;
300 }
301 else
302 { 278 {
303 SetErrnoFromWinError (error_code); 279 if (0 == SafeTerminateProcess(proc->handle, 0, 0))
304 return -1; 280 {
281 DWORD error_code = GetLastError();
282 if ((error_code != WAIT_TIMEOUT) &&
283 (error_code != ERROR_PROCESS_ABORTED))
284 {
285 LOG((error_code == ERROR_ACCESS_DENIED) ? GNUNET_ERROR_TYPE_INFO
286 : GNUNET_ERROR_TYPE_WARNING,
287 "SafeTermiateProcess failed with code %lu\n",
288 error_code);
289 /* The problem here is that a process that is already dying
290 * might cause SafeTerminateProcess to fail with
291 * ERROR_ACCESS_DENIED, but the process WILL die eventually.
292 * If we really had a permissions problem, hanging up (which
293 * is what will happen in process_wait() in that case) is
294 * a valid option.
295 */
296 if (ERROR_ACCESS_DENIED == error_code)
297 {
298 errno = 0;
299 }
300 else
301 {
302 SetErrnoFromWinError(error_code);
303 return -1;
304 }
305 }
306 }
305 } 307 }
306 }
307 } 308 }
308 } 309 return 0;
309 }
310 return 0;
311#else 310#else
312 LOG (GNUNET_ERROR_TYPE_DEBUG, 311 LOG(GNUNET_ERROR_TYPE_DEBUG,
313 "Sending signal %d to pid: %u via system call\n", 312 "Sending signal %d to pid: %u via system call\n",
314 sig, 313 sig,
315 proc->pid); 314 proc->pid);
316 return kill (proc->pid, sig); 315 return kill(proc->pid, sig);
317#endif 316#endif
318 default: 317 default:
319#if defined(WINDOWS) 318#if defined(WINDOWS)
320 errno = EINVAL; 319 errno = EINVAL;
321 return -1; 320 return -1;
322#else 321#else
323 LOG (GNUNET_ERROR_TYPE_DEBUG, 322 LOG(GNUNET_ERROR_TYPE_DEBUG,
324 "Sending signal %d to pid: %u via system call\n", 323 "Sending signal %d to pid: %u via system call\n",
325 sig, 324 sig,
326 proc->pid); 325 proc->pid);
327 return kill (proc->pid, sig); 326 return kill(proc->pid, sig);
328#endif 327#endif
329 } 328 }
330} 329}
331 330
332 331
@@ -338,7 +337,7 @@ GNUNET_OS_process_kill (struct GNUNET_OS_Process *proc, int sig)
338 * @return the current process id 337 * @return the current process id
339 */ 338 */
340pid_t 339pid_t
341GNUNET_OS_process_get_pid (struct GNUNET_OS_Process *proc) 340GNUNET_OS_process_get_pid(struct GNUNET_OS_Process *proc)
342{ 341{
343 return proc->pid; 342 return proc->pid;
344} 343}
@@ -351,15 +350,15 @@ GNUNET_OS_process_get_pid (struct GNUNET_OS_Process *proc)
351 * @param proc pointer to process structure 350 * @param proc pointer to process structure
352 */ 351 */
353void 352void
354GNUNET_OS_process_destroy (struct GNUNET_OS_Process *proc) 353GNUNET_OS_process_destroy(struct GNUNET_OS_Process *proc)
355{ 354{
356 if (NULL != proc->control_pipe) 355 if (NULL != proc->control_pipe)
357 GNUNET_DISK_file_close (proc->control_pipe); 356 GNUNET_DISK_file_close(proc->control_pipe);
358#if defined(WINDOWS) 357#if defined(WINDOWS)
359 if (NULL != proc->handle) 358 if (NULL != proc->handle)
360 CloseHandle (proc->handle); 359 CloseHandle(proc->handle);
361#endif 360#endif
362 GNUNET_free (proc); 361 GNUNET_free(proc);
363} 362}
364 363
365 364
@@ -379,14 +378,14 @@ extern GNUNET_SIGNAL_Handler w32_sigchld_handler;
379 * @param proc pointer to process structure 378 * @param proc pointer to process structure
380 */ 379 */
381static DWORD_WINAPI 380static DWORD_WINAPI
382child_wait_thread (void *arg) 381child_wait_thread(void *arg)
383{ 382{
384 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *) arg; 383 struct GNUNET_OS_Process *proc = (struct GNUNET_OS_Process *)arg;
385 384
386 WaitForSingleObject (proc->handle, INFINITE); 385 WaitForSingleObject(proc->handle, INFINITE);
387 386
388 if (w32_sigchld_handler) 387 if (w32_sigchld_handler)
389 w32_sigchld_handler (); 388 w32_sigchld_handler();
390 389
391 return 0; 390 return 0;
392} 391}
@@ -395,7 +394,7 @@ child_wait_thread (void *arg)
395 394
396#if MINGW 395#if MINGW
397static char * 396static char *
398CreateCustomEnvTable (char **vars) 397CreateCustomEnvTable(char **vars)
399{ 398{
400 char *win32_env_table; 399 char *win32_env_table;
401 char *ptr; 400 char *ptr;
@@ -412,90 +411,90 @@ CreateCustomEnvTable (char **vars)
412 char *var; 411 char *var;
413 char *val; 412 char *val;
414 413
415 win32_env_table = GetEnvironmentStringsA (); 414 win32_env_table = GetEnvironmentStringsA();
416 if (NULL == win32_env_table) 415 if (NULL == win32_env_table)
417 return NULL; 416 return NULL;
418 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++) 417 for (c = 0, var_ptr = vars; *var_ptr; var_ptr += 2, c++)
419 ; 418 ;
420 n_var = c; 419 n_var = c;
421 index = GNUNET_malloc (sizeof (char *) * n_var); 420 index = GNUNET_malloc(sizeof(char *) * n_var);
422 for (c = 0; c < n_var; c++) 421 for (c = 0; c < n_var; c++)
423 index[c] = 0; 422 index[c] = 0;
424 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++) 423 for (items_count = 0, ptr = win32_env_table; ptr[0] != 0; items_count++)
425 {
426 size_t len = strlen (ptr);
427 int found = 0;
428
429 for (var_ptr = vars; *var_ptr; var_ptr++)
430 { 424 {
431 var = *var_ptr++; 425 size_t len = strlen(ptr);
432 val = *var_ptr; 426 int found = 0;
433 var_len = strlen (var); 427
434 if (strncmp (var, ptr, var_len) == 0) 428 for (var_ptr = vars; *var_ptr; var_ptr++)
435 { 429 {
436 found = 1; 430 var = *var_ptr++;
437 index[c] = 1; 431 val = *var_ptr;
438 tablesize += var_len + strlen (val) + 1; 432 var_len = strlen(var);
439 break; 433 if (strncmp(var, ptr, var_len) == 0)
440 } 434 {
435 found = 1;
436 index[c] = 1;
437 tablesize += var_len + strlen(val) + 1;
438 break;
439 }
440 }
441 if (!found)
442 tablesize += len + 1;
443 ptr += len + 1;
441 } 444 }
442 if (! found)
443 tablesize += len + 1;
444 ptr += len + 1;
445 }
446 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++) 445 for (n_found = 0, c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
447 {
448 var = *var_ptr++;
449 val = *var_ptr;
450 if (index[c] != 1)
451 n_found += strlen (var) + strlen (val) + 1;
452 }
453 result = GNUNET_malloc (tablesize + n_found + 1);
454 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
455 {
456 size_t len = strlen (ptr);
457 int found = 0;
458
459 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
460 { 446 {
461 var = *var_ptr++; 447 var = *var_ptr++;
462 val = *var_ptr; 448 val = *var_ptr;
463 var_len = strlen (var); 449 if (index[c] != 1)
464 if (strncmp (var, ptr, var_len) == 0) 450 n_found += strlen(var) + strlen(val) + 1;
465 {
466 found = 1;
467 break;
468 }
469 }
470 if (! found)
471 {
472 strcpy (result_ptr, ptr);
473 result_ptr += len + 1;
474 } 451 }
475 else 452 result = GNUNET_malloc(tablesize + n_found + 1);
453 for (result_ptr = result, ptr = win32_env_table; ptr[0] != 0;)
476 { 454 {
477 strcpy (result_ptr, var); 455 size_t len = strlen(ptr);
478 result_ptr += var_len; 456 int found = 0;
479 strcpy (result_ptr, val); 457
480 result_ptr += strlen (val) + 1; 458 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
459 {
460 var = *var_ptr++;
461 val = *var_ptr;
462 var_len = strlen(var);
463 if (strncmp(var, ptr, var_len) == 0)
464 {
465 found = 1;
466 break;
467 }
468 }
469 if (!found)
470 {
471 strcpy(result_ptr, ptr);
472 result_ptr += len + 1;
473 }
474 else
475 {
476 strcpy(result_ptr, var);
477 result_ptr += var_len;
478 strcpy(result_ptr, val);
479 result_ptr += strlen(val) + 1;
480 }
481 ptr += len + 1;
481 } 482 }
482 ptr += len + 1;
483 }
484 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++) 483 for (c = 0, var_ptr = vars; *var_ptr; var_ptr++, c++)
485 {
486 var = *var_ptr++;
487 val = *var_ptr;
488 var_len = strlen (var);
489 if (index[c] != 1)
490 { 484 {
491 strcpy (result_ptr, var); 485 var = *var_ptr++;
492 result_ptr += var_len; 486 val = *var_ptr;
493 strcpy (result_ptr, val); 487 var_len = strlen(var);
494 result_ptr += strlen (val) + 1; 488 if (index[c] != 1)
489 {
490 strcpy(result_ptr, var);
491 result_ptr += var_len;
492 strcpy(result_ptr, val);
493 result_ptr += strlen(val) + 1;
494 }
495 } 495 }
496 } 496 FreeEnvironmentStrings(win32_env_table);
497 FreeEnvironmentStrings (win32_env_table); 497 GNUNET_free(index);
498 GNUNET_free (index);
499 *result_ptr = 0; 498 *result_ptr = 0;
500 return result; 499 return result;
501} 500}
@@ -510,25 +509,25 @@ CreateCustomEnvTable (char **vars)
510 * @param flags open flags (O_RDONLY, O_WRONLY) 509 * @param flags open flags (O_RDONLY, O_WRONLY)
511 */ 510 */
512static void 511static void
513open_dev_null (int target_fd, int flags) 512open_dev_null(int target_fd, int flags)
514{ 513{
515 int fd; 514 int fd;
516 515
517 fd = open ("/dev/null", flags); 516 fd = open("/dev/null", flags);
518 if (-1 == fd) 517 if (-1 == fd)
519 { 518 {
520 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "open", "/dev/null"); 519 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "open", "/dev/null");
521 return; 520 return;
522 } 521 }
523 if (fd == target_fd) 522 if (fd == target_fd)
524 return; 523 return;
525 if (-1 == dup2 (fd, target_fd)) 524 if (-1 == dup2(fd, target_fd))
526 { 525 {
527 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "dup2"); 526 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "dup2");
528 (void) close (fd); 527 (void)close(fd);
529 return; 528 return;
530 } 529 }
531 GNUNET_break (0 == close (fd)); 530 GNUNET_break(0 == close(fd));
532} 531}
533#endif 532#endif
534 533
@@ -551,14 +550,14 @@ open_dev_null (int target_fd, int flags)
551 * @return process ID of the new process, -1 on error 550 * @return process ID of the new process, -1 on error
552 */ 551 */
553static struct GNUNET_OS_Process * 552static struct GNUNET_OS_Process *
554start_process (int pipe_control, 553start_process(int pipe_control,
555 enum GNUNET_OS_InheritStdioFlags std_inheritance, 554 enum GNUNET_OS_InheritStdioFlags std_inheritance,
556 struct GNUNET_DISK_PipeHandle *pipe_stdin, 555 struct GNUNET_DISK_PipeHandle *pipe_stdin,
557 struct GNUNET_DISK_PipeHandle *pipe_stdout, 556 struct GNUNET_DISK_PipeHandle *pipe_stdout,
558 struct GNUNET_DISK_PipeHandle *pipe_stderr, 557 struct GNUNET_DISK_PipeHandle *pipe_stderr,
559 const SOCKTYPE *lsocks, 558 const SOCKTYPE *lsocks,
560 const char *filename, 559 const char *filename,
561 char *const argv[]) 560 char *const argv[])
562{ 561{
563#ifndef MINGW 562#ifndef MINGW
564 pid_t ret; 563 pid_t ret;
@@ -582,223 +581,223 @@ start_process (int pipe_control,
582 int fd_stdin_write; 581 int fd_stdin_write;
583 582
584 if (GNUNET_SYSERR == 583 if (GNUNET_SYSERR ==
585 GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL)) 584 GNUNET_OS_check_helper_binary(filename, GNUNET_NO, NULL))
586 return NULL; /* not executable */ 585 return NULL; /* not executable */
587 if (GNUNET_YES == pipe_control) 586 if (GNUNET_YES == pipe_control)
588 { 587 {
589 struct GNUNET_DISK_PipeHandle *childpipe; 588 struct GNUNET_DISK_PipeHandle *childpipe;
590 int dup_childpipe_read_fd = -1; 589 int dup_childpipe_read_fd = -1;
591 590
592 childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO); 591 childpipe = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
593 if (NULL == childpipe) 592 if (NULL == childpipe)
594 return NULL; 593 return NULL;
595 childpipe_read = 594 childpipe_read =
596 GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ); 595 GNUNET_DISK_pipe_detach_end(childpipe, GNUNET_DISK_PIPE_END_READ);
597 childpipe_write = 596 childpipe_write =
598 GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE); 597 GNUNET_DISK_pipe_detach_end(childpipe, GNUNET_DISK_PIPE_END_WRITE);
599 GNUNET_DISK_pipe_close (childpipe); 598 GNUNET_DISK_pipe_close(childpipe);
600 if ((NULL == childpipe_read) || (NULL == childpipe_write) || 599 if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
601 (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read, 600 (GNUNET_OK != GNUNET_DISK_internal_file_handle_(childpipe_read,
602 &childpipe_read_fd, 601 &childpipe_read_fd,
603 sizeof (int))) || 602 sizeof(int))) ||
604 (-1 == (dup_childpipe_read_fd = dup (childpipe_read_fd)))) 603 (-1 == (dup_childpipe_read_fd = dup(childpipe_read_fd))))
605 { 604 {
606 if (NULL != childpipe_read) 605 if (NULL != childpipe_read)
607 GNUNET_DISK_file_close (childpipe_read); 606 GNUNET_DISK_file_close(childpipe_read);
608 if (NULL != childpipe_write) 607 if (NULL != childpipe_write)
609 GNUNET_DISK_file_close (childpipe_write); 608 GNUNET_DISK_file_close(childpipe_write);
610 if (0 <= dup_childpipe_read_fd) 609 if (0 <= dup_childpipe_read_fd)
611 close (dup_childpipe_read_fd); 610 close(dup_childpipe_read_fd);
612 return NULL; 611 return NULL;
612 }
613 childpipe_read_fd = dup_childpipe_read_fd;
614 GNUNET_DISK_file_close(childpipe_read);
613 } 615 }
614 childpipe_read_fd = dup_childpipe_read_fd;
615 GNUNET_DISK_file_close (childpipe_read);
616 }
617 else 616 else
618 { 617 {
619 childpipe_write = NULL; 618 childpipe_write = NULL;
620 childpipe_read_fd = -1; 619 childpipe_read_fd = -1;
621 } 620 }
622 if (NULL != pipe_stdin) 621 if (NULL != pipe_stdin)
623 { 622 {
624 GNUNET_assert ( 623 GNUNET_assert(
625 GNUNET_OK == 624 GNUNET_OK ==
626 GNUNET_DISK_internal_file_handle_ ( 625 GNUNET_DISK_internal_file_handle_(
627 GNUNET_DISK_pipe_handle (pipe_stdin, GNUNET_DISK_PIPE_END_READ), 626 GNUNET_DISK_pipe_handle(pipe_stdin, GNUNET_DISK_PIPE_END_READ),
628 &fd_stdin_read, 627 &fd_stdin_read,
629 sizeof (int))); 628 sizeof(int)));
630 GNUNET_assert ( 629 GNUNET_assert(
631 GNUNET_OK == 630 GNUNET_OK ==
632 GNUNET_DISK_internal_file_handle_ ( 631 GNUNET_DISK_internal_file_handle_(
633 GNUNET_DISK_pipe_handle (pipe_stdin, GNUNET_DISK_PIPE_END_WRITE), 632 GNUNET_DISK_pipe_handle(pipe_stdin, GNUNET_DISK_PIPE_END_WRITE),
634 &fd_stdin_write, 633 &fd_stdin_write,
635 sizeof (int))); 634 sizeof(int)));
636 } 635 }
637 if (NULL != pipe_stdout) 636 if (NULL != pipe_stdout)
638 { 637 {
639 GNUNET_assert ( 638 GNUNET_assert(
640 GNUNET_OK == 639 GNUNET_OK ==
641 GNUNET_DISK_internal_file_handle_ ( 640 GNUNET_DISK_internal_file_handle_(
642 GNUNET_DISK_pipe_handle (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE), 641 GNUNET_DISK_pipe_handle(pipe_stdout, GNUNET_DISK_PIPE_END_WRITE),
643 &fd_stdout_write, 642 &fd_stdout_write,
644 sizeof (int))); 643 sizeof(int)));
645 GNUNET_assert ( 644 GNUNET_assert(
646 GNUNET_OK == 645 GNUNET_OK ==
647 GNUNET_DISK_internal_file_handle_ ( 646 GNUNET_DISK_internal_file_handle_(
648 GNUNET_DISK_pipe_handle (pipe_stdout, GNUNET_DISK_PIPE_END_READ), 647 GNUNET_DISK_pipe_handle(pipe_stdout, GNUNET_DISK_PIPE_END_READ),
649 &fd_stdout_read, 648 &fd_stdout_read,
650 sizeof (int))); 649 sizeof(int)));
651 } 650 }
652 if (NULL != pipe_stderr) 651 if (NULL != pipe_stderr)
653 { 652 {
654 GNUNET_assert ( 653 GNUNET_assert(
655 GNUNET_OK == 654 GNUNET_OK ==
656 GNUNET_DISK_internal_file_handle_ ( 655 GNUNET_DISK_internal_file_handle_(
657 GNUNET_DISK_pipe_handle (pipe_stderr, GNUNET_DISK_PIPE_END_READ), 656 GNUNET_DISK_pipe_handle(pipe_stderr, GNUNET_DISK_PIPE_END_READ),
658 &fd_stderr_read, 657 &fd_stderr_read,
659 sizeof (int))); 658 sizeof(int)));
660 GNUNET_assert ( 659 GNUNET_assert(
661 GNUNET_OK == 660 GNUNET_OK ==
662 GNUNET_DISK_internal_file_handle_ ( 661 GNUNET_DISK_internal_file_handle_(
663 GNUNET_DISK_pipe_handle (pipe_stderr, GNUNET_DISK_PIPE_END_WRITE), 662 GNUNET_DISK_pipe_handle(pipe_stderr, GNUNET_DISK_PIPE_END_WRITE),
664 &fd_stderr_write, 663 &fd_stderr_write,
665 sizeof (int))); 664 sizeof(int)));
666 } 665 }
667 lscp = NULL; 666 lscp = NULL;
668 ls = 0; 667 ls = 0;
669 if (NULL != lsocks) 668 if (NULL != lsocks)
670 { 669 {
671 i = 0; 670 i = 0;
672 while (-1 != (k = lsocks[i++])) 671 while (-1 != (k = lsocks[i++]))
673 GNUNET_array_append (lscp, ls, k); 672 GNUNET_array_append(lscp, ls, k);
674 GNUNET_array_append (lscp, ls, -1); 673 GNUNET_array_append(lscp, ls, -1);
675 } 674 }
676#if DARWIN 675#if DARWIN
677 /* see https://gnunet.org/vfork */ 676 /* see https://gnunet.org/vfork */
678 ret = vfork (); 677 ret = vfork();
679#else 678#else
680 ret = fork (); 679 ret = fork();
681#endif 680#endif
682 if (-1 == ret) 681 if (-1 == ret)
683 { 682 {
684 int eno = errno; 683 int eno = errno;
685 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork"); 684 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "fork");
686 GNUNET_array_grow (lscp, ls, 0); 685 GNUNET_array_grow(lscp, ls, 0);
687 if (NULL != childpipe_write) 686 if (NULL != childpipe_write)
688 GNUNET_DISK_file_close (childpipe_write); 687 GNUNET_DISK_file_close(childpipe_write);
689 if (0 <= childpipe_read_fd) 688 if (0 <= childpipe_read_fd)
690 close (childpipe_read_fd); 689 close(childpipe_read_fd);
691 errno = eno; 690 errno = eno;
692 return NULL; 691 return NULL;
693 } 692 }
694 if (0 != ret) 693 if (0 != ret)
695 {
696 unsetenv (GNUNET_OS_CONTROL_PIPE);
697 gnunet_proc = GNUNET_new (struct GNUNET_OS_Process);
698 gnunet_proc->pid = ret;
699 gnunet_proc->control_pipe = childpipe_write;
700 if (GNUNET_YES == pipe_control)
701 { 694 {
702 close (childpipe_read_fd); 695 unsetenv(GNUNET_OS_CONTROL_PIPE);
696 gnunet_proc = GNUNET_new(struct GNUNET_OS_Process);
697 gnunet_proc->pid = ret;
698 gnunet_proc->control_pipe = childpipe_write;
699 if (GNUNET_YES == pipe_control)
700 {
701 close(childpipe_read_fd);
702 }
703 GNUNET_array_grow(lscp, ls, 0);
704 return gnunet_proc;
703 } 705 }
704 GNUNET_array_grow (lscp, ls, 0);
705 return gnunet_proc;
706 }
707 if (0 <= childpipe_read_fd) 706 if (0 <= childpipe_read_fd)
708 { 707 {
709 char fdbuf[100]; 708 char fdbuf[100];
710#ifndef DARWIN 709#ifndef DARWIN
711 /* due to vfork, we must NOT free memory on DARWIN! */ 710 /* due to vfork, we must NOT free memory on DARWIN! */
712 GNUNET_DISK_file_close (childpipe_write); 711 GNUNET_DISK_file_close(childpipe_write);
713#endif 712#endif
714 snprintf (fdbuf, 100, "%x", childpipe_read_fd); 713 snprintf(fdbuf, 100, "%x", childpipe_read_fd);
715 setenv (GNUNET_OS_CONTROL_PIPE, fdbuf, 1); 714 setenv(GNUNET_OS_CONTROL_PIPE, fdbuf, 1);
716 } 715 }
717 else 716 else
718 unsetenv (GNUNET_OS_CONTROL_PIPE); 717 unsetenv(GNUNET_OS_CONTROL_PIPE);
719 if (NULL != pipe_stdin) 718 if (NULL != pipe_stdin)
720 { 719 {
721 GNUNET_break (0 == close (fd_stdin_write)); 720 GNUNET_break(0 == close(fd_stdin_write));
722 if (-1 == dup2 (fd_stdin_read, 0)) 721 if (-1 == dup2(fd_stdin_read, 0))
723 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2"); 722 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "dup2");
724 GNUNET_break (0 == close (fd_stdin_read)); 723 GNUNET_break(0 == close(fd_stdin_read));
725 } 724 }
726 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN)) 725 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_IN))
727 { 726 {
728 GNUNET_break (0 == close (0)); 727 GNUNET_break(0 == close(0));
729 open_dev_null (0, O_RDONLY); 728 open_dev_null(0, O_RDONLY);
730 } 729 }
731 if (NULL != pipe_stdout) 730 if (NULL != pipe_stdout)
732 { 731 {
733 GNUNET_break (0 == close (fd_stdout_read)); 732 GNUNET_break(0 == close(fd_stdout_read));
734 if (-1 == dup2 (fd_stdout_write, 1)) 733 if (-1 == dup2(fd_stdout_write, 1))
735 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2"); 734 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "dup2");
736 GNUNET_break (0 == close (fd_stdout_write)); 735 GNUNET_break(0 == close(fd_stdout_write));
737 } 736 }
738 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)) 737 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_OUT))
739 { 738 {
740 GNUNET_break (0 == close (1)); 739 GNUNET_break(0 == close(1));
741 open_dev_null (1, O_WRONLY); 740 open_dev_null(1, O_WRONLY);
742 } 741 }
743 if (NULL != pipe_stderr) 742 if (NULL != pipe_stderr)
744 { 743 {
745 GNUNET_break (0 == close (fd_stderr_read)); 744 GNUNET_break(0 == close(fd_stderr_read));
746 if (-1 == dup2 (fd_stderr_write, 2)) 745 if (-1 == dup2(fd_stderr_write, 2))
747 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2"); 746 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "dup2");
748 GNUNET_break (0 == close (fd_stderr_write)); 747 GNUNET_break(0 == close(fd_stderr_write));
749 } 748 }
750 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)) 749 else if (0 == (std_inheritance & GNUNET_OS_INHERIT_STD_ERR))
751 { 750 {
752 GNUNET_break (0 == close (2)); 751 GNUNET_break(0 == close(2));
753 open_dev_null (2, O_WRONLY); 752 open_dev_null(2, O_WRONLY);
754 } 753 }
755 if (NULL != lscp) 754 if (NULL != lscp)
756 {
757 /* read systemd documentation... */
758 i = 0;
759 tgt = 3;
760 while (-1 != lscp[i])
761 { 755 {
762 j = i + 1; 756 /* read systemd documentation... */
763 while (-1 != lscp[j]) 757 i = 0;
764 { 758 tgt = 3;
765 if (lscp[j] == tgt) 759 while (-1 != lscp[i])
766 { 760 {
767 /* dup away */ 761 j = i + 1;
768 k = dup (lscp[j]); 762 while (-1 != lscp[j])
769 GNUNET_assert (-1 != k); 763 {
770 GNUNET_assert (0 == close (lscp[j])); 764 if (lscp[j] == tgt)
771 lscp[j] = k; 765 {
772 break; 766 /* dup away */
767 k = dup(lscp[j]);
768 GNUNET_assert(-1 != k);
769 GNUNET_assert(0 == close(lscp[j]));
770 lscp[j] = k;
771 break;
772 }
773 j++;
774 }
775 if (lscp[i] != tgt)
776 {
777 /* Bury any existing FD, no matter what; they should all be closed
778 * on exec anyway and the important onces have been dup'ed away */
779 (void)close(tgt);
780 GNUNET_assert(-1 != dup2(lscp[i], tgt));
781 }
782 /* unset close-on-exec flag */
783 flags = fcntl(tgt, F_GETFD);
784 GNUNET_assert(flags >= 0);
785 flags &= ~FD_CLOEXEC;
786 fflush(stderr);
787 (void)fcntl(tgt, F_SETFD, flags);
788 tgt++;
789 i++;
773 } 790 }
774 j++; 791 GNUNET_snprintf(fds, sizeof(fds), "%u", i);
775 } 792 setenv("LISTEN_FDS", fds, 1);
776 if (lscp[i] != tgt) 793 }
777 {
778 /* Bury any existing FD, no matter what; they should all be closed
779 * on exec anyway and the important onces have been dup'ed away */
780 (void) close (tgt);
781 GNUNET_assert (-1 != dup2 (lscp[i], tgt));
782 }
783 /* unset close-on-exec flag */
784 flags = fcntl (tgt, F_GETFD);
785 GNUNET_assert (flags >= 0);
786 flags &= ~FD_CLOEXEC;
787 fflush (stderr);
788 (void) fcntl (tgt, F_SETFD, flags);
789 tgt++;
790 i++;
791 }
792 GNUNET_snprintf (fds, sizeof (fds), "%u", i);
793 setenv ("LISTEN_FDS", fds, 1);
794 }
795#ifndef DARWIN 794#ifndef DARWIN
796 /* due to vfork, we must NOT free memory on DARWIN! */ 795 /* due to vfork, we must NOT free memory on DARWIN! */
797 GNUNET_array_grow (lscp, ls, 0); 796 GNUNET_array_grow(lscp, ls, 0);
798#endif 797#endif
799 execvp (filename, argv); 798 execvp(filename, argv);
800 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, "execvp", filename); 799 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR, "execvp", filename);
801 _exit (1); 800 _exit(1);
802#else 801#else
803 struct GNUNET_DISK_FileHandle *childpipe_read; 802 struct GNUNET_DISK_FileHandle *childpipe_read;
804 struct GNUNET_DISK_FileHandle *childpipe_write; 803 struct GNUNET_DISK_FileHandle *childpipe_write;
@@ -813,7 +812,7 @@ start_process (int pipe_control,
813 int argcount = 0; 812 int argcount = 0;
814 struct GNUNET_OS_Process *gnunet_proc; 813 struct GNUNET_OS_Process *gnunet_proc;
815 char path[MAX_PATH + 1]; 814 char path[MAX_PATH + 1];
816 char *our_env[7] = {NULL, NULL, NULL, NULL, NULL, NULL, NULL}; 815 char *our_env[7] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL };
817 char *env_block = NULL; 816 char *env_block = NULL;
818 char *pathbuf; 817 char *pathbuf;
819 DWORD pathbuf_len; 818 DWORD pathbuf_len;
@@ -844,499 +843,500 @@ start_process (int pipe_control,
844 DWORD create_no_window; 843 DWORD create_no_window;
845 844
846 if (GNUNET_SYSERR == 845 if (GNUNET_SYSERR ==
847 GNUNET_OS_check_helper_binary (filename, GNUNET_NO, NULL)) 846 GNUNET_OS_check_helper_binary(filename, GNUNET_NO, NULL))
848 return NULL; /* not executable */ 847 return NULL; /* not executable */
849 848
850 /* Search in prefix dir (hopefully - the directory from which 849 /* Search in prefix dir (hopefully - the directory from which
851 * the current module was loaded), bindir and libdir, then in PATH 850 * the current module was loaded), bindir and libdir, then in PATH
852 */ 851 */
853 self_prefix = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_SELF_PREFIX); 852 self_prefix = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_SELF_PREFIX);
854 bindir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_BINDIR); 853 bindir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_BINDIR);
855 libdir = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR); 854 libdir = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LIBDIR);
856 855
857 pathbuf_len = GetEnvironmentVariableA ("PATH", (char *) &pathbuf, 0); 856 pathbuf_len = GetEnvironmentVariableA("PATH", (char *)&pathbuf, 0);
858 857
859 alloc_len = pathbuf_len + 1 + strlen (self_prefix) + 1 + strlen (bindir) + 1 + 858 alloc_len = pathbuf_len + 1 + strlen(self_prefix) + 1 + strlen(bindir) + 1 +
860 strlen (libdir); 859 strlen(libdir);
861 860
862 pathbuf = GNUNET_malloc (alloc_len * sizeof (char)); 861 pathbuf = GNUNET_malloc(alloc_len * sizeof(char));
863 862
864 ptr = pathbuf; 863 ptr = pathbuf;
865 ptr += sprintf (pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir); 864 ptr += sprintf(pathbuf, "%s;%s;%s;", self_prefix, bindir, libdir);
866 GNUNET_free (self_prefix); 865 GNUNET_free(self_prefix);
867 GNUNET_free (bindir); 866 GNUNET_free(bindir);
868 GNUNET_free (libdir); 867 GNUNET_free(libdir);
869 868
870 alloc_len = GetEnvironmentVariableA ("PATH", ptr, pathbuf_len); 869 alloc_len = GetEnvironmentVariableA("PATH", ptr, pathbuf_len);
871 if (alloc_len != pathbuf_len - 1) 870 if (alloc_len != pathbuf_len - 1)
872 { 871 {
873 GNUNET_free (pathbuf); 872 GNUNET_free(pathbuf);
874 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */ 873 errno = ENOSYS; /* PATH changed on the fly. What kind of error is that? */
875 return NULL; 874 return NULL;
876 } 875 }
877 876
878 cmdlen = strlen (filename); 877 cmdlen = strlen(filename);
879 if ((cmdlen < 5) || (0 != strcmp (&filename[cmdlen - 4], ".exe"))) 878 if ((cmdlen < 5) || (0 != strcmp(&filename[cmdlen - 4], ".exe")))
880 GNUNET_asprintf (&non_const_filename, "%s.exe", filename); 879 GNUNET_asprintf(&non_const_filename, "%s.exe", filename);
881 else 880 else
882 GNUNET_asprintf (&non_const_filename, "%s", filename); 881 GNUNET_asprintf(&non_const_filename, "%s", filename);
883 882
884 /* It could be in POSIX form, convert it to a DOS path early on */ 883 /* It could be in POSIX form, convert it to a DOS path early on */
885 if (ERROR_SUCCESS != 884 if (ERROR_SUCCESS !=
886 (lRet = plibc_conv_to_win_path (non_const_filename, win_path))) 885 (lRet = plibc_conv_to_win_path(non_const_filename, win_path)))
887 { 886 {
888 SetErrnoFromWinError (lRet); 887 SetErrnoFromWinError(lRet);
889 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, 888 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR,
890 "plibc_conv_to_win_path", 889 "plibc_conv_to_win_path",
891 non_const_filename); 890 non_const_filename);
892 GNUNET_free (non_const_filename); 891 GNUNET_free(non_const_filename);
893 GNUNET_free (pathbuf); 892 GNUNET_free(pathbuf);
894 return NULL; 893 return NULL;
895 } 894 }
896 GNUNET_free (non_const_filename); 895 GNUNET_free(non_const_filename);
897 non_const_filename = GNUNET_strdup (win_path); 896 non_const_filename = GNUNET_strdup(win_path);
898 /* Check that this is the full path. If it isn't, search. */ 897 /* Check that this is the full path. If it isn't, search. */
899 /* FIXME: convert it to wchar_t and use SearchPathW? 898 /* FIXME: convert it to wchar_t and use SearchPathW?
900 * Remember: arguments to _start_process() are technically in UTF-8... 899 * Remember: arguments to _start_process() are technically in UTF-8...
901 */ 900 */
902 if (non_const_filename[1] == ':') 901 if (non_const_filename[1] == ':')
903 { 902 {
904 snprintf (path, sizeof (path) / sizeof (char), "%s", non_const_filename); 903 snprintf(path, sizeof(path) / sizeof(char), "%s", non_const_filename);
905 LOG (GNUNET_ERROR_TYPE_DEBUG, 904 LOG(GNUNET_ERROR_TYPE_DEBUG,
906 "Using path `%s' as-is. PATH is %s\n", 905 "Using path `%s' as-is. PATH is %s\n",
907 path, 906 path,
908 ptr); 907 ptr);
909 } 908 }
910 else if (! SearchPathA (pathbuf, 909 else if (!SearchPathA(pathbuf,
911 non_const_filename, 910 non_const_filename,
912 NULL, 911 NULL,
913 sizeof (path) / sizeof (char), 912 sizeof(path) / sizeof(char),
914 path, 913 path,
915 NULL)) 914 NULL))
916 { 915 {
917 SetErrnoFromWinError (GetLastError ()); 916 SetErrnoFromWinError(GetLastError());
918 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_ERROR, 917 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_ERROR,
919 "SearchPath", 918 "SearchPath",
920 non_const_filename); 919 non_const_filename);
921 GNUNET_free (non_const_filename); 920 GNUNET_free(non_const_filename);
922 GNUNET_free (pathbuf); 921 GNUNET_free(pathbuf);
923 return NULL; 922 return NULL;
924 } 923 }
925 else 924 else
926 LOG (GNUNET_ERROR_TYPE_DEBUG, "Found `%s' in PATH `%s'\n", path, pathbuf); 925 LOG(GNUNET_ERROR_TYPE_DEBUG, "Found `%s' in PATH `%s'\n", path, pathbuf);
927 GNUNET_free (pathbuf); 926 GNUNET_free(pathbuf);
928 GNUNET_free (non_const_filename); 927 GNUNET_free(non_const_filename);
929 928
930 /* Count the number of arguments */ 929 /* Count the number of arguments */
931 arg = (char **) argv; 930 arg = (char **)argv;
932 while (*arg) 931 while (*arg)
933 { 932 {
934 arg++; 933 arg++;
935 argcount++; 934 argcount++;
936 } 935 }
937 936
938 /* Allocate a copy argv */ 937 /* Allocate a copy argv */
939 non_const_argv = GNUNET_malloc (sizeof (char *) * (argcount + 1)); 938 non_const_argv = GNUNET_malloc(sizeof(char *) * (argcount + 1));
940 939
941 /* Copy all argv strings */ 940 /* Copy all argv strings */
942 argcount = 0; 941 argcount = 0;
943 arg = (char **) argv; 942 arg = (char **)argv;
944 while (*arg) 943 while (*arg)
945 { 944 {
946 if (arg == argv) 945 if (arg == argv)
947 non_const_argv[argcount] = GNUNET_strdup (path); 946 non_const_argv[argcount] = GNUNET_strdup(path);
948 else 947 else
949 non_const_argv[argcount] = GNUNET_strdup (*arg); 948 non_const_argv[argcount] = GNUNET_strdup(*arg);
950 arg++; 949 arg++;
951 argcount++; 950 argcount++;
952 } 951 }
953 non_const_argv[argcount] = NULL; 952 non_const_argv[argcount] = NULL;
954 953
955 /* Count cmd len */ 954 /* Count cmd len */
956 cmdlen = 1; 955 cmdlen = 1;
957 arg = non_const_argv; 956 arg = non_const_argv;
958 while (*arg) 957 while (*arg)
959 { 958 {
960 cmdlen = cmdlen + strlen (*arg) + 4; 959 cmdlen = cmdlen + strlen(*arg) + 4;
961 arg++; 960 arg++;
962 } 961 }
963 962
964 /* Allocate and create cmd */ 963 /* Allocate and create cmd */
965 cmd = idx = GNUNET_malloc (sizeof (char) * cmdlen); 964 cmd = idx = GNUNET_malloc(sizeof(char) * cmdlen);
966 arg = non_const_argv; 965 arg = non_const_argv;
967 while (*arg) 966 while (*arg)
968 { 967 {
969 char arg_last_char = (*arg)[strlen (*arg) - 1]; 968 char arg_last_char = (*arg)[strlen(*arg) - 1];
970 idx += sprintf (idx, 969 idx += sprintf(idx,
971 "\"%s%s\"%s", 970 "\"%s%s\"%s",
972 *arg, 971 *arg,
973 arg_last_char == '\\' ? "\\" : "", 972 arg_last_char == '\\' ? "\\" : "",
974 *(arg + 1) ? " " : ""); 973 *(arg + 1) ? " " : "");
975 arg++; 974 arg++;
976 } 975 }
977 976
978 while (argcount > 0) 977 while (argcount > 0)
979 GNUNET_free (non_const_argv[--argcount]); 978 GNUNET_free(non_const_argv[--argcount]);
980 GNUNET_free (non_const_argv); 979 GNUNET_free(non_const_argv);
981 980
982 memset (&start, 0, sizeof (start)); 981 memset(&start, 0, sizeof(start));
983 start.cb = sizeof (start); 982 start.cb = sizeof(start);
984 if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0)) 983 if ((pipe_stdin != NULL) || (pipe_stdout != NULL) || (std_inheritance != 0))
985 start.dwFlags |= STARTF_USESTDHANDLES; 984 start.dwFlags |= STARTF_USESTDHANDLES;
986 985
987 stdih = GetStdHandle (STD_INPUT_HANDLE); 986 stdih = GetStdHandle(STD_INPUT_HANDLE);
988 GetHandleInformation (stdih, &stdif); 987 GetHandleInformation(stdih, &stdif);
989 if (pipe_stdin != NULL) 988 if (pipe_stdin != NULL)
990 { 989 {
991 GNUNET_DISK_internal_file_handle_ ( 990 GNUNET_DISK_internal_file_handle_(
992 GNUNET_DISK_pipe_handle (pipe_stdin, GNUNET_DISK_PIPE_END_READ), 991 GNUNET_DISK_pipe_handle(pipe_stdin, GNUNET_DISK_PIPE_END_READ),
993 &stdin_handle, 992 &stdin_handle,
994 sizeof (HANDLE)); 993 sizeof(HANDLE));
995 start.hStdInput = stdin_handle; 994 start.hStdInput = stdin_handle;
996 } 995 }
997 else if (stdih) 996 else if (stdih)
998 {
999 if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
1000 { 997 {
1001 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 1); 998 if (std_inheritance & GNUNET_OS_INHERIT_STD_IN)
1002 if (pipe_stdin == NULL) 999 {
1003 start.hStdInput = stdih; 1000 SetHandleInformation(stdih, HANDLE_FLAG_INHERIT, 1);
1001 if (pipe_stdin == NULL)
1002 start.hStdInput = stdih;
1003 }
1004 else
1005 SetHandleInformation(stdih, HANDLE_FLAG_INHERIT, 0);
1004 } 1006 }
1005 else
1006 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, 0);
1007 }
1008 1007
1009 1008
1010 stdoh = GetStdHandle (STD_OUTPUT_HANDLE); 1009 stdoh = GetStdHandle(STD_OUTPUT_HANDLE);
1011 GetHandleInformation (stdoh, &stdof); 1010 GetHandleInformation(stdoh, &stdof);
1012 if (NULL != pipe_stdout) 1011 if (NULL != pipe_stdout)
1013 { 1012 {
1014 GNUNET_DISK_internal_file_handle_ ( 1013 GNUNET_DISK_internal_file_handle_(
1015 GNUNET_DISK_pipe_handle (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE), 1014 GNUNET_DISK_pipe_handle(pipe_stdout, GNUNET_DISK_PIPE_END_WRITE),
1016 &stdout_handle, 1015 &stdout_handle,
1017 sizeof (HANDLE)); 1016 sizeof(HANDLE));
1018 start.hStdOutput = stdout_handle; 1017 start.hStdOutput = stdout_handle;
1019 } 1018 }
1020 else if (stdoh) 1019 else if (stdoh)
1021 {
1022 if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
1023 { 1020 {
1024 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 1); 1021 if (std_inheritance & GNUNET_OS_INHERIT_STD_OUT)
1025 if (pipe_stdout == NULL) 1022 {
1026 start.hStdOutput = stdoh; 1023 SetHandleInformation(stdoh, HANDLE_FLAG_INHERIT, 1);
1024 if (pipe_stdout == NULL)
1025 start.hStdOutput = stdoh;
1026 }
1027 else
1028 SetHandleInformation(stdoh, HANDLE_FLAG_INHERIT, 0);
1027 } 1029 }
1028 else
1029 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, 0);
1030 }
1031 1030
1032 stdeh = GetStdHandle (STD_ERROR_HANDLE); 1031 stdeh = GetStdHandle(STD_ERROR_HANDLE);
1033 GetHandleInformation (stdeh, &stdef); 1032 GetHandleInformation(stdeh, &stdef);
1034 if (stdeh) 1033 if (stdeh)
1035 {
1036 if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
1037 { 1034 {
1038 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 1); 1035 if (std_inheritance & GNUNET_OS_INHERIT_STD_ERR)
1039 start.hStdError = stdeh; 1036 {
1037 SetHandleInformation(stdeh, HANDLE_FLAG_INHERIT, 1);
1038 start.hStdError = stdeh;
1039 }
1040 else
1041 SetHandleInformation(stdeh, HANDLE_FLAG_INHERIT, 0);
1040 } 1042 }
1041 else
1042 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, 0);
1043 }
1044 1043
1045 if (GNUNET_YES == pipe_control) 1044 if (GNUNET_YES == pipe_control)
1046 { 1045 {
1047 struct GNUNET_DISK_PipeHandle *childpipe; 1046 struct GNUNET_DISK_PipeHandle *childpipe;
1048 childpipe = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO); 1047 childpipe = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_YES, GNUNET_NO);
1049 if (NULL == childpipe) 1048 if (NULL == childpipe)
1050 return NULL; 1049 return NULL;
1051 childpipe_read = 1050 childpipe_read =
1052 GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_READ); 1051 GNUNET_DISK_pipe_detach_end(childpipe, GNUNET_DISK_PIPE_END_READ);
1053 childpipe_write = 1052 childpipe_write =
1054 GNUNET_DISK_pipe_detach_end (childpipe, GNUNET_DISK_PIPE_END_WRITE); 1053 GNUNET_DISK_pipe_detach_end(childpipe, GNUNET_DISK_PIPE_END_WRITE);
1055 GNUNET_DISK_pipe_close (childpipe); 1054 GNUNET_DISK_pipe_close(childpipe);
1056 if ((NULL == childpipe_read) || (NULL == childpipe_write) || 1055 if ((NULL == childpipe_read) || (NULL == childpipe_write) ||
1057 (GNUNET_OK != GNUNET_DISK_internal_file_handle_ (childpipe_read, 1056 (GNUNET_OK != GNUNET_DISK_internal_file_handle_(childpipe_read,
1058 &childpipe_read_handle, 1057 &childpipe_read_handle,
1059 sizeof (HANDLE)))) 1058 sizeof(HANDLE))))
1060 { 1059 {
1061 if (childpipe_read) 1060 if (childpipe_read)
1062 GNUNET_DISK_file_close (childpipe_read); 1061 GNUNET_DISK_file_close(childpipe_read);
1063 if (childpipe_write) 1062 if (childpipe_write)
1064 GNUNET_DISK_file_close (childpipe_write); 1063 GNUNET_DISK_file_close(childpipe_write);
1065 GNUNET_free (cmd); 1064 GNUNET_free(cmd);
1066 return NULL; 1065 return NULL;
1066 }
1067 /* Unlike *nix variant, we don't dup the handle, so can't close
1068 * filehandle right now.
1069 */
1070 SetHandleInformation(childpipe_read_handle, HANDLE_FLAG_INHERIT, 1);
1067 } 1071 }
1068 /* Unlike *nix variant, we don't dup the handle, so can't close
1069 * filehandle right now.
1070 */
1071 SetHandleInformation (childpipe_read_handle, HANDLE_FLAG_INHERIT, 1);
1072 }
1073 else 1072 else
1074 { 1073 {
1075 childpipe_read = NULL; 1074 childpipe_read = NULL;
1076 childpipe_write = NULL; 1075 childpipe_write = NULL;
1077 } 1076 }
1078 1077
1079 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET) 1078 if (lsocks != NULL && lsocks[0] != INVALID_SOCKET)
1080 {
1081 lsocks_pipe =
1082 GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1083
1084 if (lsocks_pipe == NULL)
1085 { 1079 {
1086 GNUNET_free (cmd); 1080 lsocks_pipe =
1087 GNUNET_DISK_pipe_close (lsocks_pipe); 1081 GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
1088 if (GNUNET_YES == pipe_control) 1082
1089 { 1083 if (lsocks_pipe == NULL)
1090 GNUNET_DISK_file_close (childpipe_write); 1084 {
1091 GNUNET_DISK_file_close (childpipe_read); 1085 GNUNET_free(cmd);
1092 } 1086 GNUNET_DISK_pipe_close(lsocks_pipe);
1093 return NULL; 1087 if (GNUNET_YES == pipe_control)
1088 {
1089 GNUNET_DISK_file_close(childpipe_write);
1090 GNUNET_DISK_file_close(childpipe_read);
1091 }
1092 return NULL;
1093 }
1094 lsocks_write_fd =
1095 GNUNET_DISK_pipe_handle(lsocks_pipe, GNUNET_DISK_PIPE_END_WRITE);
1096 GNUNET_DISK_internal_file_handle_(lsocks_write_fd,
1097 &lsocks_write,
1098 sizeof(HANDLE));
1099 GNUNET_DISK_internal_file_handle_(
1100 GNUNET_DISK_pipe_handle(lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1101 &lsocks_read,
1102 sizeof(HANDLE));
1094 } 1103 }
1095 lsocks_write_fd =
1096 GNUNET_DISK_pipe_handle (lsocks_pipe, GNUNET_DISK_PIPE_END_WRITE);
1097 GNUNET_DISK_internal_file_handle_ (lsocks_write_fd,
1098 &lsocks_write,
1099 sizeof (HANDLE));
1100 GNUNET_DISK_internal_file_handle_ (
1101 GNUNET_DISK_pipe_handle (lsocks_pipe, GNUNET_DISK_PIPE_END_READ),
1102 &lsocks_read,
1103 sizeof (HANDLE));
1104 }
1105 else 1104 else
1106 { 1105 {
1107 lsocks_pipe = NULL; 1106 lsocks_pipe = NULL;
1108 lsocks_write_fd = NULL; 1107 lsocks_write_fd = NULL;
1109 } 1108 }
1110 1109
1111 env_off = 0; 1110 env_off = 0;
1112 if (GNUNET_YES == pipe_control) 1111 if (GNUNET_YES == pipe_control)
1113 { 1112 {
1114 GNUNET_asprintf (&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE); 1113 GNUNET_asprintf(&our_env[env_off++], "%s=", GNUNET_OS_CONTROL_PIPE);
1115 GNUNET_asprintf (&our_env[env_off++], "%p", childpipe_read_handle); 1114 GNUNET_asprintf(&our_env[env_off++], "%p", childpipe_read_handle);
1116 } 1115 }
1117 if ((lsocks != NULL) && (lsocks[0] != INVALID_SOCKET)) 1116 if ((lsocks != NULL) && (lsocks[0] != INVALID_SOCKET))
1118 { 1117 {
1119 /*This will tell the child that we're going to send lsocks over the pipe*/ 1118 /*This will tell the child that we're going to send lsocks over the pipe*/
1120 GNUNET_asprintf (&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS"); 1119 GNUNET_asprintf(&our_env[env_off++], "%s=", "GNUNET_OS_READ_LSOCKS");
1121 GNUNET_asprintf (&our_env[env_off++], "%lu", lsocks_read); 1120 GNUNET_asprintf(&our_env[env_off++], "%lu", lsocks_read);
1122 } 1121 }
1123 our_env[env_off++] = NULL; 1122 our_env[env_off++] = NULL;
1124 env_block = CreateCustomEnvTable (our_env); 1123 env_block = CreateCustomEnvTable(our_env);
1125 while (0 > env_off) 1124 while (0 > env_off)
1126 GNUNET_free_non_null (our_env[--env_off]); 1125 GNUNET_free_non_null(our_env[--env_off]);
1127 1126
1128 wpath_len = 0; 1127 wpath_len = 0;
1129 if (NULL == 1128 if (NULL ==
1130 (wpath = 1129 (wpath =
1131 u8_to_u16 ((uint8_t *) path, 1 + strlen (path), NULL, &wpath_len))) 1130 u8_to_u16((uint8_t *)path, 1 + strlen(path), NULL, &wpath_len)))
1132 { 1131 {
1133 LOG (GNUNET_ERROR_TYPE_DEBUG, 1132 LOG(GNUNET_ERROR_TYPE_DEBUG,
1134 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", 1133 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n",
1135 path, 1134 path,
1136 errno); 1135 errno);
1137 GNUNET_free (env_block); 1136 GNUNET_free(env_block);
1138 GNUNET_free (cmd); 1137 GNUNET_free(cmd);
1139 if (lsocks_pipe) 1138 if (lsocks_pipe)
1140 GNUNET_DISK_pipe_close (lsocks_pipe); 1139 GNUNET_DISK_pipe_close(lsocks_pipe);
1141 if (GNUNET_YES == pipe_control) 1140 if (GNUNET_YES == pipe_control)
1142 { 1141 {
1143 GNUNET_DISK_file_close (childpipe_write); 1142 GNUNET_DISK_file_close(childpipe_write);
1144 GNUNET_DISK_file_close (childpipe_read); 1143 GNUNET_DISK_file_close(childpipe_read);
1144 }
1145 return NULL;
1145 } 1146 }
1146 return NULL;
1147 }
1148 1147
1149 wcmd_len = 0; 1148 wcmd_len = 0;
1150 if (NULL == 1149 if (NULL ==
1151 (wcmd = u8_to_u16 ((uint8_t *) cmd, 1 + strlen (cmd), NULL, &wcmd_len))) 1150 (wcmd = u8_to_u16((uint8_t *)cmd, 1 + strlen(cmd), NULL, &wcmd_len)))
1152 { 1151 {
1153 LOG (GNUNET_ERROR_TYPE_DEBUG, 1152 LOG(GNUNET_ERROR_TYPE_DEBUG,
1154 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n", 1153 "Failed to convert `%s' from UTF-8 to UTF-16: %d\n",
1155 cmd, 1154 cmd,
1156 errno); 1155 errno);
1157 GNUNET_free (env_block); 1156 GNUNET_free(env_block);
1158 GNUNET_free (cmd); 1157 GNUNET_free(cmd);
1159 free (wpath); 1158 free(wpath);
1160 if (lsocks_pipe) 1159 if (lsocks_pipe)
1161 GNUNET_DISK_pipe_close (lsocks_pipe); 1160 GNUNET_DISK_pipe_close(lsocks_pipe);
1162 if (GNUNET_YES == pipe_control) 1161 if (GNUNET_YES == pipe_control)
1163 { 1162 {
1164 GNUNET_DISK_file_close (childpipe_write); 1163 GNUNET_DISK_file_close(childpipe_write);
1165 GNUNET_DISK_file_close (childpipe_read); 1164 GNUNET_DISK_file_close(childpipe_read);
1165 }
1166 return NULL;
1166 } 1167 }
1167 return NULL;
1168 }
1169 1168
1170 create_no_window = 0; 1169 create_no_window = 0;
1171 { 1170 {
1172 HANDLE console_input = CreateFile ("CONIN$", 1171 HANDLE console_input = CreateFile("CONIN$",
1173 GENERIC_READ, 1172 GENERIC_READ,
1174 FILE_SHARE_READ | FILE_SHARE_WRITE, 1173 FILE_SHARE_READ | FILE_SHARE_WRITE,
1175 NULL, 1174 NULL,
1176 OPEN_EXISTING, 1175 OPEN_EXISTING,
1177 0, 1176 0,
1178 NULL); 1177 NULL);
1179 if (INVALID_HANDLE_VALUE == console_input) 1178 if (INVALID_HANDLE_VALUE == console_input)
1180 create_no_window = CREATE_NO_WINDOW; 1179 create_no_window = CREATE_NO_WINDOW;
1181 else 1180 else
1182 CloseHandle (console_input); 1181 CloseHandle(console_input);
1183 } 1182 }
1184 1183
1185 bresult = CreateProcessW (wpath, 1184 bresult = CreateProcessW(wpath,
1186 wcmd, 1185 wcmd,
1187 NULL, 1186 NULL,
1188 NULL, 1187 NULL,
1189 GNUNET_YES, 1188 GNUNET_YES,
1190 create_no_window | CREATE_SUSPENDED, 1189 create_no_window | CREATE_SUSPENDED,
1191 env_block, 1190 env_block,
1192 NULL, 1191 NULL,
1193 &start, 1192 &start,
1194 &proc); 1193 &proc);
1195 error_code = GetLastError (); 1194 error_code = GetLastError();
1196 1195
1197 if ((NULL == pipe_stdin) && (stdih)) 1196 if ((NULL == pipe_stdin) && (stdih))
1198 SetHandleInformation (stdih, HANDLE_FLAG_INHERIT, stdif); 1197 SetHandleInformation(stdih, HANDLE_FLAG_INHERIT, stdif);
1199 1198
1200 1199
1201 if ((NULL == pipe_stdout) && (stdoh)) 1200 if ((NULL == pipe_stdout) && (stdoh))
1202 SetHandleInformation (stdoh, HANDLE_FLAG_INHERIT, stdof); 1201 SetHandleInformation(stdoh, HANDLE_FLAG_INHERIT, stdof);
1203 1202
1204 if (stdeh) 1203 if (stdeh)
1205 SetHandleInformation (stdeh, HANDLE_FLAG_INHERIT, stdef); 1204 SetHandleInformation(stdeh, HANDLE_FLAG_INHERIT, stdef);
1206 1205
1207 if (! bresult) 1206 if (!bresult)
1208 LOG (GNUNET_ERROR_TYPE_ERROR, 1207 LOG(GNUNET_ERROR_TYPE_ERROR,
1209 "CreateProcess(%s, %s) failed: %lu\n", 1208 "CreateProcess(%s, %s) failed: %lu\n",
1210 path, 1209 path,
1211 cmd, 1210 cmd,
1212 error_code); 1211 error_code);
1213 1212
1214 GNUNET_free (env_block); 1213 GNUNET_free(env_block);
1215 GNUNET_free (cmd); 1214 GNUNET_free(cmd);
1216 free (wpath); 1215 free(wpath);
1217 free (wcmd); 1216 free(wcmd);
1218 if (GNUNET_YES == pipe_control) 1217 if (GNUNET_YES == pipe_control)
1219 { 1218 {
1220 GNUNET_DISK_file_close (childpipe_read); 1219 GNUNET_DISK_file_close(childpipe_read);
1221 } 1220 }
1222 1221
1223 if (! bresult) 1222 if (!bresult)
1224 {
1225 if (GNUNET_YES == pipe_control)
1226 { 1223 {
1227 GNUNET_DISK_file_close (childpipe_write); 1224 if (GNUNET_YES == pipe_control)
1225 {
1226 GNUNET_DISK_file_close(childpipe_write);
1227 }
1228 if (NULL != lsocks)
1229 GNUNET_DISK_pipe_close(lsocks_pipe);
1230 SetErrnoFromWinError(error_code);
1231 return NULL;
1228 } 1232 }
1229 if (NULL != lsocks)
1230 GNUNET_DISK_pipe_close (lsocks_pipe);
1231 SetErrnoFromWinError (error_code);
1232 return NULL;
1233 }
1234 1233
1235 gnunet_proc = GNUNET_new (struct GNUNET_OS_Process); 1234 gnunet_proc = GNUNET_new(struct GNUNET_OS_Process);
1236 gnunet_proc->pid = proc.dwProcessId; 1235 gnunet_proc->pid = proc.dwProcessId;
1237 gnunet_proc->handle = proc.hProcess; 1236 gnunet_proc->handle = proc.hProcess;
1238 gnunet_proc->control_pipe = childpipe_write; 1237 gnunet_proc->control_pipe = childpipe_write;
1239 1238
1240 CreateThread (NULL, 64000, &child_wait_thread, (void *) gnunet_proc, 0, NULL); 1239 CreateThread(NULL, 64000, &child_wait_thread, (void *)gnunet_proc, 0, NULL);
1241 1240
1242 ResumeThread (proc.hThread); 1241 ResumeThread(proc.hThread);
1243 CloseHandle (proc.hThread); 1242 CloseHandle(proc.hThread);
1244 1243
1245 if ((NULL == lsocks) || (INVALID_SOCKET == lsocks[0])) 1244 if ((NULL == lsocks) || (INVALID_SOCKET == lsocks[0]))
1246 return gnunet_proc; 1245 return gnunet_proc;
1247 1246
1248 GNUNET_DISK_pipe_close_end (lsocks_pipe, GNUNET_DISK_PIPE_END_READ); 1247 GNUNET_DISK_pipe_close_end(lsocks_pipe, GNUNET_DISK_PIPE_END_READ);
1249 1248
1250 /* This is a replacement for "goto error" that doesn't use goto */ 1249 /* This is a replacement for "goto error" that doesn't use goto */
1251 fail = 1; 1250 fail = 1;
1252 do 1251 do
1253 { 1252 {
1254 ssize_t wrote; 1253 ssize_t wrote;
1255 uint64_t size; 1254 uint64_t size;
1256 uint64_t count; 1255 uint64_t count;
1257 unsigned int i; 1256 unsigned int i;
1258 1257
1259 /* Tell the number of sockets */ 1258 /* Tell the number of sockets */
1260 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++) 1259 for (count = 0; lsocks && lsocks[count] != INVALID_SOCKET; count++)
1261 ; 1260 ;
1262 1261
1263 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count)); 1262 wrote = GNUNET_DISK_file_write(lsocks_write_fd, &count, sizeof(count));
1264 if (sizeof (count) != wrote) 1263 if (sizeof(count) != wrote)
1265 { 1264 {
1266 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 1265 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1267 "Failed to write %u count bytes to the child: %lu\n", 1266 "Failed to write %u count bytes to the child: %lu\n",
1268 sizeof (count), 1267 sizeof(count),
1269 GetLastError ()); 1268 GetLastError());
1270 break; 1269 break;
1271 } 1270 }
1272 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++) 1271 for (i = 0; lsocks && lsocks[i] != INVALID_SOCKET; i++)
1273 { 1272 {
1274 WSAPROTOCOL_INFOA pi; 1273 WSAPROTOCOL_INFOA pi;
1275 /* Get a socket duplication info */ 1274 /* Get a socket duplication info */
1276 if (SOCKET_ERROR == 1275 if (SOCKET_ERROR ==
1277 WSADuplicateSocketA (lsocks[i], gnunet_proc->pid, &pi)) 1276 WSADuplicateSocketA(lsocks[i], gnunet_proc->pid, &pi))
1278 { 1277 {
1279 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 1278 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1280 "Failed to duplicate an socket[%u]: %lu\n", 1279 "Failed to duplicate an socket[%u]: %lu\n",
1281 i, 1280 i,
1282 GetLastError ()); 1281 GetLastError());
1283 break; 1282 break;
1284 } 1283 }
1285 /* Synchronous I/O is not nice, but we can't schedule this: 1284 /* Synchronous I/O is not nice, but we can't schedule this:
1286 * lsocks will be closed/freed by the caller soon, and until 1285 * lsocks will be closed/freed by the caller soon, and until
1287 * the child creates a duplicate, closing a socket here will 1286 * the child creates a duplicate, closing a socket here will
1288 * close it for good. 1287 * close it for good.
1289 */ 1288 */
1290 /* Send the size of the structure 1289 /* Send the size of the structure
1291 * (the child might be built with different headers...) 1290 * (the child might be built with different headers...)
1291 */
1292 size = sizeof(pi);
1293 wrote = GNUNET_DISK_file_write(lsocks_write_fd, &size, sizeof(size));
1294 if (sizeof(size) != wrote)
1295 {
1296 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1297 "Failed to write %u size[%u] bytes to the child: %lu\n",
1298 sizeof(size),
1299 i,
1300 GetLastError());
1301 break;
1302 }
1303 /* Finally! Send the data */
1304 wrote = GNUNET_DISK_file_write(lsocks_write_fd, &pi, sizeof(pi));
1305 if (sizeof(pi) != wrote)
1306 {
1307 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
1308 "Failed to write %u socket[%u] bytes to the child: %lu\n",
1309 sizeof(pi),
1310 i,
1311 GetLastError());
1312 break;
1313 }
1314 }
1315 /* This will block us until the child makes a final read or closes
1316 * the pipe (hence no 'wrote' check), since we have to wait for it
1317 * to duplicate the last socket, before we return and start closing
1318 * our own copies)
1292 */ 1319 */
1293 size = sizeof (pi); 1320 wrote = GNUNET_DISK_file_write(lsocks_write_fd, &count, sizeof(count));
1294 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &size, sizeof (size)); 1321 fail = 0;
1295 if (sizeof (size) != wrote)
1296 {
1297 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1298 "Failed to write %u size[%u] bytes to the child: %lu\n",
1299 sizeof (size),
1300 i,
1301 GetLastError ());
1302 break;
1303 }
1304 /* Finally! Send the data */
1305 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &pi, sizeof (pi));
1306 if (sizeof (pi) != wrote)
1307 {
1308 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
1309 "Failed to write %u socket[%u] bytes to the child: %lu\n",
1310 sizeof (pi),
1311 i,
1312 GetLastError ());
1313 break;
1314 }
1315 } 1322 }
1316 /* This will block us until the child makes a final read or closes 1323 while (fail);
1317 * the pipe (hence no 'wrote' check), since we have to wait for it
1318 * to duplicate the last socket, before we return and start closing
1319 * our own copies)
1320 */
1321 wrote = GNUNET_DISK_file_write (lsocks_write_fd, &count, sizeof (count));
1322 fail = 0;
1323 } while (fail);
1324 1324
1325 GNUNET_DISK_file_sync (lsocks_write_fd); 1325 GNUNET_DISK_file_sync(lsocks_write_fd);
1326 GNUNET_DISK_pipe_close (lsocks_pipe); 1326 GNUNET_DISK_pipe_close(lsocks_pipe);
1327 1327
1328 if (fail) 1328 if (fail)
1329 { 1329 {
1330 /* If we can't pass on the socket(s), the child will block forever, 1330 /* If we can't pass on the socket(s), the child will block forever,
1331 * better put it out of its misery. 1331 * better put it out of its misery.
1332 */ 1332 */
1333 SafeTerminateProcess (gnunet_proc->handle, 0, 0); 1333 SafeTerminateProcess(gnunet_proc->handle, 0, 0);
1334 CloseHandle (gnunet_proc->handle); 1334 CloseHandle(gnunet_proc->handle);
1335 if (NULL != gnunet_proc->control_pipe) 1335 if (NULL != gnunet_proc->control_pipe)
1336 GNUNET_DISK_file_close (gnunet_proc->control_pipe); 1336 GNUNET_DISK_file_close(gnunet_proc->control_pipe);
1337 GNUNET_free (gnunet_proc); 1337 GNUNET_free(gnunet_proc);
1338 return NULL; 1338 return NULL;
1339 } 1339 }
1340 return gnunet_proc; 1340 return gnunet_proc;
1341#endif 1341#endif
1342} 1342}
@@ -1355,22 +1355,22 @@ start_process (int pipe_control,
1355 * @return pointer to process structure of the new process, NULL on error 1355 * @return pointer to process structure of the new process, NULL on error
1356 */ 1356 */
1357struct GNUNET_OS_Process * 1357struct GNUNET_OS_Process *
1358GNUNET_OS_start_process_vap (int pipe_control, 1358GNUNET_OS_start_process_vap(int pipe_control,
1359 enum GNUNET_OS_InheritStdioFlags std_inheritance, 1359 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1360 struct GNUNET_DISK_PipeHandle *pipe_stdin, 1360 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1361 struct GNUNET_DISK_PipeHandle *pipe_stdout, 1361 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1362 struct GNUNET_DISK_PipeHandle *pipe_stderr, 1362 struct GNUNET_DISK_PipeHandle *pipe_stderr,
1363 const char *filename, 1363 const char *filename,
1364 char *const argv[]) 1364 char *const argv[])
1365{ 1365{
1366 return start_process (pipe_control, 1366 return start_process(pipe_control,
1367 std_inheritance, 1367 std_inheritance,
1368 pipe_stdin, 1368 pipe_stdin,
1369 pipe_stdout, 1369 pipe_stdout,
1370 pipe_stderr, 1370 pipe_stderr,
1371 NULL, 1371 NULL,
1372 filename, 1372 filename,
1373 argv); 1373 argv);
1374} 1374}
1375 1375
1376 1376
@@ -1387,13 +1387,13 @@ GNUNET_OS_start_process_vap (int pipe_control,
1387 * @return pointer to process structure of the new process, NULL on error 1387 * @return pointer to process structure of the new process, NULL on error
1388 */ 1388 */
1389struct GNUNET_OS_Process * 1389struct GNUNET_OS_Process *
1390GNUNET_OS_start_process_va (int pipe_control, 1390GNUNET_OS_start_process_va(int pipe_control,
1391 enum GNUNET_OS_InheritStdioFlags std_inheritance, 1391 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1392 struct GNUNET_DISK_PipeHandle *pipe_stdin, 1392 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1393 struct GNUNET_DISK_PipeHandle *pipe_stdout, 1393 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1394 struct GNUNET_DISK_PipeHandle *pipe_stderr, 1394 struct GNUNET_DISK_PipeHandle *pipe_stderr,
1395 const char *filename, 1395 const char *filename,
1396 va_list va) 1396 va_list va)
1397{ 1397{
1398 struct GNUNET_OS_Process *ret; 1398 struct GNUNET_OS_Process *ret;
1399 va_list ap; 1399 va_list ap;
@@ -1401,24 +1401,24 @@ GNUNET_OS_start_process_va (int pipe_control,
1401 int argc; 1401 int argc;
1402 1402
1403 argc = 0; 1403 argc = 0;
1404 va_copy (ap, va); 1404 va_copy(ap, va);
1405 while (NULL != va_arg (ap, char *)) 1405 while (NULL != va_arg(ap, char *))
1406 argc++; 1406 argc++;
1407 va_end (ap); 1407 va_end(ap);
1408 argv = GNUNET_malloc (sizeof (char *) * (argc + 1)); 1408 argv = GNUNET_malloc(sizeof(char *) * (argc + 1));
1409 argc = 0; 1409 argc = 0;
1410 va_copy (ap, va); 1410 va_copy(ap, va);
1411 while (NULL != (argv[argc] = va_arg (ap, char *))) 1411 while (NULL != (argv[argc] = va_arg(ap, char *)))
1412 argc++; 1412 argc++;
1413 va_end (ap); 1413 va_end(ap);
1414 ret = GNUNET_OS_start_process_vap (pipe_control, 1414 ret = GNUNET_OS_start_process_vap(pipe_control,
1415 std_inheritance, 1415 std_inheritance,
1416 pipe_stdin, 1416 pipe_stdin,
1417 pipe_stdout, 1417 pipe_stdout,
1418 pipe_stderr, 1418 pipe_stderr,
1419 filename, 1419 filename,
1420 argv); 1420 argv);
1421 GNUNET_free (argv); 1421 GNUNET_free(argv);
1422 return ret; 1422 return ret;
1423} 1423}
1424 1424
@@ -1435,26 +1435,26 @@ GNUNET_OS_start_process_va (int pipe_control,
1435 * @return pointer to process structure of the new process, NULL on error 1435 * @return pointer to process structure of the new process, NULL on error
1436 */ 1436 */
1437struct GNUNET_OS_Process * 1437struct GNUNET_OS_Process *
1438GNUNET_OS_start_process (int pipe_control, 1438GNUNET_OS_start_process(int pipe_control,
1439 enum GNUNET_OS_InheritStdioFlags std_inheritance, 1439 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1440 struct GNUNET_DISK_PipeHandle *pipe_stdin, 1440 struct GNUNET_DISK_PipeHandle *pipe_stdin,
1441 struct GNUNET_DISK_PipeHandle *pipe_stdout, 1441 struct GNUNET_DISK_PipeHandle *pipe_stdout,
1442 struct GNUNET_DISK_PipeHandle *pipe_stderr, 1442 struct GNUNET_DISK_PipeHandle *pipe_stderr,
1443 const char *filename, 1443 const char *filename,
1444 ...) 1444 ...)
1445{ 1445{
1446 struct GNUNET_OS_Process *ret; 1446 struct GNUNET_OS_Process *ret;
1447 va_list ap; 1447 va_list ap;
1448 1448
1449 va_start (ap, filename); 1449 va_start(ap, filename);
1450 ret = GNUNET_OS_start_process_va (pipe_control, 1450 ret = GNUNET_OS_start_process_va(pipe_control,
1451 std_inheritance, 1451 std_inheritance,
1452 pipe_stdin, 1452 pipe_stdin,
1453 pipe_stdout, 1453 pipe_stdout,
1454 pipe_stderr, 1454 pipe_stderr,
1455 filename, 1455 filename,
1456 ap); 1456 ap);
1457 va_end (ap); 1457 va_end(ap);
1458 return ret; 1458 return ret;
1459} 1459}
1460 1460
@@ -1474,20 +1474,20 @@ GNUNET_OS_start_process (int pipe_control,
1474 * @return process ID of the new process, -1 on error 1474 * @return process ID of the new process, -1 on error
1475 */ 1475 */
1476struct GNUNET_OS_Process * 1476struct GNUNET_OS_Process *
1477GNUNET_OS_start_process_v (int pipe_control, 1477GNUNET_OS_start_process_v(int pipe_control,
1478 enum GNUNET_OS_InheritStdioFlags std_inheritance, 1478 enum GNUNET_OS_InheritStdioFlags std_inheritance,
1479 const SOCKTYPE *lsocks, 1479 const SOCKTYPE *lsocks,
1480 const char *filename, 1480 const char *filename,
1481 char *const argv[]) 1481 char *const argv[])
1482{ 1482{
1483 return start_process (pipe_control, 1483 return start_process(pipe_control,
1484 std_inheritance, 1484 std_inheritance,
1485 NULL, 1485 NULL,
1486 NULL, 1486 NULL,
1487 NULL, 1487 NULL,
1488 lsocks, 1488 lsocks,
1489 filename, 1489 filename,
1490 argv); 1490 argv);
1491} 1491}
1492 1492
1493 1493
@@ -1510,11 +1510,11 @@ GNUNET_OS_start_process_v (int pipe_control,
1510 * @return pointer to process structure of the new process, NULL on error 1510 * @return pointer to process structure of the new process, NULL on error
1511 */ 1511 */
1512struct GNUNET_OS_Process * 1512struct GNUNET_OS_Process *
1513GNUNET_OS_start_process_s (int pipe_control, 1513GNUNET_OS_start_process_s(int pipe_control,
1514 unsigned int std_inheritance, 1514 unsigned int std_inheritance,
1515 const SOCKTYPE *lsocks, 1515 const SOCKTYPE *lsocks,
1516 const char *filename, 1516 const char *filename,
1517 ...) 1517 ...)
1518{ 1518{
1519 va_list ap; 1519 va_list ap;
1520 char **argv; 1520 char **argv;
@@ -1531,101 +1531,103 @@ GNUNET_OS_start_process_s (int pipe_control,
1531 size_t len; 1531 size_t len;
1532 1532
1533 argv_size = 1; 1533 argv_size = 1;
1534 va_start (ap, filename); 1534 va_start(ap, filename);
1535 arg = filename; 1535 arg = filename;
1536 last = NULL; 1536 last = NULL;
1537 do 1537 do
1538 {
1539 rpos = arg;
1540 quote_on = 0;
1541 while ('\0' != *rpos)
1542 { 1538 {
1543 if ('"' == *rpos) 1539 rpos = arg;
1544 { 1540 quote_on = 0;
1545 if (1 == quote_on) 1541 while ('\0' != *rpos)
1546 quote_on = 0; 1542 {
1547 else 1543 if ('"' == *rpos)
1548 quote_on = 1; 1544 {
1549 } 1545 if (1 == quote_on)
1550 if ((' ' == *rpos) && (0 == quote_on)) 1546 quote_on = 0;
1551 { 1547 else
1552 if (NULL != last) 1548 quote_on = 1;
1553 argv_size++; 1549 }
1554 last = NULL; 1550 if ((' ' == *rpos) && (0 == quote_on))
1555 rpos++; 1551 {
1556 while (' ' == *rpos) 1552 if (NULL != last)
1557 rpos++; 1553 argv_size++;
1558 } 1554 last = NULL;
1559 if ((NULL == last) && ('\0' != *rpos)) // FIXME: == or !=? 1555 rpos++;
1560 last = rpos; 1556 while (' ' == *rpos)
1561 if ('\0' != *rpos) 1557 rpos++;
1562 rpos++; 1558 }
1559 if ((NULL == last) && ('\0' != *rpos)) // FIXME: == or !=?
1560 last = rpos;
1561 if ('\0' != *rpos)
1562 rpos++;
1563 }
1564 if (NULL != last)
1565 argv_size++;
1563 } 1566 }
1564 if (NULL != last) 1567 while (NULL != (arg = (va_arg(ap, const char *))));
1565 argv_size++; 1568 va_end(ap);
1566 } while (NULL != (arg = (va_arg (ap, const char *))));
1567 va_end (ap);
1568 1569
1569 argv = GNUNET_malloc (argv_size * sizeof (char *)); 1570 argv = GNUNET_malloc(argv_size * sizeof(char *));
1570 argv_size = 0; 1571 argv_size = 0;
1571 va_start (ap, filename); 1572 va_start(ap, filename);
1572 arg = filename; 1573 arg = filename;
1573 last = NULL; 1574 last = NULL;
1574 do 1575 do
1575 {
1576 cp = GNUNET_strdup (arg);
1577 quote_on = 0;
1578 pos = cp;
1579 while ('\0' != *pos)
1580 { 1576 {
1581 if ('"' == *pos) 1577 cp = GNUNET_strdup(arg);
1582 { 1578 quote_on = 0;
1583 if (1 == quote_on) 1579 pos = cp;
1584 quote_on = 0; 1580 while ('\0' != *pos)
1585 else 1581 {
1586 quote_on = 1; 1582 if ('"' == *pos)
1587 } 1583 {
1588 if ((' ' == *pos) && (0 == quote_on)) 1584 if (1 == quote_on)
1589 { 1585 quote_on = 0;
1590 *pos = '\0'; 1586 else
1591 if (NULL != last) 1587 quote_on = 1;
1592 argv[argv_size++] = GNUNET_strdup (last); 1588 }
1593 last = NULL; 1589 if ((' ' == *pos) && (0 == quote_on))
1594 pos++; 1590 {
1595 while (' ' == *pos) 1591 *pos = '\0';
1596 pos++; 1592 if (NULL != last)
1597 } 1593 argv[argv_size++] = GNUNET_strdup(last);
1598 if ((NULL == last) && ('\0' != *pos)) // FIXME: == or !=? 1594 last = NULL;
1599 last = pos; 1595 pos++;
1600 if ('\0' != *pos) 1596 while (' ' == *pos)
1601 pos++; 1597 pos++;
1602 } 1598 }
1603 if (NULL != last) 1599 if ((NULL == last) && ('\0' != *pos)) // FIXME: == or !=?
1604 argv[argv_size++] = GNUNET_strdup (last); 1600 last = pos;
1605 last = NULL; 1601 if ('\0' != *pos)
1606 GNUNET_free (cp); 1602 pos++;
1607 } while (NULL != (arg = (va_arg (ap, const char *)))); 1603 }
1608 va_end (ap); 1604 if (NULL != last)
1605 argv[argv_size++] = GNUNET_strdup(last);
1606 last = NULL;
1607 GNUNET_free(cp);
1608 }
1609 while (NULL != (arg = (va_arg(ap, const char *))));
1610 va_end(ap);
1609 argv[argv_size] = NULL; 1611 argv[argv_size] = NULL;
1610 1612
1611 for (i = 0; i < argv_size; i++) 1613 for (i = 0; i < argv_size; i++)
1612 {
1613 len = strlen (argv[i]);
1614 if ((argv[i][0] == '"') && (argv[i][len - 1] == '"'))
1615 { 1614 {
1616 memmove (&argv[i][0], &argv[i][1], len - 2); 1615 len = strlen(argv[i]);
1617 argv[i][len - 2] = '\0'; 1616 if ((argv[i][0] == '"') && (argv[i][len - 1] == '"'))
1617 {
1618 memmove(&argv[i][0], &argv[i][1], len - 2);
1619 argv[i][len - 2] = '\0';
1620 }
1618 } 1621 }
1619 }
1620 binary_path = argv[0]; 1622 binary_path = argv[0];
1621 proc = GNUNET_OS_start_process_v (pipe_control, 1623 proc = GNUNET_OS_start_process_v(pipe_control,
1622 std_inheritance, 1624 std_inheritance,
1623 lsocks, 1625 lsocks,
1624 binary_path, 1626 binary_path,
1625 argv); 1627 argv);
1626 while (argv_size > 0) 1628 while (argv_size > 0)
1627 GNUNET_free (argv[--argv_size]); 1629 GNUNET_free(argv[--argv_size]);
1628 GNUNET_free (argv); 1630 GNUNET_free(argv);
1629 return proc; 1631 return proc;
1630} 1632}
1631 1633
@@ -1641,60 +1643,60 @@ GNUNET_OS_start_process_s (int pipe_control,
1641 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise 1643 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise
1642 */ 1644 */
1643static int 1645static int
1644process_status (struct GNUNET_OS_Process *proc, 1646process_status(struct GNUNET_OS_Process *proc,
1645 enum GNUNET_OS_ProcessStatusType *type, 1647 enum GNUNET_OS_ProcessStatusType *type,
1646 unsigned long *code, 1648 unsigned long *code,
1647 int options) 1649 int options)
1648{ 1650{
1649#ifndef MINGW 1651#ifndef MINGW
1650 int status; 1652 int status;
1651 int ret; 1653 int ret;
1652 1654
1653 GNUNET_assert (0 != proc); 1655 GNUNET_assert(0 != proc);
1654 ret = waitpid (proc->pid, &status, options); 1656 ret = waitpid(proc->pid, &status, options);
1655 if (ret < 0) 1657 if (ret < 0)
1656 { 1658 {
1657 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid"); 1659 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "waitpid");
1658 return GNUNET_SYSERR; 1660 return GNUNET_SYSERR;
1659 } 1661 }
1660 if (0 == ret) 1662 if (0 == ret)
1661 { 1663 {
1662 *type = GNUNET_OS_PROCESS_RUNNING; 1664 *type = GNUNET_OS_PROCESS_RUNNING;
1663 *code = 0; 1665 *code = 0;
1664 return GNUNET_NO; 1666 return GNUNET_NO;
1665 } 1667 }
1666 if (proc->pid != ret) 1668 if (proc->pid != ret)
1667 { 1669 {
1668 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid"); 1670 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "waitpid");
1669 return GNUNET_SYSERR; 1671 return GNUNET_SYSERR;
1670 } 1672 }
1671 if (WIFEXITED (status)) 1673 if (WIFEXITED(status))
1672 { 1674 {
1673 *type = GNUNET_OS_PROCESS_EXITED; 1675 *type = GNUNET_OS_PROCESS_EXITED;
1674 *code = WEXITSTATUS (status); 1676 *code = WEXITSTATUS(status);
1675 } 1677 }
1676 else if (WIFSIGNALED (status)) 1678 else if (WIFSIGNALED(status))
1677 { 1679 {
1678 *type = GNUNET_OS_PROCESS_SIGNALED; 1680 *type = GNUNET_OS_PROCESS_SIGNALED;
1679 *code = WTERMSIG (status); 1681 *code = WTERMSIG(status);
1680 } 1682 }
1681 else if (WIFSTOPPED (status)) 1683 else if (WIFSTOPPED(status))
1682 { 1684 {
1683 *type = GNUNET_OS_PROCESS_SIGNALED; 1685 *type = GNUNET_OS_PROCESS_SIGNALED;
1684 *code = WSTOPSIG (status); 1686 *code = WSTOPSIG(status);
1685 } 1687 }
1686#ifdef WIFCONTINUED 1688#ifdef WIFCONTINUED
1687 else if (WIFCONTINUED (status)) 1689 else if (WIFCONTINUED(status))
1688 { 1690 {
1689 *type = GNUNET_OS_PROCESS_RUNNING; 1691 *type = GNUNET_OS_PROCESS_RUNNING;
1690 *code = 0; 1692 *code = 0;
1691 } 1693 }
1692#endif 1694#endif
1693 else 1695 else
1694 { 1696 {
1695 *type = GNUNET_OS_PROCESS_UNKNOWN; 1697 *type = GNUNET_OS_PROCESS_UNKNOWN;
1696 *code = 0; 1698 *code = 0;
1697 } 1699 }
1698#else 1700#else
1699#ifndef WNOHANG 1701#ifndef WNOHANG
1700#define WNOHANG 42 /* just a flag for W32, purely internal at this point */ 1702#define WNOHANG 42 /* just a flag for W32, purely internal at this point */
@@ -1706,39 +1708,39 @@ process_status (struct GNUNET_OS_Process *proc,
1706 h = proc->handle; 1708 h = proc->handle;
1707 ret = proc->pid; 1709 ret = proc->pid;
1708 if (h == NULL || ret == 0) 1710 if (h == NULL || ret == 0)
1709 { 1711 {
1710 LOG (GNUNET_ERROR_TYPE_WARNING, 1712 LOG(GNUNET_ERROR_TYPE_WARNING,
1711 "Invalid process information {%d, %08X}\n", 1713 "Invalid process information {%d, %08X}\n",
1712 ret, 1714 ret,
1713 h); 1715 h);
1714 return GNUNET_SYSERR; 1716 return GNUNET_SYSERR;
1715 } 1717 }
1716 if (h == NULL) 1718 if (h == NULL)
1717 h = GetCurrentProcess (); 1719 h = GetCurrentProcess();
1718 1720
1719 if (WNOHANG != options) 1721 if (WNOHANG != options)
1720 {
1721 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE))
1722 { 1722 {
1723 SetErrnoFromWinError (GetLastError ()); 1723 if (WAIT_OBJECT_0 != WaitForSingleObject(h, INFINITE))
1724 return GNUNET_SYSERR; 1724 {
1725 SetErrnoFromWinError(GetLastError());
1726 return GNUNET_SYSERR;
1727 }
1725 } 1728 }
1726 } 1729 SetLastError(0);
1727 SetLastError (0); 1730 ret = GetExitCodeProcess(h, &c);
1728 ret = GetExitCodeProcess (h, &c); 1731 error_code = GetLastError();
1729 error_code = GetLastError ();
1730 if (ret == 0 || error_code != NO_ERROR) 1732 if (ret == 0 || error_code != NO_ERROR)
1731 { 1733 {
1732 SetErrnoFromWinError (error_code); 1734 SetErrnoFromWinError(error_code);
1733 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess"); 1735 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "GetExitCodeProcess");
1734 return GNUNET_SYSERR; 1736 return GNUNET_SYSERR;
1735 } 1737 }
1736 if (STILL_ACTIVE == c) 1738 if (STILL_ACTIVE == c)
1737 { 1739 {
1738 *type = GNUNET_OS_PROCESS_RUNNING; 1740 *type = GNUNET_OS_PROCESS_RUNNING;
1739 *code = 0; 1741 *code = 0;
1740 return GNUNET_NO; 1742 return GNUNET_NO;
1741 } 1743 }
1742 *type = GNUNET_OS_PROCESS_EXITED; 1744 *type = GNUNET_OS_PROCESS_EXITED;
1743 *code = c; 1745 *code = c;
1744#endif 1746#endif
@@ -1757,11 +1759,11 @@ process_status (struct GNUNET_OS_Process *proc,
1757 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise 1759 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise
1758 */ 1760 */
1759int 1761int
1760GNUNET_OS_process_status (struct GNUNET_OS_Process *proc, 1762GNUNET_OS_process_status(struct GNUNET_OS_Process *proc,
1761 enum GNUNET_OS_ProcessStatusType *type, 1763 enum GNUNET_OS_ProcessStatusType *type,
1762 unsigned long *code) 1764 unsigned long *code)
1763{ 1765{
1764 return process_status (proc, type, code, WNOHANG); 1766 return process_status(proc, type, code, WNOHANG);
1765} 1767}
1766 1768
1767 1769
@@ -1775,11 +1777,11 @@ GNUNET_OS_process_status (struct GNUNET_OS_Process *proc,
1775 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise 1777 * @return #GNUNET_OK on success, #GNUNET_NO if the process is still running, #GNUNET_SYSERR otherwise
1776 */ 1778 */
1777int 1779int
1778GNUNET_OS_process_wait_status (struct GNUNET_OS_Process *proc, 1780GNUNET_OS_process_wait_status(struct GNUNET_OS_Process *proc,
1779 enum GNUNET_OS_ProcessStatusType *type, 1781 enum GNUNET_OS_ProcessStatusType *type,
1780 unsigned long *code) 1782 unsigned long *code)
1781{ 1783{
1782 return process_status (proc, type, code, 0); 1784 return process_status(proc, type, code, 0);
1783} 1785}
1784 1786
1785 1787
@@ -1794,40 +1796,40 @@ GNUNET_OS_process_wait_status (struct GNUNET_OS_Process *proc,
1794 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise 1796 * @return #GNUNET_OK on success, #GNUNET_SYSERR otherwise
1795 */ 1797 */
1796int 1798int
1797GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc) 1799GNUNET_OS_process_wait(struct GNUNET_OS_Process *proc)
1798{ 1800{
1799#ifndef MINGW 1801#ifndef MINGW
1800 pid_t pid = proc->pid; 1802 pid_t pid = proc->pid;
1801 pid_t ret; 1803 pid_t ret;
1802 1804
1803 while ((pid != (ret = waitpid (pid, NULL, 0))) && (EINTR == errno)) 1805 while ((pid != (ret = waitpid(pid, NULL, 0))) && (EINTR == errno))
1804 ; 1806 ;
1805 if (pid != ret) 1807 if (pid != ret)
1806 { 1808 {
1807 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "waitpid"); 1809 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "waitpid");
1808 return GNUNET_SYSERR; 1810 return GNUNET_SYSERR;
1809 } 1811 }
1810 return GNUNET_OK; 1812 return GNUNET_OK;
1811#else 1813#else
1812 HANDLE h; 1814 HANDLE h;
1813 1815
1814 h = proc->handle; 1816 h = proc->handle;
1815 if (NULL == h) 1817 if (NULL == h)
1816 { 1818 {
1817 LOG (GNUNET_ERROR_TYPE_WARNING, 1819 LOG(GNUNET_ERROR_TYPE_WARNING,
1818 "Invalid process information {%d, %08X}\n", 1820 "Invalid process information {%d, %08X}\n",
1819 proc->pid, 1821 proc->pid,
1820 h); 1822 h);
1821 return GNUNET_SYSERR; 1823 return GNUNET_SYSERR;
1822 } 1824 }
1823 if (NULL == h) 1825 if (NULL == h)
1824 h = GetCurrentProcess (); 1826 h = GetCurrentProcess();
1825 1827
1826 if (WAIT_OBJECT_0 != WaitForSingleObject (h, INFINITE)) 1828 if (WAIT_OBJECT_0 != WaitForSingleObject(h, INFINITE))
1827 { 1829 {
1828 SetErrnoFromWinError (GetLastError ()); 1830 SetErrnoFromWinError(GetLastError());
1829 return GNUNET_SYSERR; 1831 return GNUNET_SYSERR;
1830 } 1832 }
1831 return GNUNET_OK; 1833 return GNUNET_OK;
1832#endif 1834#endif
1833} 1835}
@@ -1836,9 +1838,7 @@ GNUNET_OS_process_wait (struct GNUNET_OS_Process *proc)
1836/** 1838/**
1837 * Handle to a command. 1839 * Handle to a command.
1838 */ 1840 */
1839struct GNUNET_OS_CommandHandle 1841struct GNUNET_OS_CommandHandle {
1840{
1841
1842 /** 1842 /**
1843 * Process handle. 1843 * Process handle.
1844 */ 1844 */
@@ -1894,18 +1894,18 @@ struct GNUNET_OS_CommandHandle
1894 * @param cmd handle to the process 1894 * @param cmd handle to the process
1895 */ 1895 */
1896void 1896void
1897GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd) 1897GNUNET_OS_command_stop(struct GNUNET_OS_CommandHandle *cmd)
1898{ 1898{
1899 if (NULL != cmd->proc) 1899 if (NULL != cmd->proc)
1900 { 1900 {
1901 GNUNET_assert (NULL != cmd->rtask); 1901 GNUNET_assert(NULL != cmd->rtask);
1902 GNUNET_SCHEDULER_cancel (cmd->rtask); 1902 GNUNET_SCHEDULER_cancel(cmd->rtask);
1903 } 1903 }
1904 (void) GNUNET_OS_process_kill (cmd->eip, SIGKILL); 1904 (void)GNUNET_OS_process_kill(cmd->eip, SIGKILL);
1905 GNUNET_break (GNUNET_OK == GNUNET_OS_process_wait (cmd->eip)); 1905 GNUNET_break(GNUNET_OK == GNUNET_OS_process_wait(cmd->eip));
1906 GNUNET_OS_process_destroy (cmd->eip); 1906 GNUNET_OS_process_destroy(cmd->eip);
1907 GNUNET_DISK_pipe_close (cmd->opipe); 1907 GNUNET_DISK_pipe_close(cmd->opipe);
1908 GNUNET_free (cmd); 1908 GNUNET_free(cmd);
1909} 1909}
1910 1910
1911 1911
@@ -1915,7 +1915,7 @@ GNUNET_OS_command_stop (struct GNUNET_OS_CommandHandle *cmd)
1915 * @param cls the `struct GNUNET_OS_CommandHandle *` 1915 * @param cls the `struct GNUNET_OS_CommandHandle *`
1916 */ 1916 */
1917static void 1917static void
1918cmd_read (void *cls) 1918cmd_read(void *cls)
1919{ 1919{
1920 struct GNUNET_OS_CommandHandle *cmd = cls; 1920 struct GNUNET_OS_CommandHandle *cmd = cls;
1921 const struct GNUNET_SCHEDULER_TaskContext *tc; 1921 const struct GNUNET_SCHEDULER_TaskContext *tc;
@@ -1924,46 +1924,46 @@ cmd_read (void *cls)
1924 ssize_t ret; 1924 ssize_t ret;
1925 1925
1926 cmd->rtask = NULL; 1926 cmd->rtask = NULL;
1927 tc = GNUNET_SCHEDULER_get_task_context (); 1927 tc = GNUNET_SCHEDULER_get_task_context();
1928 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, cmd->r)) 1928 if (GNUNET_YES != GNUNET_NETWORK_fdset_handle_isset(tc->read_ready, cmd->r))
1929 { 1929 {
1930 /* timeout */ 1930 /* timeout */
1931 proc = cmd->proc; 1931 proc = cmd->proc;
1932 cmd->proc = NULL; 1932 cmd->proc = NULL;
1933 proc (cmd->proc_cls, NULL); 1933 proc(cmd->proc_cls, NULL);
1934 return; 1934 return;
1935 } 1935 }
1936 ret = GNUNET_DISK_file_read (cmd->r, 1936 ret = GNUNET_DISK_file_read(cmd->r,
1937 &cmd->buf[cmd->off], 1937 &cmd->buf[cmd->off],
1938 sizeof (cmd->buf) - cmd->off); 1938 sizeof(cmd->buf) - cmd->off);
1939 if (ret <= 0) 1939 if (ret <= 0)
1940 {
1941 if ((cmd->off > 0) && (cmd->off < sizeof (cmd->buf)))
1942 { 1940 {
1943 cmd->buf[cmd->off] = '\0'; 1941 if ((cmd->off > 0) && (cmd->off < sizeof(cmd->buf)))
1944 cmd->proc (cmd->proc_cls, cmd->buf); 1942 {
1943 cmd->buf[cmd->off] = '\0';
1944 cmd->proc(cmd->proc_cls, cmd->buf);
1945 }
1946 proc = cmd->proc;
1947 cmd->proc = NULL;
1948 proc(cmd->proc_cls, NULL);
1949 return;
1945 } 1950 }
1946 proc = cmd->proc; 1951 end = memchr(&cmd->buf[cmd->off], '\n', ret);
1947 cmd->proc = NULL;
1948 proc (cmd->proc_cls, NULL);
1949 return;
1950 }
1951 end = memchr (&cmd->buf[cmd->off], '\n', ret);
1952 cmd->off += ret; 1952 cmd->off += ret;
1953 while (NULL != end) 1953 while (NULL != end)
1954 { 1954 {
1955 *end = '\0'; 1955 *end = '\0';
1956 cmd->proc (cmd->proc_cls, cmd->buf); 1956 cmd->proc(cmd->proc_cls, cmd->buf);
1957 memmove (cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf)); 1957 memmove(cmd->buf, end + 1, cmd->off - (end + 1 - cmd->buf));
1958 cmd->off -= (end + 1 - cmd->buf); 1958 cmd->off -= (end + 1 - cmd->buf);
1959 end = memchr (cmd->buf, '\n', cmd->off); 1959 end = memchr(cmd->buf, '\n', cmd->off);
1960 } 1960 }
1961 cmd->rtask = 1961 cmd->rtask =
1962 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_absolute_get_remaining ( 1962 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_absolute_get_remaining(
1963 cmd->timeout), 1963 cmd->timeout),
1964 cmd->r, 1964 cmd->r,
1965 &cmd_read, 1965 &cmd_read,
1966 cmd); 1966 cmd);
1967} 1967}
1968 1968
1969 1969
@@ -1979,39 +1979,39 @@ cmd_read (void *cls)
1979 * @return NULL on error 1979 * @return NULL on error
1980 */ 1980 */
1981struct GNUNET_OS_CommandHandle * 1981struct GNUNET_OS_CommandHandle *
1982GNUNET_OS_command_run (GNUNET_OS_LineProcessor proc, 1982GNUNET_OS_command_run(GNUNET_OS_LineProcessor proc,
1983 void *proc_cls, 1983 void *proc_cls,
1984 struct GNUNET_TIME_Relative timeout, 1984 struct GNUNET_TIME_Relative timeout,
1985 const char *binary, 1985 const char *binary,
1986 ...) 1986 ...)
1987{ 1987{
1988 struct GNUNET_OS_CommandHandle *cmd; 1988 struct GNUNET_OS_CommandHandle *cmd;
1989 struct GNUNET_OS_Process *eip; 1989 struct GNUNET_OS_Process *eip;
1990 struct GNUNET_DISK_PipeHandle *opipe; 1990 struct GNUNET_DISK_PipeHandle *opipe;
1991 va_list ap; 1991 va_list ap;
1992 1992
1993 opipe = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 1993 opipe = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
1994 if (NULL == opipe) 1994 if (NULL == opipe)
1995 return NULL; 1995 return NULL;
1996 va_start (ap, binary); 1996 va_start(ap, binary);
1997 /* redirect stdout, don't inherit stderr/stdin */ 1997 /* redirect stdout, don't inherit stderr/stdin */
1998 eip = 1998 eip =
1999 GNUNET_OS_start_process_va (GNUNET_NO, 0, NULL, opipe, NULL, binary, ap); 1999 GNUNET_OS_start_process_va(GNUNET_NO, 0, NULL, opipe, NULL, binary, ap);
2000 va_end (ap); 2000 va_end(ap);
2001 if (NULL == eip) 2001 if (NULL == eip)
2002 { 2002 {
2003 GNUNET_DISK_pipe_close (opipe); 2003 GNUNET_DISK_pipe_close(opipe);
2004 return NULL; 2004 return NULL;
2005 } 2005 }
2006 GNUNET_DISK_pipe_close_end (opipe, GNUNET_DISK_PIPE_END_WRITE); 2006 GNUNET_DISK_pipe_close_end(opipe, GNUNET_DISK_PIPE_END_WRITE);
2007 cmd = GNUNET_new (struct GNUNET_OS_CommandHandle); 2007 cmd = GNUNET_new(struct GNUNET_OS_CommandHandle);
2008 cmd->timeout = GNUNET_TIME_relative_to_absolute (timeout); 2008 cmd->timeout = GNUNET_TIME_relative_to_absolute(timeout);
2009 cmd->eip = eip; 2009 cmd->eip = eip;
2010 cmd->opipe = opipe; 2010 cmd->opipe = opipe;
2011 cmd->proc = proc; 2011 cmd->proc = proc;
2012 cmd->proc_cls = proc_cls; 2012 cmd->proc_cls = proc_cls;
2013 cmd->r = GNUNET_DISK_pipe_handle (opipe, GNUNET_DISK_PIPE_END_READ); 2013 cmd->r = GNUNET_DISK_pipe_handle(opipe, GNUNET_DISK_PIPE_END_READ);
2014 cmd->rtask = GNUNET_SCHEDULER_add_read_file (timeout, cmd->r, &cmd_read, cmd); 2014 cmd->rtask = GNUNET_SCHEDULER_add_read_file(timeout, cmd->r, &cmd_read, cmd);
2015 return cmd; 2015 return cmd;
2016} 2016}
2017 2017
diff --git a/src/util/peer.c b/src/util/peer.c
index 00a259a3b..09347cbfd 100644
--- a/src/util/peer.c
+++ b/src/util/peer.c
@@ -11,7 +11,7 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
@@ -26,11 +26,10 @@
26#include "platform.h" 26#include "platform.h"
27#include "gnunet_peer_lib.h" 27#include "gnunet_peer_lib.h"
28 28
29#define LOG(kind,...) GNUNET_log_from (kind, "util-peer", __VA_ARGS__) 29#define LOG(kind, ...) GNUNET_log_from(kind, "util-peer", __VA_ARGS__)
30 30
31 31
32struct PeerEntry 32struct PeerEntry {
33{
34 /** 33 /**
35 * The identifier itself 34 * The identifier itself
36 */ 35 */
@@ -80,7 +79,7 @@ static unsigned int free_list_start;
80 * @return the interned identity or 0. 79 * @return the interned identity or 0.
81 */ 80 */
82GNUNET_PEER_Id 81GNUNET_PEER_Id
83GNUNET_PEER_search (const struct GNUNET_PeerIdentity *pid) 82GNUNET_PEER_search(const struct GNUNET_PeerIdentity *pid)
84{ 83{
85 struct PeerEntry *e; 84 struct PeerEntry *e;
86 85
@@ -88,10 +87,10 @@ GNUNET_PEER_search (const struct GNUNET_PeerIdentity *pid)
88 return 0; 87 return 0;
89 if (NULL == map) 88 if (NULL == map)
90 return 0; 89 return 0;
91 e = GNUNET_CONTAINER_multipeermap_get (map, pid); 90 e = GNUNET_CONTAINER_multipeermap_get(map, pid);
92 if (NULL == e) 91 if (NULL == e)
93 return 0; 92 return 0;
94 GNUNET_assert (e->rc > 0); 93 GNUNET_assert(e->rc > 0);
95 return e->pid; 94 return e->pid;
96} 95}
97 96
@@ -104,7 +103,7 @@ GNUNET_PEER_search (const struct GNUNET_PeerIdentity *pid)
104 * @return the interned identity. 103 * @return the interned identity.
105 */ 104 */
106GNUNET_PEER_Id 105GNUNET_PEER_Id
107GNUNET_PEER_intern (const struct GNUNET_PeerIdentity *pid) 106GNUNET_PEER_intern(const struct GNUNET_PeerIdentity *pid)
108{ 107{
109 GNUNET_PEER_Id ret; 108 GNUNET_PEER_Id ret;
110 struct PeerEntry *e; 109 struct PeerEntry *e;
@@ -113,42 +112,42 @@ GNUNET_PEER_intern (const struct GNUNET_PeerIdentity *pid)
113 if (NULL == pid) 112 if (NULL == pid)
114 return 0; 113 return 0;
115 if (NULL == map) 114 if (NULL == map)
116 map = GNUNET_CONTAINER_multipeermap_create (32, GNUNET_YES); 115 map = GNUNET_CONTAINER_multipeermap_create(32, GNUNET_YES);
117 e = GNUNET_CONTAINER_multipeermap_get (map, pid); 116 e = GNUNET_CONTAINER_multipeermap_get(map, pid);
118 if (NULL != e) 117 if (NULL != e)
119 { 118 {
120 GNUNET_assert (e->rc > 0); 119 GNUNET_assert(e->rc > 0);
121 e->rc++; 120 e->rc++;
122 return e->pid; 121 return e->pid;
123 } 122 }
124 ret = free_list_start; 123 ret = free_list_start;
125 if (ret == size) 124 if (ret == size)
126 {
127 GNUNET_array_grow (table, size, size + 16);
128 for (i = ret; i < size; i++)
129 { 125 {
130 table[i] = GNUNET_new (struct PeerEntry); 126 GNUNET_array_grow(table, size, size + 16);
131 table[i]->pid = i + 1; 127 for (i = ret; i < size; i++)
128 {
129 table[i] = GNUNET_new(struct PeerEntry);
130 table[i]->pid = i + 1;
131 }
132 } 132 }
133 }
134 if (0 == ret) 133 if (0 == ret)
135 { 134 {
136 memset (&table[0]->id, 0, sizeof (struct GNUNET_PeerIdentity)); 135 memset(&table[0]->id, 0, sizeof(struct GNUNET_PeerIdentity));
137 table[0]->pid = 0; 136 table[0]->pid = 0;
138 table[0]->rc = 1; 137 table[0]->rc = 1;
139 ret = 1; 138 ret = 1;
140 } 139 }
141 GNUNET_assert (ret < size); 140 GNUNET_assert(ret < size);
142 GNUNET_assert (0 == table[ret]->rc); 141 GNUNET_assert(0 == table[ret]->rc);
143 free_list_start = table[ret]->pid; 142 free_list_start = table[ret]->pid;
144 table[ret]->id = *pid; 143 table[ret]->id = *pid;
145 table[ret]->rc = 1; 144 table[ret]->rc = 1;
146 table[ret]->pid = ret; 145 table[ret]->pid = ret;
147 GNUNET_break (GNUNET_OK == 146 GNUNET_break(GNUNET_OK ==
148 GNUNET_CONTAINER_multipeermap_put (map, 147 GNUNET_CONTAINER_multipeermap_put(map,
149 &table[ret]->id, 148 &table[ret]->id,
150 table[ret], 149 table[ret],
151 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY)); 150 GNUNET_CONTAINER_MULTIHASHMAPOPTION_UNIQUE_ONLY));
152 return ret; 151 return ret;
153} 152}
154 153
@@ -160,7 +159,7 @@ GNUNET_PEER_intern (const struct GNUNET_PeerIdentity *pid)
160 * @param count size of the ids array 159 * @param count size of the ids array
161 */ 160 */
162void 161void
163GNUNET_PEER_decrement_rcs (const GNUNET_PEER_Id *ids, unsigned int count) 162GNUNET_PEER_decrement_rcs(const GNUNET_PEER_Id *ids, unsigned int count)
164{ 163{
165 int i; 164 int i;
166 GNUNET_PEER_Id id; 165 GNUNET_PEER_Id id;
@@ -168,23 +167,23 @@ GNUNET_PEER_decrement_rcs (const GNUNET_PEER_Id *ids, unsigned int count)
168 if (0 == count) 167 if (0 == count)
169 return; 168 return;
170 for (i = count - 1; i >= 0; i--) 169 for (i = count - 1; i >= 0; i--)
171 {
172 id = ids[i];
173 if (0 == id)
174 continue;
175 GNUNET_assert (id < size);
176 GNUNET_assert (table[id]->rc > 0);
177 table[id]->rc--;
178 if (0 == table[id]->rc)
179 { 170 {
180 GNUNET_break (GNUNET_OK == 171 id = ids[i];
181 GNUNET_CONTAINER_multipeermap_remove (map, 172 if (0 == id)
182 &table[id]->id, 173 continue;
183 table[id])); 174 GNUNET_assert(id < size);
184 table[id]->pid = free_list_start; 175 GNUNET_assert(table[id]->rc > 0);
185 free_list_start = id; 176 table[id]->rc--;
177 if (0 == table[id]->rc)
178 {
179 GNUNET_break(GNUNET_OK ==
180 GNUNET_CONTAINER_multipeermap_remove(map,
181 &table[id]->id,
182 table[id]));
183 table[id]->pid = free_list_start;
184 free_list_start = id;
185 }
186 } 186 }
187 }
188} 187}
189 188
190 189
@@ -195,24 +194,24 @@ GNUNET_PEER_decrement_rcs (const GNUNET_PEER_Id *ids, unsigned int count)
195 * @param delta how much to change the RC 194 * @param delta how much to change the RC
196 */ 195 */
197void 196void
198GNUNET_PEER_change_rc (GNUNET_PEER_Id id, int delta) 197GNUNET_PEER_change_rc(GNUNET_PEER_Id id, int delta)
199{ 198{
200 if (0 == id) 199 if (0 == id)
201 return; 200 return;
202 GNUNET_assert (id < size); 201 GNUNET_assert(id < size);
203 GNUNET_assert (table[id]->rc > 0); 202 GNUNET_assert(table[id]->rc > 0);
204 GNUNET_assert ( (delta >= 0) || 203 GNUNET_assert((delta >= 0) ||
205 (table[id]->rc >= (unsigned int) (-delta)) ); 204 (table[id]->rc >= (unsigned int)(-delta)));
206 table[id]->rc += delta; 205 table[id]->rc += delta;
207 if (0 == table[id]->rc) 206 if (0 == table[id]->rc)
208 { 207 {
209 GNUNET_break (GNUNET_OK == 208 GNUNET_break(GNUNET_OK ==
210 GNUNET_CONTAINER_multipeermap_remove (map, 209 GNUNET_CONTAINER_multipeermap_remove(map,
211 &table[id]->id, 210 &table[id]->id,
212 table[id])); 211 table[id]));
213 table[id]->pid = free_list_start; 212 table[id]->pid = free_list_start;
214 free_list_start = id; 213 free_list_start = id;
215 } 214 }
216} 215}
217 216
218 217
@@ -223,15 +222,15 @@ GNUNET_PEER_change_rc (GNUNET_PEER_Id id, int delta)
223 * @param pid where to write the normal peer identity 222 * @param pid where to write the normal peer identity
224 */ 223 */
225void 224void
226GNUNET_PEER_resolve (GNUNET_PEER_Id id, struct GNUNET_PeerIdentity *pid) 225GNUNET_PEER_resolve(GNUNET_PEER_Id id, struct GNUNET_PeerIdentity *pid)
227{ 226{
228 if (0 == id) 227 if (0 == id)
229 { 228 {
230 memset (pid, 0, sizeof (struct GNUNET_PeerIdentity)); 229 memset(pid, 0, sizeof(struct GNUNET_PeerIdentity));
231 return; 230 return;
232 } 231 }
233 GNUNET_assert (id < size); 232 GNUNET_assert(id < size);
234 GNUNET_assert (table[id]->rc > 0); 233 GNUNET_assert(table[id]->rc > 0);
235 *pid = table[id]->id; 234 *pid = table[id]->id;
236} 235}
237 236
@@ -243,10 +242,10 @@ GNUNET_PEER_resolve (GNUNET_PEER_Id id, struct GNUNET_PeerIdentity *pid)
243 * @return pointer to peer identity, valid as long 'id' is valid 242 * @return pointer to peer identity, valid as long 'id' is valid
244 */ 243 */
245const struct GNUNET_PeerIdentity * 244const struct GNUNET_PeerIdentity *
246GNUNET_PEER_resolve2 (GNUNET_PEER_Id id) 245GNUNET_PEER_resolve2(GNUNET_PEER_Id id)
247{ 246{
248 GNUNET_assert (id < size); 247 GNUNET_assert(id < size);
249 GNUNET_assert (table[id]->rc > 0); 248 GNUNET_assert(table[id]->rc > 0);
250 return &table[id]->id; 249 return &table[id]->id;
251} 250}
252 251
diff --git a/src/util/perf_crypto_asymmetric.c b/src/util/perf_crypto_asymmetric.c
index f42706bda..91679afa5 100644
--- a/src/util/perf_crypto_asymmetric.c
+++ b/src/util/perf_crypto_asymmetric.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Bart Polot 22 * @author Bart Polot
@@ -31,8 +31,7 @@ static struct GNUNET_TIME_Absolute start;
31 31
32#define l 500 32#define l 500
33 33
34struct TestSig 34struct TestSig {
35{
36 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 35 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
37 struct GNUNET_HashCode h; 36 struct GNUNET_HashCode h;
38 struct GNUNET_CRYPTO_EddsaSignature sig; 37 struct GNUNET_CRYPTO_EddsaSignature sig;
@@ -40,26 +39,26 @@ struct TestSig
40 39
41 40
42static void 41static void
43log_duration (const char *cryptosystem, 42log_duration(const char *cryptosystem,
44 const char *description) 43 const char *description)
45{ 44{
46 struct GNUNET_TIME_Relative t; 45 struct GNUNET_TIME_Relative t;
47 char s[64]; 46 char s[64];
48 47
49 sprintf (s, "%6s %15s", cryptosystem, description); 48 sprintf(s, "%6s %15s", cryptosystem, description);
50 t = GNUNET_TIME_absolute_get_duration (start); 49 t = GNUNET_TIME_absolute_get_duration(start);
51 t = GNUNET_TIME_relative_divide (t, l); 50 t = GNUNET_TIME_relative_divide(t, l);
52 fprintf (stdout, 51 fprintf(stdout,
53 "%s: %10s\n", 52 "%s: %10s\n",
54 s, 53 s,
55 GNUNET_STRINGS_relative_time_to_string (t, 54 GNUNET_STRINGS_relative_time_to_string(t,
56 GNUNET_NO)); 55 GNUNET_NO));
57 GAUGER ("UTIL", s, t.rel_value_us, "us"); 56 GAUGER("UTIL", s, t.rel_value_us, "us");
58} 57}
59 58
60 59
61int 60int
62main (int argc, char *argv[]) 61main(int argc, char *argv[])
63{ 62{
64 int i; 63 int i;
65 struct GNUNET_CRYPTO_EcdhePrivateKey *ecdhe[l]; 64 struct GNUNET_CRYPTO_EcdhePrivateKey *ecdhe[l];
@@ -70,60 +69,60 @@ main (int argc, char *argv[])
70 69
71 start = GNUNET_TIME_absolute_get(); 70 start = GNUNET_TIME_absolute_get();
72 for (i = 0; i < l; i++) 71 for (i = 0; i < l; i++)
73 { 72 {
74 sig[i].purp.purpose = 0; 73 sig[i].purp.purpose = 0;
75 sig[i].purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose) 74 sig[i].purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose)
76 + sizeof (struct GNUNET_HashCode)); 75 + sizeof(struct GNUNET_HashCode));
77 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 76 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
78 &sig[i].h, 77 &sig[i].h,
79 sizeof (sig[i].h)); 78 sizeof(sig[i].h));
80 } 79 }
81 log_duration ("", "Init"); 80 log_duration("", "Init");
82 81
83 start = GNUNET_TIME_absolute_get(); 82 start = GNUNET_TIME_absolute_get();
84 for (i = 0; i < l; i++) 83 for (i = 0; i < l; i++)
85 eddsa[i] = GNUNET_CRYPTO_eddsa_key_create(); 84 eddsa[i] = GNUNET_CRYPTO_eddsa_key_create();
86 log_duration ("EdDSA", "create key"); 85 log_duration("EdDSA", "create key");
87 86
88 start = GNUNET_TIME_absolute_get(); 87 start = GNUNET_TIME_absolute_get();
89 for (i = 0; i < l; i++) 88 for (i = 0; i < l; i++)
90 GNUNET_CRYPTO_eddsa_key_get_public (eddsa[i], &dspub[i]); 89 GNUNET_CRYPTO_eddsa_key_get_public(eddsa[i], &dspub[i]);
91 log_duration ("EdDSA", "get public"); 90 log_duration("EdDSA", "get public");
92 91
93 start = GNUNET_TIME_absolute_get(); 92 start = GNUNET_TIME_absolute_get();
94 for (i = 0; i < l; i++) 93 for (i = 0; i < l; i++)
95 GNUNET_assert (GNUNET_OK == 94 GNUNET_assert(GNUNET_OK ==
96 GNUNET_CRYPTO_eddsa_sign (eddsa[i], 95 GNUNET_CRYPTO_eddsa_sign(eddsa[i],
97 &sig[i].purp, 96 &sig[i].purp,
98 &sig[i].sig)); 97 &sig[i].sig));
99 log_duration ("EdDSA", "sign HashCode"); 98 log_duration("EdDSA", "sign HashCode");
100 99
101 start = GNUNET_TIME_absolute_get(); 100 start = GNUNET_TIME_absolute_get();
102 for (i = 0; i < l; i++) 101 for (i = 0; i < l; i++)
103 GNUNET_assert (GNUNET_OK == 102 GNUNET_assert(GNUNET_OK ==
104 GNUNET_CRYPTO_eddsa_verify (0, 103 GNUNET_CRYPTO_eddsa_verify(0,
105 &sig[i].purp, 104 &sig[i].purp,
106 &sig[i].sig, 105 &sig[i].sig,
107 &dspub[i])); 106 &dspub[i]));
108 log_duration ("EdDSA", "verify HashCode"); 107 log_duration("EdDSA", "verify HashCode");
109 108
110 start = GNUNET_TIME_absolute_get(); 109 start = GNUNET_TIME_absolute_get();
111 for (i = 0; i < l; i++) 110 for (i = 0; i < l; i++)
112 ecdhe[i] = GNUNET_CRYPTO_ecdhe_key_create(); 111 ecdhe[i] = GNUNET_CRYPTO_ecdhe_key_create();
113 log_duration ("ECDH", "create key"); 112 log_duration("ECDH", "create key");
114 113
115 start = GNUNET_TIME_absolute_get(); 114 start = GNUNET_TIME_absolute_get();
116 for (i = 0; i < l; i++) 115 for (i = 0; i < l; i++)
117 GNUNET_CRYPTO_ecdhe_key_get_public (ecdhe[i], &dhpub[i]); 116 GNUNET_CRYPTO_ecdhe_key_get_public(ecdhe[i], &dhpub[i]);
118 log_duration ("ECDH", "get public"); 117 log_duration("ECDH", "get public");
119 118
120 start = GNUNET_TIME_absolute_get(); 119 start = GNUNET_TIME_absolute_get();
121 for (i = 0; i < l - 1; i+=2) 120 for (i = 0; i < l - 1; i += 2)
122 { 121 {
123 GNUNET_CRYPTO_ecc_ecdh (ecdhe[i], &dhpub[i+1], &sig[i].h); 122 GNUNET_CRYPTO_ecc_ecdh(ecdhe[i], &dhpub[i + 1], &sig[i].h);
124 GNUNET_CRYPTO_ecc_ecdh (ecdhe[i+1], &dhpub[i], &sig[i+1].h); 123 GNUNET_CRYPTO_ecc_ecdh(ecdhe[i + 1], &dhpub[i], &sig[i + 1].h);
125 } 124 }
126 log_duration ("ECDH", "do DH"); 125 log_duration("ECDH", "do DH");
127 126
128 return 0; 127 return 0;
129} 128}
diff --git a/src/util/perf_crypto_ecc_dlog.c b/src/util/perf_crypto_ecc_dlog.c
index 2729241e2..b09a6ed6f 100644
--- a/src/util/perf_crypto_ecc_dlog.c
+++ b/src/util/perf_crypto_ecc_dlog.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/perf_crypto_ecc_dlog.c 22 * @file util/perf_crypto_ecc_dlog.c
23 * @brief benchmark for ECC DLOG calculation 23 * @brief benchmark for ECC DLOG calculation
@@ -49,12 +49,12 @@
49 49
50/** 50/**
51 * How many values do we test? 51 * How many values do we test?
52 */ 52 */
53#define TEST_ITER 10 53#define TEST_ITER 10
54 54
55/** 55/**
56 * Range of values to use for MATH tests. 56 * Range of values to use for MATH tests.
57 */ 57 */
58#define MATH_MAX 500000 58#define MATH_MAX 500000
59 59
60 60
@@ -65,8 +65,8 @@
65 * @param do_dlog #GNUNET_YES if we want to actually do the bencharked operation 65 * @param do_dlog #GNUNET_YES if we want to actually do the bencharked operation
66 */ 66 */
67static void 67static void
68test_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc, 68test_dlog(struct GNUNET_CRYPTO_EccDlogContext *edc,
69 int do_dlog) 69 int do_dlog)
70{ 70{
71 gcry_mpi_t fact; 71 gcry_mpi_t fact;
72 gcry_mpi_t n; 72 gcry_mpi_t n;
@@ -77,96 +77,96 @@ test_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc,
77 int x; 77 int x;
78 int iret; 78 int iret;
79 79
80 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE)); 80 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, NULL, CURVE));
81 g = gcry_mpi_ec_get_point ("g", ctx, 0); 81 g = gcry_mpi_ec_get_point("g", ctx, 0);
82 GNUNET_assert (NULL != g); 82 GNUNET_assert(NULL != g);
83 n = gcry_mpi_ec_get_mpi ("n", ctx, 0); 83 n = gcry_mpi_ec_get_mpi("n", ctx, 0);
84 q = gcry_mpi_point_new (0); 84 q = gcry_mpi_point_new(0);
85 fact = gcry_mpi_new (0); 85 fact = gcry_mpi_new(0);
86 for (i=0;i<TEST_ITER;i++) 86 for (i = 0; i < TEST_ITER; i++)
87 {
88 fprintf (stderr, ".");
89 x = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
90 MAX_FACT);
91 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
92 2))
93 {
94 gcry_mpi_set_ui (fact, x);
95 gcry_mpi_sub (fact, n, fact);
96 x = - x;
97 }
98 else
99 {
100 gcry_mpi_set_ui (fact, x);
101 }
102 gcry_mpi_ec_mul (q, fact, g, ctx);
103 if ( (GNUNET_YES == do_dlog) &&
104 (x !=
105 (iret = GNUNET_CRYPTO_ecc_dlog (edc,
106 q))) )
107 { 87 {
108 fprintf (stderr, 88 fprintf(stderr, ".");
109 "DLOG failed for value %d (%d)\n", 89 x = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
110 x, 90 MAX_FACT);
111 iret); 91 if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
112 GNUNET_assert (0); 92 2))
93 {
94 gcry_mpi_set_ui(fact, x);
95 gcry_mpi_sub(fact, n, fact);
96 x = -x;
97 }
98 else
99 {
100 gcry_mpi_set_ui(fact, x);
101 }
102 gcry_mpi_ec_mul(q, fact, g, ctx);
103 if ((GNUNET_YES == do_dlog) &&
104 (x !=
105 (iret = GNUNET_CRYPTO_ecc_dlog(edc,
106 q))))
107 {
108 fprintf(stderr,
109 "DLOG failed for value %d (%d)\n",
110 x,
111 iret);
112 GNUNET_assert(0);
113 }
113 } 114 }
114 } 115 gcry_mpi_release(fact);
115 gcry_mpi_release (fact); 116 gcry_mpi_release(n);
116 gcry_mpi_release (n); 117 gcry_mpi_point_release(g);
117 gcry_mpi_point_release (g); 118 gcry_mpi_point_release(q);
118 gcry_mpi_point_release (q); 119 gcry_ctx_release(ctx);
119 gcry_ctx_release (ctx); 120 fprintf(stderr, "\n");
120 fprintf (stderr, "\n");
121} 121}
122 122
123 123
124int 124int
125main (int argc, char *argv[]) 125main(int argc, char *argv[])
126{ 126{
127 struct GNUNET_CRYPTO_EccDlogContext *edc; 127 struct GNUNET_CRYPTO_EccDlogContext *edc;
128 struct GNUNET_TIME_Absolute start; 128 struct GNUNET_TIME_Absolute start;
129 struct GNUNET_TIME_Relative delta; 129 struct GNUNET_TIME_Relative delta;
130 130
131 if (! gcry_check_version ("1.6.0")) 131 if (!gcry_check_version("1.6.0"))
132 { 132 {
133 fprintf (stderr, 133 fprintf(stderr,
134 _ 134 _
135 ("libgcrypt has not the expected version (version %s is required).\n"), 135 ("libgcrypt has not the expected version (version %s is required).\n"),
136 "1.6.0"); 136 "1.6.0");
137 return 0; 137 return 0;
138 } 138 }
139 if (getenv ("GNUNET_GCRYPT_DEBUG")) 139 if (getenv("GNUNET_GCRYPT_DEBUG"))
140 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); 140 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
141 GNUNET_log_setup ("perf-crypto-ecc-dlog", 141 GNUNET_log_setup("perf-crypto-ecc-dlog",
142 "WARNING", 142 "WARNING",
143 NULL); 143 NULL);
144 start = GNUNET_TIME_absolute_get (); 144 start = GNUNET_TIME_absolute_get();
145 edc = GNUNET_CRYPTO_ecc_dlog_prepare (MAX_FACT, 145 edc = GNUNET_CRYPTO_ecc_dlog_prepare(MAX_FACT,
146 MAX_MEM); 146 MAX_MEM);
147 printf ("DLOG precomputation 1M/1K took %s\n", 147 printf("DLOG precomputation 1M/1K took %s\n",
148 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 148 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
149 GNUNET_YES)); 149 GNUNET_YES));
150 GAUGER ("UTIL", "ECC DLOG initialization", 150 GAUGER("UTIL", "ECC DLOG initialization",
151 GNUNET_TIME_absolute_get_duration 151 GNUNET_TIME_absolute_get_duration
152 (start).rel_value_us / 1000LL, "ms/op"); 152 (start).rel_value_us / 1000LL, "ms/op");
153 start = GNUNET_TIME_absolute_get (); 153 start = GNUNET_TIME_absolute_get();
154 /* first do a baseline run without the DLOG */ 154 /* first do a baseline run without the DLOG */
155 test_dlog (edc, GNUNET_NO); 155 test_dlog(edc, GNUNET_NO);
156 delta = GNUNET_TIME_absolute_get_duration (start); 156 delta = GNUNET_TIME_absolute_get_duration(start);
157 start = GNUNET_TIME_absolute_get (); 157 start = GNUNET_TIME_absolute_get();
158 test_dlog (edc, GNUNET_YES); 158 test_dlog(edc, GNUNET_YES);
159 delta = GNUNET_TIME_relative_subtract (GNUNET_TIME_absolute_get_duration (start), 159 delta = GNUNET_TIME_relative_subtract(GNUNET_TIME_absolute_get_duration(start),
160 delta); 160 delta);
161 printf ("%u DLOG calculations took %s\n", 161 printf("%u DLOG calculations took %s\n",
162 TEST_ITER, 162 TEST_ITER,
163 GNUNET_STRINGS_relative_time_to_string (delta, 163 GNUNET_STRINGS_relative_time_to_string(delta,
164 GNUNET_YES)); 164 GNUNET_YES));
165 GAUGER ("UTIL", "ECC DLOG operations", 165 GAUGER("UTIL", "ECC DLOG operations",
166 delta.rel_value_us / 1000LL / TEST_ITER, 166 delta.rel_value_us / 1000LL / TEST_ITER,
167 "ms/op"); 167 "ms/op");
168 168
169 GNUNET_CRYPTO_ecc_dlog_release (edc); 169 GNUNET_CRYPTO_ecc_dlog_release(edc);
170 return 0; 170 return 0;
171} 171}
172 172
diff --git a/src/util/perf_crypto_hash.c b/src/util/perf_crypto_hash.c
index c74f425ce..cdcff2824 100644
--- a/src/util/perf_crypto_hash.c
+++ b/src/util/perf_crypto_hash.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -30,80 +30,80 @@
30 30
31 31
32static void 32static void
33perfHash () 33perfHash()
34{ 34{
35 struct GNUNET_HashCode hc; 35 struct GNUNET_HashCode hc;
36 unsigned int i; 36 unsigned int i;
37 char buf[64 * 1024]; 37 char buf[64 * 1024];
38 38
39 memset (buf, 1, sizeof (buf)); 39 memset(buf, 1, sizeof(buf));
40 for (i = 0; i < 1024; i++) 40 for (i = 0; i < 1024; i++)
41 GNUNET_CRYPTO_hash (buf, sizeof (buf), &hc); 41 GNUNET_CRYPTO_hash(buf, sizeof(buf), &hc);
42} 42}
43 43
44 44
45static void 45static void
46perfHashSmall () 46perfHashSmall()
47{ 47{
48 struct GNUNET_HashCode hc; 48 struct GNUNET_HashCode hc;
49 unsigned int i; 49 unsigned int i;
50 char buf[64]; 50 char buf[64];
51 51
52 memset (buf, 1, sizeof (buf)); 52 memset(buf, 1, sizeof(buf));
53 for (i = 0; i < 1024; i++) 53 for (i = 0; i < 1024; i++)
54 GNUNET_CRYPTO_hash (buf, sizeof (buf), &hc); 54 GNUNET_CRYPTO_hash(buf, sizeof(buf), &hc);
55} 55}
56 56
57 57
58static void 58static void
59perfHKDF () 59perfHKDF()
60{ 60{
61 unsigned int i; 61 unsigned int i;
62 char res[128]; 62 char res[128];
63 char buf[128]; 63 char buf[128];
64 char skm[64]; 64 char skm[64];
65 65
66 memset (buf, 1, sizeof (buf)); 66 memset(buf, 1, sizeof(buf));
67 memset (skm, 2, sizeof (skm)); 67 memset(skm, 2, sizeof(skm));
68 for (i = 0; i < 1024; i++) 68 for (i = 0; i < 1024; i++)
69 GNUNET_CRYPTO_hkdf (res, sizeof (res), 69 GNUNET_CRYPTO_hkdf(res, sizeof(res),
70 GCRY_MD_SHA512, GCRY_MD_SHA256, 70 GCRY_MD_SHA512, GCRY_MD_SHA256,
71 buf, sizeof (buf), 71 buf, sizeof(buf),
72 skm, sizeof (skm), 72 skm, sizeof(skm),
73 "test", (size_t) 4, 73 "test", (size_t)4,
74 NULL, 0); 74 NULL, 0);
75} 75}
76 76
77 77
78int 78int
79main (int argc, char *argv[]) 79main(int argc, char *argv[])
80{ 80{
81 struct GNUNET_TIME_Absolute start; 81 struct GNUNET_TIME_Absolute start;
82 82
83 start = GNUNET_TIME_absolute_get (); 83 start = GNUNET_TIME_absolute_get();
84 perfHashSmall (); 84 perfHashSmall();
85 printf ("1024x 64-byte Hash perf took %s\n", 85 printf("1024x 64-byte Hash perf took %s\n",
86 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 86 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
87 GNUNET_YES)); 87 GNUNET_YES));
88 88
89 start = GNUNET_TIME_absolute_get (); 89 start = GNUNET_TIME_absolute_get();
90 perfHash (); 90 perfHash();
91 printf ("1024x 64k Hash perf took %s\n", 91 printf("1024x 64k Hash perf took %s\n",
92 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 92 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
93 GNUNET_YES)); 93 GNUNET_YES));
94 GAUGER ("UTIL", "Cryptographic hashing", 94 GAUGER("UTIL", "Cryptographic hashing",
95 64 * 1024 / (1 + 95 64 * 1024 / (1 +
96 GNUNET_TIME_absolute_get_duration 96 GNUNET_TIME_absolute_get_duration
97 (start).rel_value_us / 1000LL), "kb/ms"); 97 (start).rel_value_us / 1000LL), "kb/ms");
98 start = GNUNET_TIME_absolute_get (); 98 start = GNUNET_TIME_absolute_get();
99 perfHKDF (); 99 perfHKDF();
100 printf ("HKDF perf took %s\n", 100 printf("HKDF perf took %s\n",
101 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 101 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
102 GNUNET_YES)); 102 GNUNET_YES));
103 GAUGER ("UTIL", "Cryptographic HKDF", 103 GAUGER("UTIL", "Cryptographic HKDF",
104 64 * 1024 / (1 + 104 64 * 1024 / (1 +
105 GNUNET_TIME_absolute_get_duration 105 GNUNET_TIME_absolute_get_duration
106 (start).rel_value_us / 1000LL), "kb/ms"); 106 (start).rel_value_us / 1000LL), "kb/ms");
107 return 0; 107 return 0;
108} 108}
109 109
diff --git a/src/util/perf_crypto_paillier.c b/src/util/perf_crypto_paillier.c
index a62b72c96..f2aa132d5 100644
--- a/src/util/perf_crypto_paillier.c
+++ b/src/util/perf_crypto_paillier.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -29,7 +29,7 @@
29 29
30 30
31int 31int
32main (int argc, char *argv[]) 32main(int argc, char *argv[])
33{ 33{
34 struct GNUNET_TIME_Absolute start; 34 struct GNUNET_TIME_Absolute start;
35 struct GNUNET_CRYPTO_PaillierPublicKey public_key; 35 struct GNUNET_CRYPTO_PaillierPublicKey public_key;
@@ -38,51 +38,51 @@ main (int argc, char *argv[])
38 gcry_mpi_t m1; 38 gcry_mpi_t m1;
39 unsigned int i; 39 unsigned int i;
40 40
41 start = GNUNET_TIME_absolute_get (); 41 start = GNUNET_TIME_absolute_get();
42 for (i=0;i<10;i++) 42 for (i = 0; i < 10; i++)
43 GNUNET_CRYPTO_paillier_create (&public_key, 43 GNUNET_CRYPTO_paillier_create(&public_key,
44 &private_key); 44 &private_key);
45 printf ("10x key generation took %s\n", 45 printf("10x key generation took %s\n",
46 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 46 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
47 GNUNET_YES)); 47 GNUNET_YES));
48 GAUGER ("UTIL", "Paillier key generation", 48 GAUGER("UTIL", "Paillier key generation",
49 64 * 1024 / (1 + 49 64 * 1024 / (1 +
50 GNUNET_TIME_absolute_get_duration 50 GNUNET_TIME_absolute_get_duration
51 (start).rel_value_us / 1000LL), "keys/ms"); 51 (start).rel_value_us / 1000LL), "keys/ms");
52 52
53 m1 = gcry_mpi_new (0); 53 m1 = gcry_mpi_new(0);
54 m1 = gcry_mpi_set_ui (m1, 1); 54 m1 = gcry_mpi_set_ui(m1, 1);
55 /* m1 = m1 * 2 ^ (GCPB - 3) */ 55 /* m1 = m1 * 2 ^ (GCPB - 3) */
56 gcry_mpi_mul_2exp (m1, 56 gcry_mpi_mul_2exp(m1,
57 m1, 57 m1,
58 GNUNET_CRYPTO_PAILLIER_BITS - 3); 58 GNUNET_CRYPTO_PAILLIER_BITS - 3);
59 start = GNUNET_TIME_absolute_get (); 59 start = GNUNET_TIME_absolute_get();
60 for (i=0;i<10;i++) 60 for (i = 0; i < 10; i++)
61 GNUNET_CRYPTO_paillier_encrypt (&public_key, 61 GNUNET_CRYPTO_paillier_encrypt(&public_key,
62 m1, 62 m1,
63 2, 63 2,
64 &c1); 64 &c1);
65 printf ("10x encryption took %s\n", 65 printf("10x encryption took %s\n",
66 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 66 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
67 GNUNET_YES)); 67 GNUNET_YES));
68 GAUGER ("UTIL", "Paillier encryption", 68 GAUGER("UTIL", "Paillier encryption",
69 64 * 1024 / (1 + 69 64 * 1024 / (1 +
70 GNUNET_TIME_absolute_get_duration 70 GNUNET_TIME_absolute_get_duration
71 (start).rel_value_us / 1000LL), "ops/ms"); 71 (start).rel_value_us / 1000LL), "ops/ms");
72 72
73 start = GNUNET_TIME_absolute_get (); 73 start = GNUNET_TIME_absolute_get();
74 for (i=0;i<10;i++) 74 for (i = 0; i < 10; i++)
75 GNUNET_CRYPTO_paillier_decrypt (&private_key, 75 GNUNET_CRYPTO_paillier_decrypt(&private_key,
76 &public_key, 76 &public_key,
77 &c1, 77 &c1,
78 m1); 78 m1);
79 printf ("10x decryption took %s\n", 79 printf("10x decryption took %s\n",
80 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 80 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
81 GNUNET_YES)); 81 GNUNET_YES));
82 GAUGER ("UTIL", "Paillier decryption", 82 GAUGER("UTIL", "Paillier decryption",
83 64 * 1024 / (1 + 83 64 * 1024 / (1 +
84 GNUNET_TIME_absolute_get_duration 84 GNUNET_TIME_absolute_get_duration
85 (start).rel_value_us / 1000LL), "ops/ms"); 85 (start).rel_value_us / 1000LL), "ops/ms");
86 86
87 87
88 return 0; 88 return 0;
diff --git a/src/util/perf_crypto_rsa.c b/src/util/perf_crypto_rsa.c
index 1140738f6..33740666e 100644
--- a/src/util/perf_crypto_rsa.c
+++ b/src/util/perf_crypto_rsa.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -34,7 +34,7 @@
34 * @param len keylength to evaluate with 34 * @param len keylength to evaluate with
35 */ 35 */
36static void 36static void
37eval (unsigned int len) 37eval(unsigned int len)
38{ 38{
39 struct GNUNET_TIME_Absolute start; 39 struct GNUNET_TIME_Absolute start;
40 struct GNUNET_CRYPTO_RsaSignature *sig; 40 struct GNUNET_CRYPTO_RsaSignature *sig;
@@ -48,153 +48,153 @@ eval (unsigned int len)
48 size_t bbuf_len; 48 size_t bbuf_len;
49 struct GNUNET_HashCode hc; 49 struct GNUNET_HashCode hc;
50 50
51 start = GNUNET_TIME_absolute_get (); 51 start = GNUNET_TIME_absolute_get();
52 for (i=0;i<10;i++) 52 for (i = 0; i < 10; i++)
53 { 53 {
54 private_key = GNUNET_CRYPTO_rsa_private_key_create (len); 54 private_key = GNUNET_CRYPTO_rsa_private_key_create(len);
55 GNUNET_CRYPTO_rsa_private_key_free (private_key); 55 GNUNET_CRYPTO_rsa_private_key_free(private_key);
56 } 56 }
57 printf ("10x %u-key generation took %s\n", 57 printf("10x %u-key generation took %s\n",
58 len, 58 len,
59 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 59 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
60 GNUNET_YES)); 60 GNUNET_YES));
61 GNUNET_snprintf (sbuf, 61 GNUNET_snprintf(sbuf,
62 sizeof (sbuf), 62 sizeof(sbuf),
63 "RSA %u-key generation", 63 "RSA %u-key generation",
64 len); 64 len);
65 GAUGER ("UTIL", sbuf, 65 GAUGER("UTIL", sbuf,
66 64 * 1024 / (1 + 66 64 * 1024 / (1 +
67 GNUNET_TIME_absolute_get_duration 67 GNUNET_TIME_absolute_get_duration
68 (start).rel_value_us / 1000LL), "keys/ms"); 68 (start).rel_value_us / 1000LL), "keys/ms");
69 private_key = GNUNET_CRYPTO_rsa_private_key_create (len); 69 private_key = GNUNET_CRYPTO_rsa_private_key_create(len);
70 public_key = GNUNET_CRYPTO_rsa_private_key_get_public (private_key); 70 public_key = GNUNET_CRYPTO_rsa_private_key_get_public(private_key);
71 for (i=0;i<10;i++) 71 for (i = 0; i < 10; i++)
72 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 72 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
73 &bsec[i], sizeof (bsec[0])); 73 &bsec[i], sizeof(bsec[0]));
74 /* 74 /*
75 start = GNUNET_TIME_absolute_get (); 75 start = GNUNET_TIME_absolute_get ();
76 for (i=0;i<10;i++) 76 for (i=0;i<10;i++)
77 rsa_blinding_key_derive(public_key, &bsec[i]); 77 rsa_blinding_key_derive(public_key, &bsec[i]);
78 printf ("10x %u-blinding key generation took %s\n", 78 printf ("10x %u-blinding key generation took %s\n",
79 len, 79 len,
80 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 80 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start),
81 GNUNET_YES)); 81 GNUNET_YES));
82 GNUNET_snprintf (sbuf, 82 GNUNET_snprintf (sbuf,
83 sizeof (sbuf), 83 sizeof (sbuf),
84 "RSA %u-blinding key generation", 84 "RSA %u-blinding key generation",
85 len); 85 len);
86 GAUGER ("UTIL", sbuf, 86 GAUGER ("UTIL", sbuf,
87 64 * 1024 / (1 + 87 64 * 1024 / (1 +
88 GNUNET_TIME_absolute_get_duration 88 GNUNET_TIME_absolute_get_duration
89 (start).rel_value_us / 1000LL), "keys/ms"); 89 (start).rel_value_us / 1000LL), "keys/ms");
90 */ 90 */
91 start = GNUNET_TIME_absolute_get (); 91 start = GNUNET_TIME_absolute_get();
92 GNUNET_CRYPTO_hash ("test", 4, &hc); 92 GNUNET_CRYPTO_hash("test", 4, &hc);
93 for (i=0;i<10;i++) 93 for (i = 0; i < 10; i++)
94 { 94 {
95 GNUNET_CRYPTO_rsa_blind (&hc, 95 GNUNET_CRYPTO_rsa_blind(&hc,
96 &bsec[i], 96 &bsec[i],
97 public_key, 97 public_key,
98 &bbuf, &bbuf_len); 98 &bbuf, &bbuf_len);
99 GNUNET_free (bbuf); 99 GNUNET_free(bbuf);
100 } 100 }
101 printf ("10x %u-blinding took %s\n", 101 printf("10x %u-blinding took %s\n",
102 len, 102 len,
103 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 103 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
104 GNUNET_YES)); 104 GNUNET_YES));
105 GNUNET_snprintf (sbuf, 105 GNUNET_snprintf(sbuf,
106 sizeof (sbuf), 106 sizeof(sbuf),
107 "RSA %u-blinding", 107 "RSA %u-blinding",
108 len); 108 len);
109 GAUGER ("UTIL", 109 GAUGER("UTIL",
110 sbuf, 110 sbuf,
111 64 * 1024 / (1 + 111 64 * 1024 / (1 +
112 GNUNET_TIME_absolute_get_duration 112 GNUNET_TIME_absolute_get_duration
113 (start).rel_value_us / 1000LL), "ops/ms"); 113 (start).rel_value_us / 1000LL), "ops/ms");
114 GNUNET_CRYPTO_rsa_blind (&hc, 114 GNUNET_CRYPTO_rsa_blind(&hc,
115 &bsec[0], 115 &bsec[0],
116 public_key, 116 public_key,
117 &bbuf, &bbuf_len); 117 &bbuf, &bbuf_len);
118 start = GNUNET_TIME_absolute_get (); 118 start = GNUNET_TIME_absolute_get();
119 for (i=0;i<10;i++) 119 for (i = 0; i < 10; i++)
120 { 120 {
121 sig = GNUNET_CRYPTO_rsa_sign_blinded (private_key, 121 sig = GNUNET_CRYPTO_rsa_sign_blinded(private_key,
122 bbuf, bbuf_len); 122 bbuf, bbuf_len);
123 GNUNET_CRYPTO_rsa_signature_free (sig); 123 GNUNET_CRYPTO_rsa_signature_free(sig);
124 } 124 }
125 printf ("10x %u-signing took %s\n", 125 printf("10x %u-signing took %s\n",
126 len, 126 len,
127 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 127 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
128 GNUNET_YES)); 128 GNUNET_YES));
129 GNUNET_snprintf (sbuf, 129 GNUNET_snprintf(sbuf,
130 sizeof (sbuf), 130 sizeof(sbuf),
131 "RSA %u-signing", 131 "RSA %u-signing",
132 len); 132 len);
133 GAUGER ("UTIL", 133 GAUGER("UTIL",
134 sbuf, 134 sbuf,
135 64 * 1024 / (1 + 135 64 * 1024 / (1 +
136 GNUNET_TIME_absolute_get_duration 136 GNUNET_TIME_absolute_get_duration
137 (start).rel_value_us / 1000LL), "ops/ms"); 137 (start).rel_value_us / 1000LL), "ops/ms");
138 sig = GNUNET_CRYPTO_rsa_sign_blinded (private_key, 138 sig = GNUNET_CRYPTO_rsa_sign_blinded(private_key,
139 bbuf, 139 bbuf,
140 bbuf_len); 140 bbuf_len);
141 start = GNUNET_TIME_absolute_get (); 141 start = GNUNET_TIME_absolute_get();
142 for (i=0;i<10;i++) 142 for (i = 0; i < 10; i++)
143 { 143 {
144 rsig = GNUNET_CRYPTO_rsa_unblind (sig, 144 rsig = GNUNET_CRYPTO_rsa_unblind(sig,
145 &bsec[0], 145 &bsec[0],
146 public_key); 146 public_key);
147 GNUNET_CRYPTO_rsa_signature_free (rsig); 147 GNUNET_CRYPTO_rsa_signature_free(rsig);
148 } 148 }
149 printf ("10x %u-unblinding took %s\n", 149 printf("10x %u-unblinding took %s\n",
150 len, 150 len,
151 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 151 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
152 GNUNET_YES)); 152 GNUNET_YES));
153 GNUNET_snprintf (sbuf, 153 GNUNET_snprintf(sbuf,
154 sizeof (sbuf), 154 sizeof(sbuf),
155 "RSA %u-unblinding", 155 "RSA %u-unblinding",
156 len); 156 len);
157 GAUGER ("UTIL", 157 GAUGER("UTIL",
158 sbuf, 158 sbuf,
159 64 * 1024 / (1 + 159 64 * 1024 / (1 +
160 GNUNET_TIME_absolute_get_duration 160 GNUNET_TIME_absolute_get_duration
161 (start).rel_value_us / 1000LL), "ops/ms"); 161 (start).rel_value_us / 1000LL), "ops/ms");
162 rsig = GNUNET_CRYPTO_rsa_unblind (sig, 162 rsig = GNUNET_CRYPTO_rsa_unblind(sig,
163 &bsec[0], 163 &bsec[0],
164 public_key); 164 public_key);
165 start = GNUNET_TIME_absolute_get (); 165 start = GNUNET_TIME_absolute_get();
166 for (i=0;i<10;i++) 166 for (i = 0; i < 10; i++)
167 { 167 {
168 GNUNET_assert (GNUNET_OK == 168 GNUNET_assert(GNUNET_OK ==
169 GNUNET_CRYPTO_rsa_verify (&hc, 169 GNUNET_CRYPTO_rsa_verify(&hc,
170 rsig, 170 rsig,
171 public_key)); 171 public_key));
172 } 172 }
173 printf ("10x %u-verifying took %s\n", 173 printf("10x %u-verifying took %s\n",
174 len, 174 len,
175 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 175 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
176 GNUNET_YES)); 176 GNUNET_YES));
177 GNUNET_snprintf (sbuf, 177 GNUNET_snprintf(sbuf,
178 sizeof (sbuf), 178 sizeof(sbuf),
179 "RSA %u-verification", 179 "RSA %u-verification",
180 len); 180 len);
181 GAUGER ("UTIL", 181 GAUGER("UTIL",
182 sbuf, 182 sbuf,
183 64 * 1024 / (1 + 183 64 * 1024 / (1 +
184 GNUNET_TIME_absolute_get_duration 184 GNUNET_TIME_absolute_get_duration
185 (start).rel_value_us / 1000LL), "ops/ms"); 185 (start).rel_value_us / 1000LL), "ops/ms");
186 GNUNET_CRYPTO_rsa_signature_free (sig); 186 GNUNET_CRYPTO_rsa_signature_free(sig);
187 GNUNET_CRYPTO_rsa_public_key_free (public_key); 187 GNUNET_CRYPTO_rsa_public_key_free(public_key);
188 GNUNET_CRYPTO_rsa_private_key_free (private_key); 188 GNUNET_CRYPTO_rsa_private_key_free(private_key);
189 GNUNET_free (bbuf); 189 GNUNET_free(bbuf);
190} 190}
191 191
192 192
193int 193int
194main (int argc, char *argv[]) 194main(int argc, char *argv[])
195{ 195{
196 eval (1024); 196 eval(1024);
197 eval (2048); 197 eval(2048);
198 /* eval (4096); */ 198 /* eval (4096); */
199 return 0; 199 return 0;
200} 200}
diff --git a/src/util/perf_crypto_symmetric.c b/src/util/perf_crypto_symmetric.c
index 0bef04b7a..01bec8f11 100644
--- a/src/util/perf_crypto_symmetric.c
+++ b/src/util/perf_crypto_symmetric.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -29,7 +29,7 @@
29 29
30 30
31static void 31static void
32perfEncrypt () 32perfEncrypt()
33{ 33{
34 unsigned int i; 34 unsigned int i;
35 char buf[64 * 1024]; 35 char buf[64 * 1024];
@@ -37,38 +37,38 @@ perfEncrypt ()
37 struct GNUNET_CRYPTO_SymmetricSessionKey sk; 37 struct GNUNET_CRYPTO_SymmetricSessionKey sk;
38 struct GNUNET_CRYPTO_SymmetricInitializationVector iv; 38 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
39 39
40 GNUNET_CRYPTO_symmetric_create_session_key (&sk); 40 GNUNET_CRYPTO_symmetric_create_session_key(&sk);
41 41
42 memset (buf, 1, sizeof (buf)); 42 memset(buf, 1, sizeof(buf));
43 for (i = 0; i < 1024; i++) 43 for (i = 0; i < 1024; i++)
44 { 44 {
45 memset (&iv, (int8_t) i, sizeof (iv)); 45 memset(&iv, (int8_t)i, sizeof(iv));
46 GNUNET_CRYPTO_symmetric_encrypt (buf, sizeof (buf), 46 GNUNET_CRYPTO_symmetric_encrypt(buf, sizeof(buf),
47 &sk, &iv, 47 &sk, &iv,
48 rbuf); 48 rbuf);
49 GNUNET_CRYPTO_symmetric_decrypt (rbuf, sizeof (buf), 49 GNUNET_CRYPTO_symmetric_decrypt(rbuf, sizeof(buf),
50 &sk, &iv, 50 &sk, &iv,
51 buf); 51 buf);
52 } 52 }
53 memset (rbuf, 1, sizeof (rbuf)); 53 memset(rbuf, 1, sizeof(rbuf));
54 GNUNET_assert (0 == memcmp (rbuf, buf, sizeof (buf))); 54 GNUNET_assert(0 == memcmp(rbuf, buf, sizeof(buf)));
55} 55}
56 56
57 57
58int 58int
59main (int argc, char *argv[]) 59main(int argc, char *argv[])
60{ 60{
61 struct GNUNET_TIME_Absolute start; 61 struct GNUNET_TIME_Absolute start;
62 62
63 start = GNUNET_TIME_absolute_get (); 63 start = GNUNET_TIME_absolute_get();
64 perfEncrypt (); 64 perfEncrypt();
65 printf ("Encrypt perf took %s\n", 65 printf("Encrypt perf took %s\n",
66 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 66 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
67 GNUNET_YES)); 67 GNUNET_YES));
68 GAUGER ("UTIL", "Symmetric encryption", 68 GAUGER("UTIL", "Symmetric encryption",
69 64 * 1024 / (1 + 69 64 * 1024 / (1 +
70 GNUNET_TIME_absolute_get_duration 70 GNUNET_TIME_absolute_get_duration
71 (start).rel_value_us / 1000LL), "kb/ms"); 71 (start).rel_value_us / 1000LL), "kb/ms");
72 return 0; 72 return 0;
73} 73}
74 74
diff --git a/src/util/perf_malloc.c b/src/util/perf_malloc.c
index 4447934af..ee2281edd 100644
--- a/src/util/perf_malloc.c
+++ b/src/util/perf_malloc.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -28,36 +28,36 @@
28#include <gauger.h> 28#include <gauger.h>
29 29
30static uint64_t 30static uint64_t
31perfMalloc () 31perfMalloc()
32{ 32{
33 size_t i; 33 size_t i;
34 uint64_t ret; 34 uint64_t ret;
35 35
36 ret = 0; 36 ret = 0;
37 for (i=1;i<1024 * 1024;i+=1024) 37 for (i = 1; i < 1024 * 1024; i += 1024)
38 { 38 {
39 ret += i; 39 ret += i;
40 GNUNET_free (GNUNET_malloc (i)); 40 GNUNET_free(GNUNET_malloc(i));
41 } 41 }
42 return ret; 42 return ret;
43} 43}
44 44
45 45
46int 46int
47main (int argc, char *argv[]) 47main(int argc, char *argv[])
48{ 48{
49 struct GNUNET_TIME_Absolute start; 49 struct GNUNET_TIME_Absolute start;
50 uint64_t kb; 50 uint64_t kb;
51 51
52 start = GNUNET_TIME_absolute_get (); 52 start = GNUNET_TIME_absolute_get();
53 kb = perfMalloc (); 53 kb = perfMalloc();
54 printf ("Malloc perf took %s\n", 54 printf("Malloc perf took %s\n",
55 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 55 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
56 GNUNET_YES)); 56 GNUNET_YES));
57 GAUGER ("UTIL", "Allocation", 57 GAUGER("UTIL", "Allocation",
58 kb / 1024 / (1 + 58 kb / 1024 / (1 +
59 GNUNET_TIME_absolute_get_duration 59 GNUNET_TIME_absolute_get_duration
60 (start).rel_value_us / 1000LL), "kb/ms"); 60 (start).rel_value_us / 1000LL), "kb/ms");
61 return 0; 61 return 0;
62} 62}
63 63
diff --git a/src/util/plugin.c b/src/util/plugin.c
index 19169f070..2b11e5c3c 100644
--- a/src/util/plugin.c
+++ b/src/util/plugin.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/plugin.c 22 * @file util/plugin.c
@@ -28,13 +28,12 @@
28#include <ltdl.h> 28#include <ltdl.h>
29#include "gnunet_util_lib.h" 29#include "gnunet_util_lib.h"
30 30
31#define LOG(kind, ...) GNUNET_log_from (kind, "util-plugin", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-plugin", __VA_ARGS__)
32 32
33/** 33/**
34 * Linked list of active plugins. 34 * Linked list of active plugins.
35 */ 35 */
36struct PluginList 36struct PluginList {
37{
38 /** 37 /**
39 * This is a linked list. 38 * This is a linked list.
40 */ 39 */
@@ -72,40 +71,40 @@ static struct PluginList *plugins;
72 * Setup libtool paths. 71 * Setup libtool paths.
73 */ 72 */
74static void 73static void
75plugin_init () 74plugin_init()
76{ 75{
77 int err; 76 int err;
78 const char *opath; 77 const char *opath;
79 char *path; 78 char *path;
80 char *cpath; 79 char *cpath;
81 80
82 err = lt_dlinit (); 81 err = lt_dlinit();
83 if (err > 0) 82 if (err > 0)
84 {
85 fprintf (stderr,
86 _ ("Initialization of plugin mechanism failed: %s!\n"),
87 lt_dlerror ());
88 return;
89 }
90 opath = lt_dlgetsearchpath ();
91 if (NULL != opath)
92 old_dlsearchpath = GNUNET_strdup (opath);
93 path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR);
94 if (NULL != path)
95 {
96 if (NULL != opath)
97 { 83 {
98 GNUNET_asprintf (&cpath, "%s:%s", opath, path); 84 fprintf(stderr,
99 lt_dlsetsearchpath (cpath); 85 _("Initialization of plugin mechanism failed: %s!\n"),
100 GNUNET_free (path); 86 lt_dlerror());
101 GNUNET_free (cpath); 87 return;
102 } 88 }
103 else 89 opath = lt_dlgetsearchpath();
90 if (NULL != opath)
91 old_dlsearchpath = GNUNET_strdup(opath);
92 path = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LIBDIR);
93 if (NULL != path)
104 { 94 {
105 lt_dlsetsearchpath (path); 95 if (NULL != opath)
106 GNUNET_free (path); 96 {
97 GNUNET_asprintf(&cpath, "%s:%s", opath, path);
98 lt_dlsetsearchpath(cpath);
99 GNUNET_free(path);
100 GNUNET_free(cpath);
101 }
102 else
103 {
104 lt_dlsetsearchpath(path);
105 GNUNET_free(path);
106 }
107 } 107 }
108 }
109} 108}
110 109
111 110
@@ -113,15 +112,15 @@ plugin_init ()
113 * Shutdown libtool. 112 * Shutdown libtool.
114 */ 113 */
115static void 114static void
116plugin_fini () 115plugin_fini()
117{ 116{
118 lt_dlsetsearchpath (old_dlsearchpath); 117 lt_dlsetsearchpath(old_dlsearchpath);
119 if (NULL != old_dlsearchpath) 118 if (NULL != old_dlsearchpath)
120 { 119 {
121 GNUNET_free (old_dlsearchpath); 120 GNUNET_free(old_dlsearchpath);
122 old_dlsearchpath = NULL; 121 old_dlsearchpath = NULL;
123 } 122 }
124 lt_dlexit (); 123 lt_dlexit();
125} 124}
126 125
127 126
@@ -133,22 +132,22 @@ plugin_fini ()
133 * @return NULL if the symbol was not found 132 * @return NULL if the symbol was not found
134 */ 133 */
135static GNUNET_PLUGIN_Callback 134static GNUNET_PLUGIN_Callback
136resolve_function (struct PluginList *plug, const char *name) 135resolve_function(struct PluginList *plug, const char *name)
137{ 136{
138 char *initName; 137 char *initName;
139 void *mptr; 138 void *mptr;
140 139
141 GNUNET_asprintf (&initName, "_%s_%s", plug->name, name); 140 GNUNET_asprintf(&initName, "_%s_%s", plug->name, name);
142 mptr = lt_dlsym (plug->handle, &initName[1]); 141 mptr = lt_dlsym(plug->handle, &initName[1]);
143 if (NULL == mptr) 142 if (NULL == mptr)
144 mptr = lt_dlsym (plug->handle, initName); 143 mptr = lt_dlsym(plug->handle, initName);
145 if (NULL == mptr) 144 if (NULL == mptr)
146 LOG (GNUNET_ERROR_TYPE_ERROR, 145 LOG(GNUNET_ERROR_TYPE_ERROR,
147 _ ("`%s' failed to resolve method '%s' with error: %s\n"), 146 _("`%s' failed to resolve method '%s' with error: %s\n"),
148 "lt_dlsym", 147 "lt_dlsym",
149 &initName[1], 148 &initName[1],
150 lt_dlerror ()); 149 lt_dlerror());
151 GNUNET_free (initName); 150 GNUNET_free(initName);
152 return mptr; 151 return mptr;
153} 152}
154 153
@@ -163,30 +162,30 @@ resolve_function (struct PluginList *plug, const char *name)
163 * @return #GNUNET_YES if the plugin exists, #GNUNET_NO if not 162 * @return #GNUNET_YES if the plugin exists, #GNUNET_NO if not
164 */ 163 */
165int 164int
166GNUNET_PLUGIN_test (const char *library_name) 165GNUNET_PLUGIN_test(const char *library_name)
167{ 166{
168 void *libhandle; 167 void *libhandle;
169 GNUNET_PLUGIN_Callback init; 168 GNUNET_PLUGIN_Callback init;
170 struct PluginList plug; 169 struct PluginList plug;
171 170
172 if (! initialized) 171 if (!initialized)
173 { 172 {
174 initialized = GNUNET_YES; 173 initialized = GNUNET_YES;
175 plugin_init (); 174 plugin_init();
176 } 175 }
177 libhandle = lt_dlopenext (library_name); 176 libhandle = lt_dlopenext(library_name);
178 if (NULL == libhandle) 177 if (NULL == libhandle)
179 return GNUNET_NO; 178 return GNUNET_NO;
180 plug.handle = libhandle; 179 plug.handle = libhandle;
181 plug.name = (char *) library_name; 180 plug.name = (char *)library_name;
182 init = resolve_function (&plug, "init"); 181 init = resolve_function(&plug, "init");
183 if (NULL == init) 182 if (NULL == init)
184 { 183 {
185 GNUNET_break (0); 184 GNUNET_break(0);
186 lt_dlclose (libhandle); 185 lt_dlclose(libhandle);
187 return GNUNET_NO; 186 return GNUNET_NO;
188 } 187 }
189 lt_dlclose (libhandle); 188 lt_dlclose(libhandle);
190 return GNUNET_YES; 189 return GNUNET_YES;
191} 190}
192 191
@@ -204,42 +203,42 @@ GNUNET_PLUGIN_test (const char *library_name)
204 * @return whatever the initialization function returned 203 * @return whatever the initialization function returned
205 */ 204 */
206void * 205void *
207GNUNET_PLUGIN_load (const char *library_name, void *arg) 206GNUNET_PLUGIN_load(const char *library_name, void *arg)
208{ 207{
209 void *libhandle; 208 void *libhandle;
210 struct PluginList *plug; 209 struct PluginList *plug;
211 GNUNET_PLUGIN_Callback init; 210 GNUNET_PLUGIN_Callback init;
212 void *ret; 211 void *ret;
213 212
214 if (! initialized) 213 if (!initialized)
215 { 214 {
216 initialized = GNUNET_YES; 215 initialized = GNUNET_YES;
217 plugin_init (); 216 plugin_init();
218 } 217 }
219 libhandle = lt_dlopenext (library_name); 218 libhandle = lt_dlopenext(library_name);
220 if (libhandle == NULL) 219 if (libhandle == NULL)
221 { 220 {
222 LOG (GNUNET_ERROR_TYPE_ERROR, 221 LOG(GNUNET_ERROR_TYPE_ERROR,
223 _ ("`%s' failed for library `%s' with error: %s\n"), 222 _("`%s' failed for library `%s' with error: %s\n"),
224 "lt_dlopenext", 223 "lt_dlopenext",
225 library_name, 224 library_name,
226 lt_dlerror ()); 225 lt_dlerror());
227 return NULL; 226 return NULL;
228 } 227 }
229 plug = GNUNET_new (struct PluginList); 228 plug = GNUNET_new(struct PluginList);
230 plug->handle = libhandle; 229 plug->handle = libhandle;
231 plug->name = GNUNET_strdup (library_name); 230 plug->name = GNUNET_strdup(library_name);
232 plug->next = plugins; 231 plug->next = plugins;
233 plugins = plug; 232 plugins = plug;
234 init = resolve_function (plug, "init"); 233 init = resolve_function(plug, "init");
235 if ((init == NULL) || (NULL == (ret = init (arg)))) 234 if ((init == NULL) || (NULL == (ret = init(arg))))
236 { 235 {
237 lt_dlclose (libhandle); 236 lt_dlclose(libhandle);
238 GNUNET_free (plug->name); 237 GNUNET_free(plug->name);
239 plugins = plug->next; 238 plugins = plug->next;
240 GNUNET_free (plug); 239 GNUNET_free(plug);
241 return NULL; 240 return NULL;
242 } 241 }
243 return ret; 242 return ret;
244} 243}
245 244
@@ -253,7 +252,7 @@ GNUNET_PLUGIN_load (const char *library_name, void *arg)
253 * @return whatever the shutdown function returned 252 * @return whatever the shutdown function returned
254 */ 253 */
255void * 254void *
256GNUNET_PLUGIN_unload (const char *library_name, void *arg) 255GNUNET_PLUGIN_unload(const char *library_name, void *arg)
257{ 256{
258 struct PluginList *pos; 257 struct PluginList *pos;
259 struct PluginList *prev; 258 struct PluginList *prev;
@@ -262,30 +261,30 @@ GNUNET_PLUGIN_unload (const char *library_name, void *arg)
262 261
263 prev = NULL; 262 prev = NULL;
264 pos = plugins; 263 pos = plugins;
265 while ((NULL != pos) && (0 != strcmp (pos->name, library_name))) 264 while ((NULL != pos) && (0 != strcmp(pos->name, library_name)))
266 { 265 {
267 prev = pos; 266 prev = pos;
268 pos = pos->next; 267 pos = pos->next;
269 } 268 }
270 if (NULL == pos) 269 if (NULL == pos)
271 return NULL; 270 return NULL;
272 271
273 done = resolve_function (pos, "done"); 272 done = resolve_function(pos, "done");
274 ret = NULL; 273 ret = NULL;
275 if (NULL != done) 274 if (NULL != done)
276 ret = done (arg); 275 ret = done(arg);
277 if (NULL == prev) 276 if (NULL == prev)
278 plugins = pos->next; 277 plugins = pos->next;
279 else 278 else
280 prev->next = pos->next; 279 prev->next = pos->next;
281 lt_dlclose (pos->handle); 280 lt_dlclose(pos->handle);
282 GNUNET_free (pos->name); 281 GNUNET_free(pos->name);
283 GNUNET_free (pos); 282 GNUNET_free(pos);
284 if (NULL == plugins) 283 if (NULL == plugins)
285 { 284 {
286 plugin_fini (); 285 plugin_fini();
287 initialized = GNUNET_NO; 286 initialized = GNUNET_NO;
288 } 287 }
289 return ret; 288 return ret;
290} 289}
291 290
@@ -293,8 +292,7 @@ GNUNET_PLUGIN_unload (const char *library_name, void *arg)
293/** 292/**
294 * Closure for #find_libraries(). 293 * Closure for #find_libraries().
295 */ 294 */
296struct LoadAllContext 295struct LoadAllContext {
297{
298 /** 296 /**
299 * Prefix the plugin names we find have to match. 297 * Prefix the plugin names we find have to match.
300 */ 298 */
@@ -327,7 +325,7 @@ struct LoadAllContext
327 * @return #GNUNET_OK (continue loading) 325 * @return #GNUNET_OK (continue loading)
328 */ 326 */
329static int 327static int
330find_libraries (void *cls, const char *filename) 328find_libraries(void *cls, const char *filename)
331{ 329{
332 struct LoadAllContext *lac = cls; 330 struct LoadAllContext *lac = cls;
333 const char *slashpos; 331 const char *slashpos;
@@ -338,20 +336,20 @@ find_libraries (void *cls, const char *filename)
338 size_t n; 336 size_t n;
339 337
340 libname = filename; 338 libname = filename;
341 while (NULL != (slashpos = strstr (libname, DIR_SEPARATOR_STR))) 339 while (NULL != (slashpos = strstr(libname, DIR_SEPARATOR_STR)))
342 libname = slashpos + 1; 340 libname = slashpos + 1;
343 n = strlen (libname); 341 n = strlen(libname);
344 if (0 != strncmp (lac->basename, libname, strlen (lac->basename))) 342 if (0 != strncmp(lac->basename, libname, strlen(lac->basename)))
345 return GNUNET_OK; /* wrong name */ 343 return GNUNET_OK; /* wrong name */
346 if ((n > 3) && (0 == strcmp (&libname[n - 3], ".la"))) 344 if ((n > 3) && (0 == strcmp(&libname[n - 3], ".la")))
347 return GNUNET_OK; /* .la file */ 345 return GNUNET_OK; /* .la file */
348 basename = GNUNET_strdup (libname); 346 basename = GNUNET_strdup(libname);
349 if (NULL != (dot = strstr (basename, "."))) 347 if (NULL != (dot = strstr(basename, ".")))
350 *dot = '\0'; 348 *dot = '\0';
351 lib_ret = GNUNET_PLUGIN_load (basename, lac->arg); 349 lib_ret = GNUNET_PLUGIN_load(basename, lac->arg);
352 if (NULL != lib_ret) 350 if (NULL != lib_ret)
353 lac->cb (lac->cb_cls, basename, lib_ret); 351 lac->cb(lac->cb_cls, basename, lib_ret);
354 GNUNET_free (basename); 352 GNUNET_free(basename);
355 return GNUNET_OK; 353 return GNUNET_OK;
356} 354}
357 355
@@ -369,27 +367,27 @@ find_libraries (void *cls, const char *filename)
369 * @param cb_cls closure for @a cb 367 * @param cb_cls closure for @a cb
370 */ 368 */
371void 369void
372GNUNET_PLUGIN_load_all (const char *basename, 370GNUNET_PLUGIN_load_all(const char *basename,
373 void *arg, 371 void *arg,
374 GNUNET_PLUGIN_LoaderCallback cb, 372 GNUNET_PLUGIN_LoaderCallback cb,
375 void *cb_cls) 373 void *cb_cls)
376{ 374{
377 struct LoadAllContext lac; 375 struct LoadAllContext lac;
378 char *path; 376 char *path;
379 377
380 path = GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LIBDIR); 378 path = GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LIBDIR);
381 if (NULL == path) 379 if (NULL == path)
382 { 380 {
383 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 381 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
384 _ ("Could not determine plugin installation path.\n")); 382 _("Could not determine plugin installation path.\n"));
385 return; 383 return;
386 } 384 }
387 lac.basename = basename; 385 lac.basename = basename;
388 lac.arg = arg; 386 lac.arg = arg;
389 lac.cb = cb; 387 lac.cb = cb;
390 lac.cb_cls = cb_cls; 388 lac.cb_cls = cb_cls;
391 GNUNET_DISK_directory_scan (path, &find_libraries, &lac); 389 GNUNET_DISK_directory_scan(path, &find_libraries, &lac);
392 GNUNET_free (path); 390 GNUNET_free(path);
393} 391}
394 392
395 393
diff --git a/src/util/proc_compat.c b/src/util/proc_compat.c
index 7abea446a..3d73d7889 100644
--- a/src/util/proc_compat.c
+++ b/src/util/proc_compat.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20#include "platform.h" 20#include "platform.h"
21 21
22/** 22/**
@@ -35,16 +35,16 @@
35 * @param n search character limit 35 * @param n search character limit
36 */ 36 */
37void* 37void*
38GN_memrchr_ (const void *s, 38GN_memrchr_(const void *s,
39 int c, 39 int c,
40 size_t n) 40 size_t n)
41{ 41{
42 const unsigned char *ucs = s; 42 const unsigned char *ucs = s;
43 ssize_t i; 43 ssize_t i;
44 44
45 for (i = n - 1; i >= 0; i--) 45 for (i = n - 1; i >= 0; i--)
46 if (c == (int) ucs[i]) 46 if (c == (int)ucs[i])
47 return (void *) &ucs[i]; 47 return (void *)&ucs[i];
48 return NULL; 48 return NULL;
49} 49}
50 50
diff --git a/src/util/program.c b/src/util/program.c
index 77f4ea3ae..9bd3d64f9 100644
--- a/src/util/program.c
+++ b/src/util/program.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/program.c 22 * @file util/program.c
@@ -31,16 +31,15 @@
31#include "speedup.h" 31#include "speedup.h"
32#include <gcrypt.h> 32#include <gcrypt.h>
33 33
34#define LOG(kind, ...) GNUNET_log_from (kind, "util-program", __VA_ARGS__) 34#define LOG(kind, ...) GNUNET_log_from(kind, "util-program", __VA_ARGS__)
35 35
36#define LOG_STRERROR_FILE(kind, syscall, filename) \ 36#define LOG_STRERROR_FILE(kind, syscall, filename) \
37 GNUNET_log_from_strerror_file (kind, "util-program", syscall, filename) 37 GNUNET_log_from_strerror_file(kind, "util-program", syscall, filename)
38 38
39/** 39/**
40 * Context for the command. 40 * Context for the command.
41 */ 41 */
42struct CommandContext 42struct CommandContext {
43{
44 /** 43 /**
45 * Argv argument. 44 * Argv argument.
46 */ 45 */
@@ -72,10 +71,10 @@ struct CommandContext
72 * task run when the scheduler shuts down 71 * task run when the scheduler shuts down
73 */ 72 */
74static void 73static void
75shutdown_task (void *cls) 74shutdown_task(void *cls)
76{ 75{
77 (void) cls; 76 (void)cls;
78 GNUNET_SPEEDUP_stop_ (); 77 GNUNET_SPEEDUP_stop_();
79} 78}
80 79
81 80
@@ -84,14 +83,14 @@ shutdown_task (void *cls)
84 * program. Runs the program-specific main task. 83 * program. Runs the program-specific main task.
85 */ 84 */
86static void 85static void
87program_main (void *cls) 86program_main(void *cls)
88{ 87{
89 struct CommandContext *cc = cls; 88 struct CommandContext *cc = cls;
90 89
91 GNUNET_SPEEDUP_start_ (cc->cfg); 90 GNUNET_SPEEDUP_start_(cc->cfg);
92 GNUNET_SCHEDULER_add_shutdown (&shutdown_task, NULL); 91 GNUNET_SCHEDULER_add_shutdown(&shutdown_task, NULL);
93 GNUNET_RESOLVER_connect (cc->cfg); 92 GNUNET_RESOLVER_connect(cc->cfg);
94 cc->task (cc->task_cls, cc->args, cc->cfgfile, cc->cfg); 93 cc->task(cc->task_cls, cc->args, cc->cfgfile, cc->cfg);
95} 94}
96 95
97 96
@@ -103,16 +102,16 @@ program_main (void *cls)
103 * @param a2 second command line option 102 * @param a2 second command line option
104 */ 103 */
105static int 104static int
106cmd_sorter (const void *a1, const void *a2) 105cmd_sorter(const void *a1, const void *a2)
107{ 106{
108 const struct GNUNET_GETOPT_CommandLineOption *c1 = a1; 107 const struct GNUNET_GETOPT_CommandLineOption *c1 = a1;
109 const struct GNUNET_GETOPT_CommandLineOption *c2 = a2; 108 const struct GNUNET_GETOPT_CommandLineOption *c2 = a2;
110 109
111 if (toupper ((unsigned char) c1->shortName) > 110 if (toupper((unsigned char)c1->shortName) >
112 toupper ((unsigned char) c2->shortName)) 111 toupper((unsigned char)c2->shortName))
113 return 1; 112 return 1;
114 if (toupper ((unsigned char) c1->shortName) < 113 if (toupper((unsigned char)c1->shortName) <
115 toupper ((unsigned char) c2->shortName)) 114 toupper((unsigned char)c2->shortName))
116 return -1; 115 return -1;
117 if (c1->shortName > c2->shortName) 116 if (c1->shortName > c2->shortName)
118 return 1; 117 return 1;
@@ -138,16 +137,17 @@ cmd_sorter (const void *a1, const void *a2)
138 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 137 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
139 */ 138 */
140int 139int
141GNUNET_PROGRAM_run2 (int argc, 140GNUNET_PROGRAM_run2(int argc,
142 char *const *argv, 141 char *const *argv,
143 const char *binaryName, 142 const char *binaryName,
144 const char *binaryHelp, 143 const char *binaryHelp,
145 const struct GNUNET_GETOPT_CommandLineOption *options, 144 const struct GNUNET_GETOPT_CommandLineOption *options,
146 GNUNET_PROGRAM_Main task, 145 GNUNET_PROGRAM_Main task,
147 void *task_cls, 146 void *task_cls,
148 int run_without_scheduler) 147 int run_without_scheduler)
149{ 148{
150 struct CommandContext cc; 149 struct CommandContext cc;
150
151#if ENABLE_NLS 151#if ENABLE_NLS
152 char *path; 152 char *path;
153#endif 153#endif
@@ -161,191 +161,191 @@ GNUNET_PROGRAM_run2 (int argc,
161 unsigned long long skew_variance; 161 unsigned long long skew_variance;
162 long long clock_offset; 162 long long clock_offset;
163 struct GNUNET_CONFIGURATION_Handle *cfg; 163 struct GNUNET_CONFIGURATION_Handle *cfg;
164 const struct GNUNET_OS_ProjectData *pd = GNUNET_OS_project_data_get (); 164 const struct GNUNET_OS_ProjectData *pd = GNUNET_OS_project_data_get();
165 struct GNUNET_GETOPT_CommandLineOption defoptions[] = 165 struct GNUNET_GETOPT_CommandLineOption defoptions[] =
166 {GNUNET_GETOPT_option_cfgfile (&cc.cfgfile), 166 { GNUNET_GETOPT_option_cfgfile(&cc.cfgfile),
167 GNUNET_GETOPT_option_help (binaryHelp), 167 GNUNET_GETOPT_option_help(binaryHelp),
168 GNUNET_GETOPT_option_loglevel (&loglev), 168 GNUNET_GETOPT_option_loglevel(&loglev),
169 GNUNET_GETOPT_option_logfile (&logfile), 169 GNUNET_GETOPT_option_logfile(&logfile),
170 GNUNET_GETOPT_option_version (pd->version)}; 170 GNUNET_GETOPT_option_version(pd->version) };
171 struct GNUNET_GETOPT_CommandLineOption *allopts; 171 struct GNUNET_GETOPT_CommandLineOption *allopts;
172 const char *gargs; 172 const char *gargs;
173 char *lpfx; 173 char *lpfx;
174 char *spc; 174 char *spc;
175 175
176 logfile = NULL; 176 logfile = NULL;
177 gargs = getenv ("GNUNET_ARGS"); 177 gargs = getenv("GNUNET_ARGS");
178 if (NULL != gargs) 178 if (NULL != gargs)
179 { 179 {
180 char **gargv; 180 char **gargv;
181 unsigned int gargc; 181 unsigned int gargc;
182 char *cargs; 182 char *cargs;
183 183
184 gargv = NULL; 184 gargv = NULL;
185 gargc = 0; 185 gargc = 0;
186 for (int i = 0; i < argc; i++) 186 for (int i = 0; i < argc; i++)
187 GNUNET_array_append (gargv, gargc, GNUNET_strdup (argv[i])); 187 GNUNET_array_append(gargv, gargc, GNUNET_strdup(argv[i]));
188 cargs = GNUNET_strdup (gargs); 188 cargs = GNUNET_strdup(gargs);
189 for (char *tok = strtok (cargs, " "); NULL != tok; tok = strtok (NULL, " ")) 189 for (char *tok = strtok(cargs, " "); NULL != tok; tok = strtok(NULL, " "))
190 GNUNET_array_append (gargv, gargc, GNUNET_strdup (tok)); 190 GNUNET_array_append(gargv, gargc, GNUNET_strdup(tok));
191 GNUNET_free (cargs); 191 GNUNET_free(cargs);
192 GNUNET_array_append (gargv, gargc, NULL); 192 GNUNET_array_append(gargv, gargc, NULL);
193 argv = (char *const *) gargv; 193 argv = (char *const *)gargv;
194 argc = gargc - 1; 194 argc = gargc - 1;
195 } 195 }
196 memset (&cc, 0, sizeof (cc)); 196 memset(&cc, 0, sizeof(cc));
197 loglev = NULL; 197 loglev = NULL;
198 cc.task = task; 198 cc.task = task;
199 cc.task_cls = task_cls; 199 cc.task_cls = task_cls;
200 cc.cfg = cfg = GNUNET_CONFIGURATION_create (); 200 cc.cfg = cfg = GNUNET_CONFIGURATION_create();
201 /* prepare */ 201 /* prepare */
202#if ENABLE_NLS 202#if ENABLE_NLS
203 if (NULL != pd->gettext_domain) 203 if (NULL != pd->gettext_domain)
204 {
205 setlocale (LC_ALL, "");
206 path = (NULL == pd->gettext_path)
207 ? GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR)
208 : GNUNET_strdup (pd->gettext_path);
209 if (NULL != path)
210 { 204 {
211 bindtextdomain (pd->gettext_domain, path); 205 setlocale(LC_ALL, "");
212 GNUNET_free (path); 206 path = (NULL == pd->gettext_path)
207 ? GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LOCALEDIR)
208 : GNUNET_strdup(pd->gettext_path);
209 if (NULL != path)
210 {
211 bindtextdomain(pd->gettext_domain, path);
212 GNUNET_free(path);
213 }
214 textdomain(pd->gettext_domain);
213 } 215 }
214 textdomain (pd->gettext_domain);
215 }
216#endif 216#endif
217 cnt = 0; 217 cnt = 0;
218 while (NULL != options[cnt].name) 218 while (NULL != options[cnt].name)
219 cnt++; 219 cnt++;
220 allopts = 220 allopts =
221 GNUNET_malloc ((cnt + 1) * sizeof (struct GNUNET_GETOPT_CommandLineOption) + 221 GNUNET_malloc((cnt + 1) * sizeof(struct GNUNET_GETOPT_CommandLineOption) +
222 sizeof (defoptions)); 222 sizeof(defoptions));
223 GNUNET_memcpy (allopts, defoptions, sizeof (defoptions)); 223 GNUNET_memcpy(allopts, defoptions, sizeof(defoptions));
224 GNUNET_memcpy (&allopts[sizeof (defoptions) / 224 GNUNET_memcpy(&allopts[sizeof(defoptions) /
225 sizeof (struct GNUNET_GETOPT_CommandLineOption)], 225 sizeof(struct GNUNET_GETOPT_CommandLineOption)],
226 options, 226 options,
227 (cnt + 1) * sizeof (struct GNUNET_GETOPT_CommandLineOption)); 227 (cnt + 1) * sizeof(struct GNUNET_GETOPT_CommandLineOption));
228 cnt += sizeof (defoptions) / sizeof (struct GNUNET_GETOPT_CommandLineOption); 228 cnt += sizeof(defoptions) / sizeof(struct GNUNET_GETOPT_CommandLineOption);
229 qsort (allopts, 229 qsort(allopts,
230 cnt, 230 cnt,
231 sizeof (struct GNUNET_GETOPT_CommandLineOption), 231 sizeof(struct GNUNET_GETOPT_CommandLineOption),
232 &cmd_sorter); 232 &cmd_sorter);
233 loglev = NULL; 233 loglev = NULL;
234 xdg = getenv ("XDG_CONFIG_HOME"); 234 xdg = getenv("XDG_CONFIG_HOME");
235 if (NULL != xdg) 235 if (NULL != xdg)
236 GNUNET_asprintf (&cfg_fn, 236 GNUNET_asprintf(&cfg_fn,
237 "%s%s%s", 237 "%s%s%s",
238 xdg, 238 xdg,
239 DIR_SEPARATOR_STR, 239 DIR_SEPARATOR_STR,
240 pd->config_file); 240 pd->config_file);
241 else 241 else
242 cfg_fn = GNUNET_strdup (pd->user_config_file); 242 cfg_fn = GNUNET_strdup(pd->user_config_file);
243 lpfx = GNUNET_strdup (binaryName); 243 lpfx = GNUNET_strdup(binaryName);
244 if (NULL != (spc = strstr (lpfx, " "))) 244 if (NULL != (spc = strstr(lpfx, " ")))
245 *spc = '\0'; 245 *spc = '\0';
246 ret = GNUNET_GETOPT_run (binaryName, allopts, (unsigned int) argc, argv); 246 ret = GNUNET_GETOPT_run(binaryName, allopts, (unsigned int)argc, argv);
247 if ((GNUNET_OK > ret) || 247 if ((GNUNET_OK > ret) ||
248 (GNUNET_OK != GNUNET_log_setup (lpfx, loglev, logfile))) 248 (GNUNET_OK != GNUNET_log_setup(lpfx, loglev, logfile)))
249 {
250 GNUNET_free (allopts);
251 GNUNET_free (lpfx);
252 goto cleanup;
253 }
254 if (NULL != cc.cfgfile)
255 {
256 if ((GNUNET_YES != GNUNET_DISK_file_test (cc.cfgfile)) ||
257 (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, cc.cfgfile)))
258 { 249 {
259 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 250 GNUNET_free(allopts);
260 _ ( 251 GNUNET_free(lpfx);
261 "Unreadable or malformed configuration file `%s', exit ...\n"),
262 cc.cfgfile);
263 ret = GNUNET_SYSERR;
264 GNUNET_free (allopts);
265 GNUNET_free (lpfx);
266 goto cleanup; 252 goto cleanup;
267 } 253 }
268 } 254 if (NULL != cc.cfgfile)
269 else
270 {
271 if (GNUNET_YES == GNUNET_DISK_file_test (cfg_fn))
272 { 255 {
273 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, cfg_fn)) 256 if ((GNUNET_YES != GNUNET_DISK_file_test(cc.cfgfile)) ||
274 { 257 (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, cc.cfgfile)))
275 GNUNET_log ( 258 {
276 GNUNET_ERROR_TYPE_ERROR, 259 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
277 _ ( 260 _(
278 "Unreadable or malformed default configuration file `%s', exit ...\n"), 261 "Unreadable or malformed configuration file `%s', exit ...\n"),
279 cfg_fn); 262 cc.cfgfile);
280 ret = GNUNET_SYSERR; 263 ret = GNUNET_SYSERR;
281 GNUNET_free (allopts); 264 GNUNET_free(allopts);
282 GNUNET_free (lpfx); 265 GNUNET_free(lpfx);
283 goto cleanup; 266 goto cleanup;
284 } 267 }
285 } 268 }
286 else 269 else
287 { 270 {
288 GNUNET_free (cfg_fn); 271 if (GNUNET_YES == GNUNET_DISK_file_test(cfg_fn))
289 cfg_fn = NULL; 272 {
290 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg, NULL)) 273 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, cfg_fn))
291 { 274 {
292 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 275 GNUNET_log(
293 _ ("Unreadable or malformed configuration, exit ...\n")); 276 GNUNET_ERROR_TYPE_ERROR,
294 ret = GNUNET_SYSERR; 277 _(
295 GNUNET_free (allopts); 278 "Unreadable or malformed default configuration file `%s', exit ...\n"),
296 GNUNET_free (lpfx); 279 cfg_fn);
297 goto cleanup; 280 ret = GNUNET_SYSERR;
298 } 281 GNUNET_free(allopts);
282 GNUNET_free(lpfx);
283 goto cleanup;
284 }
285 }
286 else
287 {
288 GNUNET_free(cfg_fn);
289 cfg_fn = NULL;
290 if (GNUNET_OK != GNUNET_CONFIGURATION_load(cfg, NULL))
291 {
292 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
293 _("Unreadable or malformed configuration, exit ...\n"));
294 ret = GNUNET_SYSERR;
295 GNUNET_free(allopts);
296 GNUNET_free(lpfx);
297 goto cleanup;
298 }
299 }
299 } 300 }
300 } 301 GNUNET_free(allopts);
301 GNUNET_free (allopts); 302 GNUNET_free(lpfx);
302 GNUNET_free (lpfx); 303 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cc.cfg,
303 if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cc.cfg, 304 "testing",
305 "skew_offset",
306 &skew_offset) &&
307 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(cc.cfg,
304 "testing", 308 "testing",
305 "skew_offset", 309 "skew_variance",
306 &skew_offset) && 310 &skew_variance)))
307 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (cc.cfg, 311 {
308 "testing", 312 clock_offset = skew_offset - skew_variance;
309 "skew_variance", 313 GNUNET_TIME_set_offset(clock_offset);
310 &skew_variance))) 314 }
311 {
312 clock_offset = skew_offset - skew_variance;
313 GNUNET_TIME_set_offset (clock_offset);
314 }
315 /* ARM needs to know which configuration file to use when starting 315 /* ARM needs to know which configuration file to use when starting
316 services. If we got a command-line option *and* if nothing is 316 services. If we got a command-line option *and* if nothing is
317 specified in the configuration, remember the command-line option 317 specified in the configuration, remember the command-line option
318 in "cfg". This is typically really only having an effect if we 318 in "cfg". This is typically really only having an effect if we
319 are running code in src/arm/, as obviously the rest of the code 319 are running code in src/arm/, as obviously the rest of the code
320 has little business with ARM-specific options. */ 320 has little business with ARM-specific options. */
321 if (GNUNET_YES != GNUNET_CONFIGURATION_have_value (cfg, "arm", "CONFIG")) 321 if (GNUNET_YES != GNUNET_CONFIGURATION_have_value(cfg, "arm", "CONFIG"))
322 { 322 {
323 if (NULL != cc.cfgfile) 323 if (NULL != cc.cfgfile)
324 GNUNET_CONFIGURATION_set_value_string (cfg, "arm", "CONFIG", cc.cfgfile); 324 GNUNET_CONFIGURATION_set_value_string(cfg, "arm", "CONFIG", cc.cfgfile);
325 else if (NULL != cfg_fn) 325 else if (NULL != cfg_fn)
326 GNUNET_CONFIGURATION_set_value_string (cfg, "arm", "CONFIG", cfg_fn); 326 GNUNET_CONFIGURATION_set_value_string(cfg, "arm", "CONFIG", cfg_fn);
327 } 327 }
328 328
329 /* run */ 329 /* run */
330 cc.args = &argv[ret]; 330 cc.args = &argv[ret];
331 if ((NULL == cc.cfgfile) && (NULL != cfg_fn)) 331 if ((NULL == cc.cfgfile) && (NULL != cfg_fn))
332 cc.cfgfile = GNUNET_strdup (cfg_fn); 332 cc.cfgfile = GNUNET_strdup(cfg_fn);
333 if (GNUNET_NO == run_without_scheduler) 333 if (GNUNET_NO == run_without_scheduler)
334 { 334 {
335 GNUNET_SCHEDULER_run (&program_main, &cc); 335 GNUNET_SCHEDULER_run(&program_main, &cc);
336 } 336 }
337 else 337 else
338 { 338 {
339 GNUNET_RESOLVER_connect (cc.cfg); 339 GNUNET_RESOLVER_connect(cc.cfg);
340 cc.task (cc.task_cls, cc.args, cc.cfgfile, cc.cfg); 340 cc.task(cc.task_cls, cc.args, cc.cfgfile, cc.cfg);
341 } 341 }
342 ret = GNUNET_OK; 342 ret = GNUNET_OK;
343cleanup: 343cleanup:
344 GNUNET_CONFIGURATION_destroy (cfg); 344 GNUNET_CONFIGURATION_destroy(cfg);
345 GNUNET_free_non_null (cc.cfgfile); 345 GNUNET_free_non_null(cc.cfgfile);
346 GNUNET_free_non_null (cfg_fn); 346 GNUNET_free_non_null(cfg_fn);
347 GNUNET_free_non_null (loglev); 347 GNUNET_free_non_null(loglev);
348 GNUNET_free_non_null (logfile); 348 GNUNET_free_non_null(logfile);
349 return ret; 349 return ret;
350} 350}
351 351
@@ -364,22 +364,22 @@ cleanup:
364 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success 364 * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
365 */ 365 */
366int 366int
367GNUNET_PROGRAM_run (int argc, 367GNUNET_PROGRAM_run(int argc,
368 char *const *argv, 368 char *const *argv,
369 const char *binaryName, 369 const char *binaryName,
370 const char *binaryHelp, 370 const char *binaryHelp,
371 const struct GNUNET_GETOPT_CommandLineOption *options, 371 const struct GNUNET_GETOPT_CommandLineOption *options,
372 GNUNET_PROGRAM_Main task, 372 GNUNET_PROGRAM_Main task,
373 void *task_cls) 373 void *task_cls)
374{ 374{
375 return GNUNET_PROGRAM_run2 (argc, 375 return GNUNET_PROGRAM_run2(argc,
376 argv, 376 argv,
377 binaryName, 377 binaryName,
378 binaryHelp, 378 binaryHelp,
379 options, 379 options,
380 task, 380 task,
381 task_cls, 381 task_cls,
382 GNUNET_NO); 382 GNUNET_NO);
383} 383}
384 384
385 385
diff --git a/src/util/regex.c b/src/util/regex.c
index 70bf5c485..24e83cfd1 100644
--- a/src/util/regex.c
+++ b/src/util/regex.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file src/tun/regex.c 21 * @file src/tun/regex.c
22 * @brief functions to convert IP networks to regexes 22 * @brief functions to convert IP networks to regexes
@@ -42,15 +42,15 @@
42 * bytes long. 42 * bytes long.
43 */ 43 */
44void 44void
45GNUNET_TUN_ipv4toregexsearch (const struct in_addr *ip, 45GNUNET_TUN_ipv4toregexsearch(const struct in_addr *ip,
46 uint16_t port, 46 uint16_t port,
47 char *rxstr) 47 char *rxstr)
48{ 48{
49 GNUNET_snprintf (rxstr, 49 GNUNET_snprintf(rxstr,
50 GNUNET_TUN_IPV4_REGEXLEN, 50 GNUNET_TUN_IPV4_REGEXLEN,
51 "4-%04X-%08X", 51 "4-%04X-%08X",
52 (unsigned int) port, 52 (unsigned int)port,
53 ntohl (ip->s_addr)); 53 ntohl(ip->s_addr));
54} 54}
55 55
56 56
@@ -63,21 +63,21 @@ GNUNET_TUN_ipv4toregexsearch (const struct in_addr *ip,
63 * bytes long. 63 * bytes long.
64 */ 64 */
65void 65void
66GNUNET_TUN_ipv6toregexsearch (const struct in6_addr *ipv6, 66GNUNET_TUN_ipv6toregexsearch(const struct in6_addr *ipv6,
67 uint16_t port, 67 uint16_t port,
68 char *rxstr) 68 char *rxstr)
69{ 69{
70 const uint32_t *addr; 70 const uint32_t *addr;
71 71
72 addr = (const uint32_t *) ipv6; 72 addr = (const uint32_t *)ipv6;
73 GNUNET_snprintf (rxstr, 73 GNUNET_snprintf(rxstr,
74 GNUNET_TUN_IPV6_REGEXLEN, 74 GNUNET_TUN_IPV6_REGEXLEN,
75 "6-%04X-%08X%08X%08X%08X", 75 "6-%04X-%08X%08X%08X%08X",
76 (unsigned int) port, 76 (unsigned int)port,
77 ntohl (addr[0]), 77 ntohl(addr[0]),
78 ntohl (addr[1]), 78 ntohl(addr[1]),
79 ntohl (addr[2]), 79 ntohl(addr[2]),
80 ntohl (addr[3])); 80 ntohl(addr[3]));
81} 81}
82 82
83 83
@@ -88,54 +88,59 @@ GNUNET_TUN_ipv6toregexsearch (const struct in6_addr *ipv6,
88 * @param mask which bits in value are wildcards (any value)? 88 * @param mask which bits in value are wildcards (any value)?
89 */ 89 */
90static char * 90static char *
91nibble_to_regex (uint8_t value, 91nibble_to_regex(uint8_t value,
92 uint8_t mask) 92 uint8_t mask)
93{ 93{
94 char *ret; 94 char *ret;
95 95
96 value &= mask; 96 value &= mask;
97 switch (mask) 97 switch (mask)
98 { 98 {
99 case 0: 99 case 0:
100 return GNUNET_strdup (DOT); 100 return GNUNET_strdup(DOT);
101 case 8: 101
102 GNUNET_asprintf (&ret, 102 case 8:
103 "(%X|%X|%X|%X|%X|%X|%X|%X)", 103 GNUNET_asprintf(&ret,
104 value, 104 "(%X|%X|%X|%X|%X|%X|%X|%X)",
105 value + 1, 105 value,
106 value + 2, 106 value + 1,
107 value + 3, 107 value + 2,
108 value + 4, 108 value + 3,
109 value + 5, 109 value + 4,
110 value + 6, 110 value + 5,
111 value + 7); 111 value + 6,
112 return ret; 112 value + 7);
113 case 12: 113 return ret;
114 GNUNET_asprintf (&ret, 114
115 "(%X|%X|%X|%X)", 115 case 12:
116 value, 116 GNUNET_asprintf(&ret,
117 value + 1, 117 "(%X|%X|%X|%X)",
118 value + 2, 118 value,
119 value + 3); 119 value + 1,
120 return ret; 120 value + 2,
121 case 14: 121 value + 3);
122 GNUNET_asprintf (&ret, 122 return ret;
123 "(%X|%X)", 123
124 value, 124 case 14:
125 value + 1); 125 GNUNET_asprintf(&ret,
126 return ret; 126 "(%X|%X)",
127 case 15: 127 value,
128 GNUNET_asprintf (&ret, 128 value + 1);
129 "%X", 129 return ret;
130 value); 130
131 return ret; 131 case 15:
132 default: 132 GNUNET_asprintf(&ret,
133 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 133 "%X",
134 _("Bad mask: %d\n"), 134 value);
135 mask); 135 return ret;
136 GNUNET_break (0); 136
137 return NULL; 137 default:
138 } 138 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
139 _("Bad mask: %d\n"),
140 mask);
141 GNUNET_break(0);
142 return NULL;
143 }
139} 144}
140 145
141 146
@@ -146,33 +151,33 @@ nibble_to_regex (uint8_t value,
146 * @param mask which bits in value are wildcards (any value)? 151 * @param mask which bits in value are wildcards (any value)?
147 */ 152 */
148static char * 153static char *
149num_to_regex (uint16_t value, 154num_to_regex(uint16_t value,
150 uint16_t mask) 155 uint16_t mask)
151{ 156{
152 const uint8_t *v = (const uint8_t *) &value; 157 const uint8_t *v = (const uint8_t *)&value;
153 const uint8_t *m = (const uint8_t *) &mask; 158 const uint8_t *m = (const uint8_t *)&mask;
154 char *a; 159 char *a;
155 char *b; 160 char *b;
156 char *c; 161 char *c;
157 char *d; 162 char *d;
158 char *ret; 163 char *ret;
159 164
160 a = nibble_to_regex (v[0] >> 4, m[0] >> 4); 165 a = nibble_to_regex(v[0] >> 4, m[0] >> 4);
161 b = nibble_to_regex (v[0] & 15, m[0] & 15); 166 b = nibble_to_regex(v[0] & 15, m[0] & 15);
162 c = nibble_to_regex (v[1] >> 4, m[1] >> 4); 167 c = nibble_to_regex(v[1] >> 4, m[1] >> 4);
163 d = nibble_to_regex (v[1] & 15, m[1] & 15); 168 d = nibble_to_regex(v[1] & 15, m[1] & 15);
164 ret = NULL; 169 ret = NULL;
165 if ( (NULL != a) && 170 if ((NULL != a) &&
166 (NULL != b) && 171 (NULL != b) &&
167 (NULL != c) && 172 (NULL != c) &&
168 (NULL != d) ) 173 (NULL != d))
169 GNUNET_asprintf (&ret, 174 GNUNET_asprintf(&ret,
170 "%s%s%s%s", 175 "%s%s%s%s",
171 a, b, c, d); 176 a, b, c, d);
172 GNUNET_free_non_null (a); 177 GNUNET_free_non_null(a);
173 GNUNET_free_non_null (b); 178 GNUNET_free_non_null(b);
174 GNUNET_free_non_null (c); 179 GNUNET_free_non_null(c);
175 GNUNET_free_non_null (d); 180 GNUNET_free_non_null(d);
176 return ret; 181 return ret;
177} 182}
178 183
@@ -185,33 +190,36 @@ num_to_regex (uint16_t value,
185 * #GNUNET_NO if not 190 * #GNUNET_NO if not
186 */ 191 */
187static int 192static int
188needs_parens (const char *arg) 193needs_parens(const char *arg)
189{ 194{
190 size_t off; 195 size_t off;
191 size_t len; 196 size_t len;
192 unsigned int op; 197 unsigned int op;
193 198
194 op = 0; 199 op = 0;
195 len = strlen (arg); 200 len = strlen(arg);
196 for (off=0;off<len;off++) 201 for (off = 0; off < len; off++)
197 {
198 switch (arg[off])
199 { 202 {
200 case '(': 203 switch (arg[off])
201 op++; 204 {
202 break; 205 case '(':
203 case ')': 206 op++;
204 GNUNET_assert (op > 0); 207 break;
205 op--; 208
206 break; 209 case ')':
207 case '|': 210 GNUNET_assert(op > 0);
208 if (0 == op) 211 op--;
209 return GNUNET_YES; 212 break;
210 break; 213
211 default: 214 case '|':
212 break; 215 if (0 == op)
216 return GNUNET_YES;
217 break;
218
219 default:
220 break;
221 }
213 } 222 }
214 }
215 return GNUNET_NO; 223 return GNUNET_NO;
216} 224}
217 225
@@ -227,21 +235,21 @@ needs_parens (const char *arg)
227 * @return corresponding regex 235 * @return corresponding regex
228 */ 236 */
229static char * 237static char *
230compute_policy (unsigned int start, 238compute_policy(unsigned int start,
231 unsigned int end, 239 unsigned int end,
232 unsigned int step, 240 unsigned int step,
233 const struct GNUNET_STRINGS_PortPolicy *pp) 241 const struct GNUNET_STRINGS_PortPolicy *pp)
234{ 242{
235 unsigned int i; 243 unsigned int i;
236 char before[36]; /* 16 * 2 + 3 dots + 0-terminator */ 244 char before[36]; /* 16 * 2 + 3 dots + 0-terminator */
237 char middlel[33]; /* 16 * 2 + 0-terminator */ 245 char middlel[33]; /* 16 * 2 + 0-terminator */
238 char middleh[33]; /* 16 * 2 + 0-terminator */ 246 char middleh[33]; /* 16 * 2 + 0-terminator */
239 char after[36]; /* 16 * 2 + 3 dots + 0-terminator */ 247 char after[36]; /* 16 * 2 + 3 dots + 0-terminator */
240 char beforep[36+2]; /* 16 * 2 + 3 dots + 0-terminator + ()*/ 248 char beforep[36 + 2]; /* 16 * 2 + 3 dots + 0-terminator + ()*/
241 char middlehp[33+2]; /* 16 * 2 + 0-terminator + () */ 249 char middlehp[33 + 2]; /* 16 * 2 + 0-terminator + () */
242 char middlelp[33+2]; /* 16 * 2 + 0-terminator + () */ 250 char middlelp[33 + 2]; /* 16 * 2 + 0-terminator + () */
243 char afterp[36+2]; /* 16 * 2 + 3 dots + 0-terminator + () */ 251 char afterp[36 + 2]; /* 16 * 2 + 3 dots + 0-terminator + () */
244 char dots[5 * strlen (DOT)]; 252 char dots[5 * strlen(DOT)];
245 char buf[3]; 253 char buf[3];
246 char *middle; 254 char *middle;
247 char *ret; 255 char *ret;
@@ -253,248 +261,248 @@ compute_policy (unsigned int start,
253 unsigned int start_port; 261 unsigned int start_port;
254 unsigned int end_port; 262 unsigned int end_port;
255 263
256 GNUNET_assert (GNUNET_YES == pp->negate_portrange); 264 GNUNET_assert(GNUNET_YES == pp->negate_portrange);
257 start_port = pp->start_port; 265 start_port = pp->start_port;
258 if (1 == start_port) 266 if (1 == start_port)
259 start_port = 0; 267 start_port = 0;
260 end_port = pp->end_port; 268 end_port = pp->end_port;
261 GNUNET_assert ((end - start) / step <= 0xF); 269 GNUNET_assert((end - start) / step <= 0xF);
262 before[0] = '\0'; 270 before[0] = '\0';
263 middlel[0] = '\0'; 271 middlel[0] = '\0';
264 middleh[0] = '\0'; 272 middleh[0] = '\0';
265 after[0] = '\0'; 273 after[0] = '\0';
266 for (i=start;i<=end;i+=step) 274 for (i = start; i <= end; i += step)
267 { 275 {
268 GNUNET_snprintf (buf, 276 GNUNET_snprintf(buf,
269 sizeof (buf), 277 sizeof(buf),
270 "%X|", 278 "%X|",
271 (i - start) / step); 279 (i - start) / step);
272 if (i / step < start_port / step) 280 if (i / step < start_port / step)
273 strcat (before, buf); 281 strcat(before, buf);
274 else if (i / step > end_port / step) 282 else if (i / step > end_port / step)
275 strcat (after, buf); 283 strcat(after, buf);
276 else if (i / step == start_port / step) 284 else if (i / step == start_port / step)
277 strcat (middlel, buf); 285 strcat(middlel, buf);
278 else if (i / step == end_port / step) 286 else if (i / step == end_port / step)
279 strcat (middleh, buf); 287 strcat(middleh, buf);
280 } 288 }
281 if (strlen (before) > 0) 289 if (strlen(before) > 0)
282 before[strlen (before)-1] = '\0'; 290 before[strlen(before) - 1] = '\0';
283 if (strlen (middlel) > 0) 291 if (strlen(middlel) > 0)
284 middlel[strlen (middlel)-1] = '\0'; 292 middlel[strlen(middlel) - 1] = '\0';
285 if (strlen (middleh) > 0) 293 if (strlen(middleh) > 0)
286 middleh[strlen (middleh)-1] = '\0'; 294 middleh[strlen(middleh) - 1] = '\0';
287 if (strlen (after) > 0) 295 if (strlen(after) > 0)
288 after[strlen (after)-1] = '\0'; 296 after[strlen(after) - 1] = '\0';
289 if (needs_parens (before)) 297 if (needs_parens(before))
290 GNUNET_snprintf (beforep, 298 GNUNET_snprintf(beforep,
291 sizeof (beforep), 299 sizeof(beforep),
292 "(%s)", 300 "(%s)",
293 before); 301 before);
294 else 302 else
295 strcpy (beforep, before); 303 strcpy(beforep, before);
296 if (needs_parens (middlel)) 304 if (needs_parens(middlel))
297 GNUNET_snprintf (middlelp, 305 GNUNET_snprintf(middlelp,
298 sizeof (middlelp), 306 sizeof(middlelp),
299 "(%s)", 307 "(%s)",
300 middlel); 308 middlel);
301 else 309 else
302 strcpy (middlelp, middlel); 310 strcpy(middlelp, middlel);
303 if (needs_parens (middleh)) 311 if (needs_parens(middleh))
304 GNUNET_snprintf (middlehp, 312 GNUNET_snprintf(middlehp,
305 sizeof (middlehp), 313 sizeof(middlehp),
306 "(%s)", 314 "(%s)",
307 middleh); 315 middleh);
308 else 316 else
309 strcpy (middlehp, middleh); 317 strcpy(middlehp, middleh);
310 if (needs_parens (after)) 318 if (needs_parens(after))
311 GNUNET_snprintf (afterp, 319 GNUNET_snprintf(afterp,
312 sizeof (afterp), 320 sizeof(afterp),
313 "(%s)", 321 "(%s)",
314 after); 322 after);
315 else 323 else
316 strcpy (afterp, after); 324 strcpy(afterp, after);
317 dots[0] = '\0'; 325 dots[0] = '\0';
318 for (xstep=step/16;xstep>0;xstep/=16) 326 for (xstep = step / 16; xstep > 0; xstep /= 16)
319 strcat (dots, DOT); 327 strcat(dots, DOT);
320 if (step >= 16) 328 if (step >= 16)
321 { 329 {
322 if (strlen (middlel) > 0) 330 if (strlen(middlel) > 0)
323 recl = compute_policy ((start_port / step) * step, 331 recl = compute_policy((start_port / step) * step,
324 (start_port / step) * step + step - 1, 332 (start_port / step) * step + step - 1,
325 step / 16, 333 step / 16,
326 pp); 334 pp);
327 else 335 else
328 recl = GNUNET_strdup (""); 336 recl = GNUNET_strdup("");
329 if (strlen (middleh) > 0) 337 if (strlen(middleh) > 0)
330 rech = compute_policy ((end_port / step) * step, 338 rech = compute_policy((end_port / step) * step,
331 (end_port / step) * step + step - 1, 339 (end_port / step) * step + step - 1,
332 step / 16, 340 step / 16,
333 pp); 341 pp);
334 else 342 else
335 rech = GNUNET_strdup (""); 343 rech = GNUNET_strdup("");
336 } 344 }
337 else
338 {
339 recl = GNUNET_strdup ("");
340 rech = GNUNET_strdup ("");
341 middlel[0] = '\0';
342 middlelp[0] = '\0';
343 middleh[0] = '\0';
344 middlehp[0] = '\0';
345 }
346 if (needs_parens (recl))
347 GNUNET_asprintf (&reclp,
348 "(%s)",
349 recl);
350 else 345 else
351 reclp = GNUNET_strdup (recl); 346 {
352 if (needs_parens (rech)) 347 recl = GNUNET_strdup("");
353 GNUNET_asprintf (&rechp, 348 rech = GNUNET_strdup("");
354 "(%s)", 349 middlel[0] = '\0';
355 rech); 350 middlelp[0] = '\0';
351 middleh[0] = '\0';
352 middlehp[0] = '\0';
353 }
354 if (needs_parens(recl))
355 GNUNET_asprintf(&reclp,
356 "(%s)",
357 recl);
356 else 358 else
357 rechp = GNUNET_strdup (rech); 359 reclp = GNUNET_strdup(recl);
358 360 if (needs_parens(rech))
359 if ( (strlen (middleh) > 0) && 361 GNUNET_asprintf(&rechp,
360 (strlen (rech) > 0) && 362 "(%s)",
361 (strlen (middlel) > 0) && 363 rech);
362 (strlen (recl) > 0) )
363 {
364 GNUNET_asprintf (&middle,
365 "%s%s|%s%s",
366 middlel,
367 reclp,
368 middleh,
369 rechp);
370 }
371 else if ( (strlen (middleh) > 0) &&
372 (strlen (rech) > 0) )
373 {
374 GNUNET_asprintf (&middle,
375 "%s%s",
376 middleh,
377 rechp);
378 }
379 else if ( (strlen (middlel) > 0) &&
380 (strlen (recl) > 0) )
381 {
382 GNUNET_asprintf (&middle,
383 "%s%s",
384 middlel,
385 reclp);
386 }
387 else 364 else
388 { 365 rechp = GNUNET_strdup(rech);
389 middle = GNUNET_strdup (""); 366
390 } 367 if ((strlen(middleh) > 0) &&
391 if ( (strlen(before) > 0) && 368 (strlen(rech) > 0) &&
392 (strlen(after) > 0) ) 369 (strlen(middlel) > 0) &&
393 { 370 (strlen(recl) > 0))
394 if (strlen (dots) > 0)
395 { 371 {
396 if (strlen (middle) > 0) 372 GNUNET_asprintf(&middle,
397 GNUNET_asprintf (&ret, 373 "%s%s|%s%s",
398 "(%s%s|%s|%s%s)", 374 middlel,
399 beforep, dots, 375 reclp,
400 middle, 376 middleh,
401 afterp, dots); 377 rechp);
402 else
403 GNUNET_asprintf (&ret,
404 "(%s|%s)%s",
405 beforep,
406 afterp,
407 dots);
408 } 378 }
409 else 379 else if ((strlen(middleh) > 0) &&
380 (strlen(rech) > 0))
410 { 381 {
411 if (strlen (middle) > 0) 382 GNUNET_asprintf(&middle,
412 GNUNET_asprintf (&ret, 383 "%s%s",
413 "(%s|%s|%s)", 384 middleh,
414 before, 385 rechp);
415 middle,
416 after);
417 else if (1 == step)
418 GNUNET_asprintf (&ret,
419 "%s|%s",
420 before,
421 after);
422 else
423 GNUNET_asprintf (&ret,
424 "(%s|%s)",
425 before,
426 after);
427 } 386 }
428 } 387 else if ((strlen(middlel) > 0) &&
429 else if (strlen (before) > 0) 388 (strlen(recl) > 0))
430 {
431 if (strlen (dots) > 0)
432 { 389 {
433 if (strlen (middle) > 0) 390 GNUNET_asprintf(&middle,
434 GNUNET_asprintf (&ret, 391 "%s%s",
435 "(%s%s|%s)", 392 middlel,
436 beforep, dots, 393 reclp);
437 middle);
438 else
439 GNUNET_asprintf (&ret,
440 "%s%s",
441 beforep, dots);
442 } 394 }
443 else 395 else
396 {
397 middle = GNUNET_strdup("");
398 }
399 if ((strlen(before) > 0) &&
400 (strlen(after) > 0))
444 { 401 {
445 if (strlen (middle) > 0) 402 if (strlen(dots) > 0)
446 GNUNET_asprintf (&ret, 403 {
447 "(%s|%s)", 404 if (strlen(middle) > 0)
448 before, 405 GNUNET_asprintf(&ret,
449 middle); 406 "(%s%s|%s|%s%s)",
407 beforep, dots,
408 middle,
409 afterp, dots);
410 else
411 GNUNET_asprintf(&ret,
412 "(%s|%s)%s",
413 beforep,
414 afterp,
415 dots);
416 }
450 else 417 else
451 GNUNET_asprintf (&ret, 418 {
452 "%s", 419 if (strlen(middle) > 0)
453 before); 420 GNUNET_asprintf(&ret,
421 "(%s|%s|%s)",
422 before,
423 middle,
424 after);
425 else if (1 == step)
426 GNUNET_asprintf(&ret,
427 "%s|%s",
428 before,
429 after);
430 else
431 GNUNET_asprintf(&ret,
432 "(%s|%s)",
433 before,
434 after);
435 }
454 } 436 }
455 } 437 else if (strlen(before) > 0)
456 else if (strlen (after) > 0)
457 {
458 if (strlen (dots) > 0)
459 { 438 {
460 if (strlen (middle) > 0) 439 if (strlen(dots) > 0)
461 GNUNET_asprintf (&ret, 440 {
462 "(%s|%s%s)", 441 if (strlen(middle) > 0)
463 middle, 442 GNUNET_asprintf(&ret,
464 afterp, dots); 443 "(%s%s|%s)",
444 beforep, dots,
445 middle);
446 else
447 GNUNET_asprintf(&ret,
448 "%s%s",
449 beforep, dots);
450 }
465 else 451 else
466 GNUNET_asprintf (&ret, 452 {
467 "%s%s", 453 if (strlen(middle) > 0)
468 afterp, dots); 454 GNUNET_asprintf(&ret,
455 "(%s|%s)",
456 before,
457 middle);
458 else
459 GNUNET_asprintf(&ret,
460 "%s",
461 before);
462 }
469 } 463 }
470 else 464 else if (strlen(after) > 0)
471 { 465 {
472 if (strlen (middle) > 0) 466 if (strlen(dots) > 0)
473 GNUNET_asprintf (&ret, 467 {
474 "%s|%s", 468 if (strlen(middle) > 0)
475 middle, 469 GNUNET_asprintf(&ret,
476 after); 470 "(%s|%s%s)",
471 middle,
472 afterp, dots);
473 else
474 GNUNET_asprintf(&ret,
475 "%s%s",
476 afterp, dots);
477 }
477 else 478 else
478 GNUNET_asprintf (&ret, 479 {
479 "%s", 480 if (strlen(middle) > 0)
480 after); 481 GNUNET_asprintf(&ret,
482 "%s|%s",
483 middle,
484 after);
485 else
486 GNUNET_asprintf(&ret,
487 "%s",
488 after);
489 }
490 }
491 else if (strlen(middle) > 0)
492 {
493 GNUNET_asprintf(&ret,
494 "%s",
495 middle);
481 } 496 }
482 }
483 else if (strlen (middle) > 0)
484 {
485 GNUNET_asprintf (&ret,
486 "%s",
487 middle);
488 }
489 else 497 else
490 { 498 {
491 ret = GNUNET_strdup (""); 499 ret = GNUNET_strdup("");
492 } 500 }
493 GNUNET_free (middle); 501 GNUNET_free(middle);
494 GNUNET_free (reclp); 502 GNUNET_free(reclp);
495 GNUNET_free (rechp); 503 GNUNET_free(rechp);
496 GNUNET_free (recl); 504 GNUNET_free(recl);
497 GNUNET_free (rech); 505 GNUNET_free(rech);
498 return ret; 506 return ret;
499} 507}
500 508
@@ -509,7 +517,7 @@ compute_policy (unsigned int start,
509 * @return NULL on error 517 * @return NULL on error
510 */ 518 */
511static char * 519static char *
512port_to_regex (const struct GNUNET_STRINGS_PortPolicy *pp) 520port_to_regex(const struct GNUNET_STRINGS_PortPolicy *pp)
513{ 521{
514 char *reg; 522 char *reg;
515 char *ret; 523 char *ret;
@@ -517,57 +525,57 @@ port_to_regex (const struct GNUNET_STRINGS_PortPolicy *pp)
517 unsigned int i; 525 unsigned int i;
518 unsigned int cnt; 526 unsigned int cnt;
519 527
520 if ( (0 == pp->start_port) || 528 if ((0 == pp->start_port) ||
521 ( (1 == pp->start_port) && 529 ((1 == pp->start_port) &&
522 (0xFFFF == pp->end_port) && 530 (0xFFFF == pp->end_port) &&
523 (GNUNET_NO == pp->negate_portrange)) ) 531 (GNUNET_NO == pp->negate_portrange)))
524 return GNUNET_strdup (DOT DOT DOT DOT); 532 return GNUNET_strdup(DOT DOT DOT DOT);
525 if ( (pp->start_port == pp->end_port) && 533 if ((pp->start_port == pp->end_port) &&
526 (GNUNET_NO == pp->negate_portrange)) 534 (GNUNET_NO == pp->negate_portrange))
527 { 535 {
528 GNUNET_asprintf (&ret, 536 GNUNET_asprintf(&ret,
529 "%04X", 537 "%04X",
530 pp->start_port); 538 pp->start_port);
531 return ret; 539 return ret;
532 } 540 }
533 if (pp->end_port < pp->start_port) 541 if (pp->end_port < pp->start_port)
534 return NULL; 542 return NULL;
535 543
536 if (GNUNET_YES == pp->negate_portrange) 544 if (GNUNET_YES == pp->negate_portrange)
537 { 545 {
538 ret = compute_policy (0, 0xFFFF, 0x1000, pp); 546 ret = compute_policy(0, 0xFFFF, 0x1000, pp);
539 } 547 }
540 else 548 else
541 {
542 cnt = pp->end_port - pp->start_port + 1;
543 reg = GNUNET_malloc (cnt * 5 + 1);
544 pos = reg;
545 for (i=1;i<=0xFFFF;i++)
546 { 549 {
547 if ( (i >= pp->start_port) && (i <= pp->end_port) ) 550 cnt = pp->end_port - pp->start_port + 1;
548 { 551 reg = GNUNET_malloc(cnt * 5 + 1);
549 if (pos == reg) 552 pos = reg;
553 for (i = 1; i <= 0xFFFF; i++)
550 { 554 {
551 GNUNET_snprintf (pos, 555 if ((i >= pp->start_port) && (i <= pp->end_port))
552 5, 556 {
553 "%04X", 557 if (pos == reg)
554 i); 558 {
559 GNUNET_snprintf(pos,
560 5,
561 "%04X",
562 i);
563 }
564 else
565 {
566 GNUNET_snprintf(pos,
567 6,
568 "|%04X",
569 i);
570 }
571 pos += strlen(pos);
572 }
555 } 573 }
556 else 574 GNUNET_asprintf(&ret,
557 { 575 "(%s)",
558 GNUNET_snprintf (pos, 576 reg);
559 6, 577 GNUNET_free(reg);
560 "|%04X",
561 i);
562 }
563 pos += strlen (pos);
564 }
565 } 578 }
566 GNUNET_asprintf (&ret,
567 "(%s)",
568 reg);
569 GNUNET_free (reg);
570 }
571 return ret; 579 return ret;
572} 580}
573 581
@@ -581,9 +589,9 @@ port_to_regex (const struct GNUNET_STRINGS_PortPolicy *pp)
581 * @return NULL on error, otherwise regex for the address 589 * @return NULL on error, otherwise regex for the address
582 */ 590 */
583static char * 591static char *
584address_to_regex (const void *addr, 592address_to_regex(const void *addr,
585 const void *mask, 593 const void *mask,
586 size_t len) 594 size_t len)
587{ 595{
588 const uint16_t *a = addr; 596 const uint16_t *a = addr;
589 const uint16_t *m = mask; 597 const uint16_t *m = mask;
@@ -593,29 +601,29 @@ address_to_regex (const void *addr,
593 unsigned int i; 601 unsigned int i;
594 602
595 ret = NULL; 603 ret = NULL;
596 GNUNET_assert (1 != (len % 2)); 604 GNUNET_assert(1 != (len % 2));
597 for (i=0;i<len / 2;i++) 605 for (i = 0; i < len / 2; i++)
598 {
599 reg = num_to_regex (a[i], m[i]);
600 if (NULL == reg)
601 {
602 GNUNET_free_non_null (ret);
603 return NULL;
604 }
605 if (NULL == ret)
606 {
607 ret = reg;
608 }
609 else
610 { 606 {
611 GNUNET_asprintf (&tmp, 607 reg = num_to_regex(a[i], m[i]);
612 "%s%s", 608 if (NULL == reg)
613 ret, reg); 609 {
614 GNUNET_free (ret); 610 GNUNET_free_non_null(ret);
615 GNUNET_free (reg); 611 return NULL;
616 ret = tmp; 612 }
613 if (NULL == ret)
614 {
615 ret = reg;
616 }
617 else
618 {
619 GNUNET_asprintf(&tmp,
620 "%s%s",
621 ret, reg);
622 GNUNET_free(ret);
623 GNUNET_free(reg);
624 ret = tmp;
625 }
617 } 626 }
618 }
619 return ret; 627 return ret;
620} 628}
621 629
@@ -627,28 +635,28 @@ address_to_regex (const void *addr,
627 * @return NULL on error 635 * @return NULL on error
628 */ 636 */
629static char * 637static char *
630ipv4_to_regex (const struct GNUNET_STRINGS_IPv4NetworkPolicy *v4) 638ipv4_to_regex(const struct GNUNET_STRINGS_IPv4NetworkPolicy *v4)
631{ 639{
632 char *reg; 640 char *reg;
633 char *pp; 641 char *pp;
634 char *ret; 642 char *ret;
635 643
636 reg = address_to_regex (&v4->network, 644 reg = address_to_regex(&v4->network,
637 &v4->netmask, 645 &v4->netmask,
638 sizeof (struct in_addr)); 646 sizeof(struct in_addr));
639 if (NULL == reg) 647 if (NULL == reg)
640 return NULL; 648 return NULL;
641 pp = port_to_regex (&v4->pp); 649 pp = port_to_regex(&v4->pp);
642 if (NULL == pp) 650 if (NULL == pp)
643 { 651 {
644 GNUNET_free (reg); 652 GNUNET_free(reg);
645 return NULL; 653 return NULL;
646 } 654 }
647 GNUNET_asprintf (&ret, 655 GNUNET_asprintf(&ret,
648 "4-%s-%s", 656 "4-%s-%s",
649 pp, reg); 657 pp, reg);
650 GNUNET_free (pp); 658 GNUNET_free(pp);
651 GNUNET_free (reg); 659 GNUNET_free(reg);
652 return ret; 660 return ret;
653} 661}
654 662
@@ -660,28 +668,28 @@ ipv4_to_regex (const struct GNUNET_STRINGS_IPv4NetworkPolicy *v4)
660 * @return NULL on error 668 * @return NULL on error
661 */ 669 */
662static char * 670static char *
663ipv6_to_regex (const struct GNUNET_STRINGS_IPv6NetworkPolicy *v6) 671ipv6_to_regex(const struct GNUNET_STRINGS_IPv6NetworkPolicy *v6)
664{ 672{
665 char *reg; 673 char *reg;
666 char *pp; 674 char *pp;
667 char *ret; 675 char *ret;
668 676
669 reg = address_to_regex (&v6->network, 677 reg = address_to_regex(&v6->network,
670 &v6->netmask, 678 &v6->netmask,
671 sizeof (struct in6_addr)); 679 sizeof(struct in6_addr));
672 if (NULL == reg) 680 if (NULL == reg)
673 return NULL; 681 return NULL;
674 pp = port_to_regex (&v6->pp); 682 pp = port_to_regex(&v6->pp);
675 if (NULL == pp) 683 if (NULL == pp)
676 { 684 {
677 GNUNET_free (reg); 685 GNUNET_free(reg);
678 return NULL; 686 return NULL;
679 } 687 }
680 GNUNET_asprintf (&ret, 688 GNUNET_asprintf(&ret,
681 "6-%s-%s", 689 "6-%s-%s",
682 pp, reg); 690 pp, reg);
683 GNUNET_free (pp); 691 GNUNET_free(pp);
684 GNUNET_free (reg); 692 GNUNET_free(reg);
685 return ret; 693 return ret;
686} 694}
687 695
@@ -696,7 +704,7 @@ ipv6_to_regex (const struct GNUNET_STRINGS_IPv6NetworkPolicy *v6)
696 * @return regular expression, NULL on error 704 * @return regular expression, NULL on error
697 */ 705 */
698char * 706char *
699GNUNET_TUN_ipv4policy2regex (const char *policy) 707GNUNET_TUN_ipv4policy2regex(const char *policy)
700{ 708{
701 struct GNUNET_STRINGS_IPv4NetworkPolicy *np; 709 struct GNUNET_STRINGS_IPv4NetworkPolicy *np;
702 char *reg; 710 char *reg;
@@ -704,36 +712,36 @@ GNUNET_TUN_ipv4policy2regex (const char *policy)
704 char *line; 712 char *line;
705 unsigned int i; 713 unsigned int i;
706 714
707 np = GNUNET_STRINGS_parse_ipv4_policy (policy); 715 np = GNUNET_STRINGS_parse_ipv4_policy(policy);
708 if (NULL == np) 716 if (NULL == np)
709 return NULL; 717 return NULL;
710 reg = NULL; 718 reg = NULL;
711 for (i=0; (0 == i) || (0 != np[i].network.s_addr); i++) 719 for (i = 0; (0 == i) || (0 != np[i].network.s_addr); i++)
712 {
713 line = ipv4_to_regex (&np[i]);
714 if (NULL == line)
715 {
716 GNUNET_free_non_null (reg);
717 GNUNET_free (np);
718 return NULL;
719 }
720 if (NULL == reg)
721 {
722 reg = line;
723 }
724 else
725 { 720 {
726 GNUNET_asprintf (&tmp, 721 line = ipv4_to_regex(&np[i]);
727 "%s|(%s)", 722 if (NULL == line)
728 reg, line); 723 {
729 GNUNET_free (reg); 724 GNUNET_free_non_null(reg);
730 GNUNET_free (line); 725 GNUNET_free(np);
731 reg = tmp; 726 return NULL;
727 }
728 if (NULL == reg)
729 {
730 reg = line;
731 }
732 else
733 {
734 GNUNET_asprintf(&tmp,
735 "%s|(%s)",
736 reg, line);
737 GNUNET_free(reg);
738 GNUNET_free(line);
739 reg = tmp;
740 }
741 if (0 == np[i].network.s_addr)
742 break;
732 } 743 }
733 if (0 == np[i].network.s_addr) 744 GNUNET_free(np);
734 break;
735 }
736 GNUNET_free (np);
737 return reg; 745 return reg;
738} 746}
739 747
@@ -748,7 +756,7 @@ GNUNET_TUN_ipv4policy2regex (const char *policy)
748 * @return regular expression, NULL on error 756 * @return regular expression, NULL on error
749 */ 757 */
750char * 758char *
751GNUNET_TUN_ipv6policy2regex (const char *policy) 759GNUNET_TUN_ipv6policy2regex(const char *policy)
752{ 760{
753 struct in6_addr zero; 761 struct in6_addr zero;
754 struct GNUNET_STRINGS_IPv6NetworkPolicy *np; 762 struct GNUNET_STRINGS_IPv6NetworkPolicy *np;
@@ -757,37 +765,37 @@ GNUNET_TUN_ipv6policy2regex (const char *policy)
757 char *line; 765 char *line;
758 unsigned int i; 766 unsigned int i;
759 767
760 np = GNUNET_STRINGS_parse_ipv6_policy (policy); 768 np = GNUNET_STRINGS_parse_ipv6_policy(policy);
761 if (NULL == np) 769 if (NULL == np)
762 return NULL; 770 return NULL;
763 reg = NULL; 771 reg = NULL;
764 memset (&zero, 0, sizeof (struct in6_addr)); 772 memset(&zero, 0, sizeof(struct in6_addr));
765 for (i=0; (0 == i) || (0 != memcmp (&zero, &np[i].network, sizeof (struct in6_addr))); i++) 773 for (i = 0; (0 == i) || (0 != memcmp(&zero, &np[i].network, sizeof(struct in6_addr))); i++)
766 {
767 line = ipv6_to_regex (&np[i]);
768 if (NULL == line)
769 { 774 {
770 GNUNET_free_non_null (reg); 775 line = ipv6_to_regex(&np[i]);
771 GNUNET_free (np); 776 if (NULL == line)
772 return NULL; 777 {
773 } 778 GNUNET_free_non_null(reg);
774 if (NULL == reg) 779 GNUNET_free(np);
775 { 780 return NULL;
776 reg = line; 781 }
777 } 782 if (NULL == reg)
778 else 783 {
779 { 784 reg = line;
780 GNUNET_asprintf (&tmp, 785 }
781 "%s|(%s)", 786 else
782 reg, line); 787 {
783 GNUNET_free (reg); 788 GNUNET_asprintf(&tmp,
784 GNUNET_free (line); 789 "%s|(%s)",
785 reg = tmp; 790 reg, line);
791 GNUNET_free(reg);
792 GNUNET_free(line);
793 reg = tmp;
794 }
795 if (0 == memcmp(&zero, &np[i].network, sizeof(struct in6_addr)))
796 break;
786 } 797 }
787 if (0 == memcmp (&zero, &np[i].network, sizeof (struct in6_addr))) 798 GNUNET_free(np);
788 break;
789 }
790 GNUNET_free (np);
791 return reg; 799 return reg;
792} 800}
793 801
@@ -801,12 +809,12 @@ GNUNET_TUN_ipv6policy2regex (const char *policy)
801 * @param hc corresponding hash 809 * @param hc corresponding hash
802 */ 810 */
803void 811void
804GNUNET_TUN_service_name_to_hash (const char *service_name, 812GNUNET_TUN_service_name_to_hash(const char *service_name,
805 struct GNUNET_HashCode *hc) 813 struct GNUNET_HashCode *hc)
806{ 814{
807 GNUNET_CRYPTO_hash (service_name, 815 GNUNET_CRYPTO_hash(service_name,
808 strlen (service_name), 816 strlen(service_name),
809 hc); 817 hc);
810} 818}
811 819
812 820
@@ -820,16 +828,16 @@ GNUNET_TUN_service_name_to_hash (const char *service_name,
820 * @param[out] cadet_port CADET port to use 828 * @param[out] cadet_port CADET port to use
821 */ 829 */
822void 830void
823GNUNET_TUN_compute_service_cadet_port (const struct GNUNET_HashCode *desc, 831GNUNET_TUN_compute_service_cadet_port(const struct GNUNET_HashCode *desc,
824 uint16_t ip_port, 832 uint16_t ip_port,
825 struct GNUNET_HashCode *cadet_port) 833 struct GNUNET_HashCode *cadet_port)
826{ 834{
827 uint16_t be_port = htons (ip_port); 835 uint16_t be_port = htons(ip_port);
828 836
829 *cadet_port = *desc; 837 *cadet_port = *desc;
830 GNUNET_memcpy (cadet_port, 838 GNUNET_memcpy(cadet_port,
831 &be_port, 839 &be_port,
832 sizeof (uint16_t)); 840 sizeof(uint16_t));
833} 841}
834 842
835 843
diff --git a/src/util/resolver.h b/src/util/resolver.h
index 0991ad39f..9b75b0c66 100644
--- a/src/util/resolver.h
+++ b/src/util/resolver.h
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -40,8 +40,7 @@ GNUNET_NETWORK_STRUCT_BEGIN
40 * will just be a header without any data (used to indicate the end of 40 * will just be a header without any data (used to indicate the end of
41 * the list). 41 * the list).
42 */ 42 */
43struct GNUNET_RESOLVER_GetMessage 43struct GNUNET_RESOLVER_GetMessage {
44{
45 /** 44 /**
46 * Type: #GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST 45 * Type: #GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST
47 */ 46 */
@@ -66,12 +65,10 @@ struct GNUNET_RESOLVER_GetMessage
66 65
67 /* followed by 0-terminated string for A/AAAA-lookup or 66 /* followed by 0-terminated string for A/AAAA-lookup or
68 by 'struct in_addr' / 'struct in6_addr' for reverse lookup */ 67 by 'struct in_addr' / 'struct in6_addr' for reverse lookup */
69
70}; 68};
71 69
72 70
73struct GNUNET_RESOLVER_ResponseMessage 71struct GNUNET_RESOLVER_ResponseMessage {
74{
75 /** 72 /**
76 * Type: #GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE 73 * Type: #GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE
77 */ 74 */
diff --git a/src/util/resolver_api.c b/src/util/resolver_api.c
index 78ce222e6..6c56786b0 100644
--- a/src/util/resolver_api.c
+++ b/src/util/resolver_api.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/resolver_api.c 22 * @file util/resolver_api.c
@@ -29,9 +29,9 @@
29#include "gnunet_resolver_service.h" 29#include "gnunet_resolver_service.h"
30#include "resolver.h" 30#include "resolver.h"
31 31
32#define LOG(kind,...) GNUNET_log_from (kind, "util-resolver-api", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-resolver-api", __VA_ARGS__)
33 33
34#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-resolver-api", syscall) 34#define LOG_STRERROR(kind, syscall) GNUNET_log_from_strerror(kind, "util-resolver-api", syscall)
35 35
36/** 36/**
37 * Maximum supported length for a hostname 37 * Maximum supported length for a hostname
@@ -97,9 +97,7 @@ static struct GNUNET_SCHEDULER_Task *s_task;
97 * the request prior to the timeout or successful execution. Also 97 * the request prior to the timeout or successful execution. Also
98 * used to track our internal state for the request. 98 * used to track our internal state for the request.
99 */ 99 */
100struct GNUNET_RESOLVER_RequestHandle 100struct GNUNET_RESOLVER_RequestHandle {
101{
102
103 /** 101 /**
104 * Next entry in DLL of requests. 102 * Next entry in DLL of requests.
105 */ 103 */
@@ -186,61 +184,61 @@ struct GNUNET_RESOLVER_RequestHandle
186 * #GNUNET_SYSERR otherwise. 184 * #GNUNET_SYSERR otherwise.
187 */ 185 */
188static int 186static int
189check_config () 187check_config()
190{ 188{
191 char *hostname; 189 char *hostname;
192 struct sockaddr_in v4; 190 struct sockaddr_in v4;
193 struct sockaddr_in6 v6; 191 struct sockaddr_in6 v6;
194 192
195 if (GNUNET_OK == 193 if (GNUNET_OK ==
196 GNUNET_CONFIGURATION_have_value (resolver_cfg, 194 GNUNET_CONFIGURATION_have_value(resolver_cfg,
197 "resolver", 195 "resolver",
198 "UNIXPATH")) 196 "UNIXPATH"))
199 return GNUNET_OK; 197 return GNUNET_OK;
200 memset (&v4, 0, sizeof (v4)); 198 memset(&v4, 0, sizeof(v4));
201 v4.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 199 v4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
202 v4.sin_family = AF_INET; 200 v4.sin_family = AF_INET;
203#if HAVE_SOCKADDR_IN_SIN_LEN 201#if HAVE_SOCKADDR_IN_SIN_LEN
204 v4.sin_len = sizeof (v4); 202 v4.sin_len = sizeof(v4);
205#endif 203#endif
206 memset (&v6, 0, sizeof (v6)); 204 memset(&v6, 0, sizeof(v6));
207 v6.sin6_family = AF_INET6; 205 v6.sin6_family = AF_INET6;
208#if HAVE_SOCKADDR_IN_SIN_LEN 206#if HAVE_SOCKADDR_IN_SIN_LEN
209 v6.sin6_len = sizeof (v6); 207 v6.sin6_len = sizeof(v6);
210#endif 208#endif
211 if (GNUNET_OK != 209 if (GNUNET_OK !=
212 GNUNET_CONFIGURATION_get_value_string (resolver_cfg, 210 GNUNET_CONFIGURATION_get_value_string(resolver_cfg,
213 "resolver", 211 "resolver",
214 "HOSTNAME", 212 "HOSTNAME",
215 &hostname)) 213 &hostname))
216 { 214 {
217 LOG (GNUNET_ERROR_TYPE_INFO, 215 LOG(GNUNET_ERROR_TYPE_INFO,
218 _("Missing `%s' for `%s' in configuration, DNS resolution will be unavailable.\n"), 216 _("Missing `%s' for `%s' in configuration, DNS resolution will be unavailable.\n"),
219 "HOSTNAME", 217 "HOSTNAME",
220 "resolver"); 218 "resolver");
221 return GNUNET_SYSERR; 219 return GNUNET_SYSERR;
222 } 220 }
223 if ( (1 == inet_pton (AF_INET, hostname, &v4)) || 221 if ((1 == inet_pton(AF_INET, hostname, &v4)) ||
224 (1 == inet_pton (AF_INET6, hostname, &v6)) ) 222 (1 == inet_pton(AF_INET6, hostname, &v6)))
225 {
226 GNUNET_free (hostname);
227 return GNUNET_OK;
228 }
229 for (unsigned int i = 0;
230 NULL != loopback[i];
231 i++)
232 if (0 == strcasecmp (loopback[i],
233 hostname))
234 { 223 {
235 GNUNET_free (hostname); 224 GNUNET_free(hostname);
236 return GNUNET_OK; 225 return GNUNET_OK;
237 } 226 }
238 LOG (GNUNET_ERROR_TYPE_INFO, 227 for (unsigned int i = 0;
239 _("Missing `%s' or numeric IP address for `%s' of `%s' in configuration, DNS resolution will be unavailable.\n"), 228 NULL != loopback[i];
240 "localhost", 229 i++)
241 "HOSTNAME", 230 if (0 == strcasecmp(loopback[i],
242 "resolver"); 231 hostname))
243 GNUNET_free (hostname); 232 {
233 GNUNET_free(hostname);
234 return GNUNET_OK;
235 }
236 LOG(GNUNET_ERROR_TYPE_INFO,
237 _("Missing `%s' or numeric IP address for `%s' of `%s' in configuration, DNS resolution will be unavailable.\n"),
238 "localhost",
239 "HOSTNAME",
240 "resolver");
241 GNUNET_free(hostname);
244 return GNUNET_SYSERR; 242 return GNUNET_SYSERR;
245} 243}
246 244
@@ -251,9 +249,9 @@ check_config ()
251 * @param cfg configuration to use 249 * @param cfg configuration to use
252 */ 250 */
253void 251void
254GNUNET_RESOLVER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg) 252GNUNET_RESOLVER_connect(const struct GNUNET_CONFIGURATION_Handle *cfg)
255{ 253{
256 GNUNET_assert (NULL != cfg); 254 GNUNET_assert(NULL != cfg);
257 backoff = GNUNET_TIME_UNIT_MILLISECONDS; 255 backoff = GNUNET_TIME_UNIT_MILLISECONDS;
258 resolver_cfg = cfg; 256 resolver_cfg = cfg;
259} 257}
@@ -263,35 +261,35 @@ GNUNET_RESOLVER_connect (const struct GNUNET_CONFIGURATION_Handle *cfg)
263 * Destroy the connection to the resolver service. 261 * Destroy the connection to the resolver service.
264 */ 262 */
265void 263void
266GNUNET_RESOLVER_disconnect () 264GNUNET_RESOLVER_disconnect()
267{ 265{
268 struct GNUNET_RESOLVER_RequestHandle *rh; 266 struct GNUNET_RESOLVER_RequestHandle *rh;
269 267
270 while (NULL != (rh = req_head)) 268 while (NULL != (rh = req_head))
271 { 269 {
272 GNUNET_assert (GNUNET_SYSERR == rh->was_transmitted); 270 GNUNET_assert(GNUNET_SYSERR == rh->was_transmitted);
273 GNUNET_CONTAINER_DLL_remove (req_head, 271 GNUNET_CONTAINER_DLL_remove(req_head,
274 req_tail, 272 req_tail,
275 rh); 273 rh);
276 GNUNET_free (rh); 274 GNUNET_free(rh);
277 } 275 }
278 if (NULL != mq) 276 if (NULL != mq)
279 { 277 {
280 LOG (GNUNET_ERROR_TYPE_DEBUG, 278 LOG(GNUNET_ERROR_TYPE_DEBUG,
281 "Disconnecting from DNS service\n"); 279 "Disconnecting from DNS service\n");
282 GNUNET_MQ_destroy (mq); 280 GNUNET_MQ_destroy(mq);
283 mq = NULL; 281 mq = NULL;
284 } 282 }
285 if (NULL != r_task) 283 if (NULL != r_task)
286 { 284 {
287 GNUNET_SCHEDULER_cancel (r_task); 285 GNUNET_SCHEDULER_cancel(r_task);
288 r_task = NULL; 286 r_task = NULL;
289 } 287 }
290 if (NULL != s_task) 288 if (NULL != s_task)
291 { 289 {
292 GNUNET_SCHEDULER_cancel (s_task); 290 GNUNET_SCHEDULER_cancel(s_task);
293 s_task = NULL; 291 s_task = NULL;
294 } 292 }
295} 293}
296 294
297 295
@@ -299,11 +297,11 @@ GNUNET_RESOLVER_disconnect ()
299 * Task executed on system shutdown. 297 * Task executed on system shutdown.
300 */ 298 */
301static void 299static void
302shutdown_task (void *cls) 300shutdown_task(void *cls)
303{ 301{
304 (void) cls; 302 (void)cls;
305 s_task = NULL; 303 s_task = NULL;
306 GNUNET_RESOLVER_disconnect (); 304 GNUNET_RESOLVER_disconnect();
307 backoff = GNUNET_TIME_UNIT_MILLISECONDS; 305 backoff = GNUNET_TIME_UNIT_MILLISECONDS;
308} 306}
309 307
@@ -312,7 +310,7 @@ shutdown_task (void *cls)
312 * Consider disconnecting if we have no further requests pending. 310 * Consider disconnecting if we have no further requests pending.
313 */ 311 */
314static void 312static void
315check_disconnect () 313check_disconnect()
316{ 314{
317 for (struct GNUNET_RESOLVER_RequestHandle *rh = req_head; 315 for (struct GNUNET_RESOLVER_RequestHandle *rh = req_head;
318 NULL != rh; 316 NULL != rh;
@@ -320,15 +318,15 @@ check_disconnect ()
320 if (GNUNET_SYSERR != rh->was_transmitted) 318 if (GNUNET_SYSERR != rh->was_transmitted)
321 return; 319 return;
322 if (NULL != r_task) 320 if (NULL != r_task)
323 { 321 {
324 GNUNET_SCHEDULER_cancel (r_task); 322 GNUNET_SCHEDULER_cancel(r_task);
325 r_task = NULL; 323 r_task = NULL;
326 } 324 }
327 if (NULL != s_task) 325 if (NULL != s_task)
328 return; 326 return;
329 s_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MILLISECONDS, 327 s_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MILLISECONDS,
330 &shutdown_task, 328 &shutdown_task,
331 NULL); 329 NULL);
332} 330}
333 331
334 332
@@ -341,47 +339,49 @@ check_disconnect ()
341 * @return address as a string, NULL on error 339 * @return address as a string, NULL on error
342 */ 340 */
343static char * 341static char *
344no_resolve (int af, 342no_resolve(int af,
345 const void *ip, 343 const void *ip,
346 socklen_t ip_len) 344 socklen_t ip_len)
347{ 345{
348 char buf[INET6_ADDRSTRLEN]; 346 char buf[INET6_ADDRSTRLEN];
349 347
350 switch (af) 348 switch (af)
351 {
352 case AF_INET:
353 if (ip_len != sizeof (struct in_addr))
354 return NULL;
355 if (NULL ==
356 inet_ntop (AF_INET,
357 ip,
358 buf,
359 sizeof (buf)))
360 { 349 {
361 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 350 case AF_INET:
362 "inet_ntop"); 351 if (ip_len != sizeof(struct in_addr))
363 return NULL; 352 return NULL;
364 } 353 if (NULL ==
365 break; 354 inet_ntop(AF_INET,
366 case AF_INET6: 355 ip,
367 if (ip_len != sizeof (struct in6_addr)) 356 buf,
368 return NULL; 357 sizeof(buf)))
369 if (NULL == 358 {
370 inet_ntop (AF_INET6, 359 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
371 ip, 360 "inet_ntop");
372 buf, 361 return NULL;
373 sizeof (buf))) 362 }
374 { 363 break;
375 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 364
376 "inet_ntop"); 365 case AF_INET6:
366 if (ip_len != sizeof(struct in6_addr))
367 return NULL;
368 if (NULL ==
369 inet_ntop(AF_INET6,
370 ip,
371 buf,
372 sizeof(buf)))
373 {
374 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
375 "inet_ntop");
376 return NULL;
377 }
378 break;
379
380 default:
381 GNUNET_break(0);
377 return NULL; 382 return NULL;
378 } 383 }
379 break; 384 return GNUNET_strdup(buf);
380 default:
381 GNUNET_break (0);
382 return NULL;
383 }
384 return GNUNET_strdup (buf);
385} 385}
386 386
387 387
@@ -389,7 +389,7 @@ no_resolve (int af,
389 * Adjust exponential back-off and reconnect to the service. 389 * Adjust exponential back-off and reconnect to the service.
390 */ 390 */
391static void 391static void
392reconnect (void); 392reconnect(void);
393 393
394 394
395/** 395/**
@@ -401,16 +401,16 @@ reconnect (void);
401 * @param error error code 401 * @param error error code
402 */ 402 */
403static void 403static void
404mq_error_handler (void *cls, 404mq_error_handler(void *cls,
405 enum GNUNET_MQ_Error error) 405 enum GNUNET_MQ_Error error)
406{ 406{
407 (void) cls; 407 (void)cls;
408 GNUNET_MQ_destroy (mq); 408 GNUNET_MQ_destroy(mq);
409 mq = NULL; 409 mq = NULL;
410 LOG (GNUNET_ERROR_TYPE_DEBUG, 410 LOG(GNUNET_ERROR_TYPE_DEBUG,
411 "MQ error %d, reconnecting\n", 411 "MQ error %d, reconnecting\n",
412 error); 412 error);
413 reconnect (); 413 reconnect();
414} 414}
415 415
416 416
@@ -418,44 +418,44 @@ mq_error_handler (void *cls,
418 * Process pending requests to the resolver. 418 * Process pending requests to the resolver.
419 */ 419 */
420static void 420static void
421process_requests () 421process_requests()
422{ 422{
423 struct GNUNET_RESOLVER_GetMessage *msg; 423 struct GNUNET_RESOLVER_GetMessage *msg;
424 struct GNUNET_MQ_Envelope *env; 424 struct GNUNET_MQ_Envelope *env;
425 struct GNUNET_RESOLVER_RequestHandle *rh = req_head; 425 struct GNUNET_RESOLVER_RequestHandle *rh = req_head;
426 426
427 if (NULL == mq) 427 if (NULL == mq)
428 { 428 {
429 reconnect (); 429 reconnect();
430 return; 430 return;
431 } 431 }
432 if (NULL == rh) 432 if (NULL == rh)
433 { 433 {
434 /* nothing to do, release socket really soon if there is nothing 434 /* nothing to do, release socket really soon if there is nothing
435 * else happening... */ 435 * else happening... */
436 if (NULL == s_task) 436 if (NULL == s_task)
437 s_task = 437 s_task =
438 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MILLISECONDS, 438 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MILLISECONDS,
439 &shutdown_task, 439 &shutdown_task,
440 NULL); 440 NULL);
441 return; 441 return;
442 } 442 }
443 if (GNUNET_NO != rh->was_transmitted) 443 if (GNUNET_NO != rh->was_transmitted)
444 return; /* waiting for reply */ 444 return; /* waiting for reply */
445 env = GNUNET_MQ_msg_extra (msg, 445 env = GNUNET_MQ_msg_extra(msg,
446 rh->data_len, 446 rh->data_len,
447 GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST); 447 GNUNET_MESSAGE_TYPE_RESOLVER_REQUEST);
448 msg->direction = htonl (rh->direction); 448 msg->direction = htonl(rh->direction);
449 msg->af = htonl (rh->af); 449 msg->af = htonl(rh->af);
450 msg->client_id = rh->id; 450 msg->client_id = rh->id;
451 GNUNET_memcpy (&msg[1], 451 GNUNET_memcpy(&msg[1],
452 &rh[1], 452 &rh[1],
453 rh->data_len); 453 rh->data_len);
454 LOG (GNUNET_ERROR_TYPE_DEBUG, 454 LOG(GNUNET_ERROR_TYPE_DEBUG,
455 "Transmitting DNS resolution request (ID %u) to DNS service\n", 455 "Transmitting DNS resolution request (ID %u) to DNS service\n",
456 rh->id); 456 rh->id);
457 GNUNET_MQ_send (mq, 457 GNUNET_MQ_send(mq,
458 env); 458 env);
459 rh->was_transmitted = GNUNET_YES; 459 rh->was_transmitted = GNUNET_YES;
460} 460}
461 461
@@ -467,11 +467,11 @@ process_requests ()
467 * @param msg message with the hostname 467 * @param msg message with the hostname
468 */ 468 */
469static int 469static int
470check_response (void *cls, 470check_response(void *cls,
471 const struct GNUNET_RESOLVER_ResponseMessage *msg) 471 const struct GNUNET_RESOLVER_ResponseMessage *msg)
472{ 472{
473 (void) cls; 473 (void)cls;
474 (void) msg; 474 (void)msg;
475 475
476 /* implemented in #handle_response() for now */ 476 /* implemented in #handle_response() for now */
477 return GNUNET_OK; 477 return GNUNET_OK;
@@ -487,8 +487,8 @@ check_response (void *cls,
487 * @param msg message with the response 487 * @param msg message with the response
488 */ 488 */
489static void 489static void
490handle_response (void *cls, 490handle_response(void *cls,
491 const struct GNUNET_RESOLVER_ResponseMessage *msg) 491 const struct GNUNET_RESOLVER_ResponseMessage *msg)
492{ 492{
493 struct GNUNET_RESOLVER_RequestHandle *rh = req_head; 493 struct GNUNET_RESOLVER_RequestHandle *rh = req_head;
494 uint16_t size; 494 uint16_t size;
@@ -496,141 +496,141 @@ handle_response (void *cls,
496 uint32_t client_request_id = msg->client_id; 496 uint32_t client_request_id = msg->client_id;
497 497
498 for (; rh != NULL; rh = rh->next) 498 for (; rh != NULL; rh = rh->next)
499 { 499 {
500 if (rh->id == client_request_id) 500 if (rh->id == client_request_id)
501 break; 501 break;
502 } 502 }
503 503
504 (void) cls; 504 (void)cls;
505 if (NULL == rh) 505 if (NULL == rh)
506 {
507 /* Resolver service sent extra replies to query (after terminator)? Bad! */
508 GNUNET_break (0);
509 GNUNET_MQ_destroy (mq);
510 mq = NULL;
511 reconnect ();
512 return;
513 }
514 size = ntohs (msg->header.size);
515 if (size == sizeof (struct GNUNET_RESOLVER_ResponseMessage))
516 {
517 LOG (GNUNET_ERROR_TYPE_DEBUG,
518 "Received empty response from DNS service\n");
519 /* message contains not data, just header; end of replies */
520 /* check if request was canceled */
521 if (GNUNET_SYSERR != rh->was_transmitted)
522 { 506 {
523 /* no reverse lookup was successful, return IP as string */ 507 /* Resolver service sent extra replies to query (after terminator)? Bad! */
524 if (NULL != rh->name_callback) 508 GNUNET_break(0);
525 { 509 GNUNET_MQ_destroy(mq);
526 if (GNUNET_NO == rh->received_response) 510 mq = NULL;
527 { 511 reconnect();
528 nret = no_resolve (rh->af, 512 return;
529 &rh[1],
530 rh->data_len);
531 rh->name_callback (rh->cls, nret);
532 GNUNET_free (nret);
533 }
534 /* finally, make termination call */
535 if (GNUNET_SYSERR != rh->was_transmitted)
536 rh->name_callback (rh->cls,
537 NULL);
538 }
539 if ( (NULL != rh->addr_callback) &&
540 (GNUNET_SYSERR != rh->was_transmitted) )
541 rh->addr_callback (rh->cls,
542 NULL,
543 0);
544 } 513 }
545 rh->was_transmitted = GNUNET_NO; 514 size = ntohs(msg->header.size);
546 GNUNET_RESOLVER_request_cancel (rh); 515 if (size == sizeof(struct GNUNET_RESOLVER_ResponseMessage))
547 process_requests ();
548 return;
549 }
550 /* return reverse lookup results to caller */
551 if (NULL != rh->name_callback)
552 {
553 const char *hostname;
554
555 hostname = (const char *) &msg[1];
556 if (hostname[size - sizeof (struct GNUNET_RESOLVER_ResponseMessage) - 1] != '\0')
557 { 516 {
558 GNUNET_break (0); 517 LOG(GNUNET_ERROR_TYPE_DEBUG,
518 "Received empty response from DNS service\n");
519 /* message contains not data, just header; end of replies */
520 /* check if request was canceled */
559 if (GNUNET_SYSERR != rh->was_transmitted) 521 if (GNUNET_SYSERR != rh->was_transmitted)
560 rh->name_callback (rh->cls, 522 {
561 NULL); 523 /* no reverse lookup was successful, return IP as string */
524 if (NULL != rh->name_callback)
525 {
526 if (GNUNET_NO == rh->received_response)
527 {
528 nret = no_resolve(rh->af,
529 &rh[1],
530 rh->data_len);
531 rh->name_callback(rh->cls, nret);
532 GNUNET_free(nret);
533 }
534 /* finally, make termination call */
535 if (GNUNET_SYSERR != rh->was_transmitted)
536 rh->name_callback(rh->cls,
537 NULL);
538 }
539 if ((NULL != rh->addr_callback) &&
540 (GNUNET_SYSERR != rh->was_transmitted))
541 rh->addr_callback(rh->cls,
542 NULL,
543 0);
544 }
562 rh->was_transmitted = GNUNET_NO; 545 rh->was_transmitted = GNUNET_NO;
563 GNUNET_RESOLVER_request_cancel (rh); 546 GNUNET_RESOLVER_request_cancel(rh);
564 GNUNET_MQ_destroy (mq); 547 process_requests();
565 mq = NULL;
566 reconnect ();
567 return; 548 return;
568 } 549 }
569 LOG (GNUNET_ERROR_TYPE_DEBUG, 550 /* return reverse lookup results to caller */
570 "Resolver returns `%s' for IP `%s'.\n", 551 if (NULL != rh->name_callback)
571 hostname, 552 {
572 GNUNET_a2s ((const void *) &rh[1], 553 const char *hostname;
554
555 hostname = (const char *)&msg[1];
556 if (hostname[size - sizeof(struct GNUNET_RESOLVER_ResponseMessage) - 1] != '\0')
557 {
558 GNUNET_break(0);
559 if (GNUNET_SYSERR != rh->was_transmitted)
560 rh->name_callback(rh->cls,
561 NULL);
562 rh->was_transmitted = GNUNET_NO;
563 GNUNET_RESOLVER_request_cancel(rh);
564 GNUNET_MQ_destroy(mq);
565 mq = NULL;
566 reconnect();
567 return;
568 }
569 LOG(GNUNET_ERROR_TYPE_DEBUG,
570 "Resolver returns `%s' for IP `%s'.\n",
571 hostname,
572 GNUNET_a2s((const void *)&rh[1],
573 rh->data_len)); 573 rh->data_len));
574 if (rh->was_transmitted != GNUNET_SYSERR) 574 if (rh->was_transmitted != GNUNET_SYSERR)
575 rh->name_callback (rh->cls, 575 rh->name_callback(rh->cls,
576 hostname); 576 hostname);
577 rh->received_response = GNUNET_YES; 577 rh->received_response = GNUNET_YES;
578 } 578 }
579 /* return lookup results to caller */ 579 /* return lookup results to caller */
580 if (NULL != rh->addr_callback) 580 if (NULL != rh->addr_callback)
581 {
582 struct sockaddr_in v4;
583 struct sockaddr_in6 v6;
584 const struct sockaddr *sa;
585 socklen_t salen;
586 const void *ip;
587 size_t ip_len;
588
589 ip = &msg[1];
590 ip_len = size - sizeof (struct GNUNET_RESOLVER_ResponseMessage);
591 if (ip_len == sizeof (struct in_addr))
592 { 581 {
593 memset (&v4, 0, sizeof (v4)); 582 struct sockaddr_in v4;
594 v4.sin_family = AF_INET; 583 struct sockaddr_in6 v6;
595 v4.sin_addr = *(struct in_addr*) ip; 584 const struct sockaddr *sa;
585 socklen_t salen;
586 const void *ip;
587 size_t ip_len;
588
589 ip = &msg[1];
590 ip_len = size - sizeof(struct GNUNET_RESOLVER_ResponseMessage);
591 if (ip_len == sizeof(struct in_addr))
592 {
593 memset(&v4, 0, sizeof(v4));
594 v4.sin_family = AF_INET;
595 v4.sin_addr = *(struct in_addr*)ip;
596#if HAVE_SOCKADDR_IN_SIN_LEN 596#if HAVE_SOCKADDR_IN_SIN_LEN
597 v4.sin_len = sizeof (v4); 597 v4.sin_len = sizeof(v4);
598#endif 598#endif
599 salen = sizeof (v4); 599 salen = sizeof(v4);
600 sa = (const struct sockaddr *) &v4; 600 sa = (const struct sockaddr *)&v4;
601 } 601 }
602 else if (ip_len == sizeof (struct in6_addr)) 602 else if (ip_len == sizeof(struct in6_addr))
603 { 603 {
604 memset (&v6, 0, sizeof (v6)); 604 memset(&v6, 0, sizeof(v6));
605 v6.sin6_family = AF_INET6; 605 v6.sin6_family = AF_INET6;
606 v6.sin6_addr = *(struct in6_addr*) ip; 606 v6.sin6_addr = *(struct in6_addr*)ip;
607#if HAVE_SOCKADDR_IN_SIN_LEN 607#if HAVE_SOCKADDR_IN_SIN_LEN
608 v6.sin6_len = sizeof (v6); 608 v6.sin6_len = sizeof(v6);
609#endif 609#endif
610 salen = sizeof (v6); 610 salen = sizeof(v6);
611 sa = (const struct sockaddr *) &v6; 611 sa = (const struct sockaddr *)&v6;
612 } 612 }
613 else 613 else
614 { 614 {
615 GNUNET_break (0); 615 GNUNET_break(0);
616 if (GNUNET_SYSERR != rh->was_transmitted)
617 rh->addr_callback(rh->cls,
618 NULL,
619 0);
620 rh->was_transmitted = GNUNET_NO;
621 GNUNET_RESOLVER_request_cancel(rh);
622 GNUNET_MQ_destroy(mq);
623 mq = NULL;
624 reconnect();
625 return;
626 }
627 LOG(GNUNET_ERROR_TYPE_DEBUG,
628 "Received IP from DNS service\n");
616 if (GNUNET_SYSERR != rh->was_transmitted) 629 if (GNUNET_SYSERR != rh->was_transmitted)
617 rh->addr_callback (rh->cls, 630 rh->addr_callback(rh->cls,
618 NULL, 631 sa,
619 0); 632 salen);
620 rh->was_transmitted = GNUNET_NO;
621 GNUNET_RESOLVER_request_cancel (rh);
622 GNUNET_MQ_destroy (mq);
623 mq = NULL;
624 reconnect ();
625 return;
626 } 633 }
627 LOG (GNUNET_ERROR_TYPE_DEBUG,
628 "Received IP from DNS service\n");
629 if (GNUNET_SYSERR != rh->was_transmitted)
630 rh->addr_callback (rh->cls,
631 sa,
632 salen);
633 }
634} 634}
635 635
636 636
@@ -642,7 +642,7 @@ handle_response (void *cls,
642 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request 642 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request
643 */ 643 */
644static void 644static void
645numeric_resolution (void *cls) 645numeric_resolution(void *cls)
646{ 646{
647 struct GNUNET_RESOLVER_RequestHandle *rh = cls; 647 struct GNUNET_RESOLVER_RequestHandle *rh = cls;
648 struct sockaddr_in v4; 648 struct sockaddr_in v4;
@@ -650,63 +650,63 @@ numeric_resolution (void *cls)
650 const char *hostname; 650 const char *hostname;
651 651
652 rh->task = NULL; 652 rh->task = NULL;
653 memset (&v4, 0, sizeof (v4)); 653 memset(&v4, 0, sizeof(v4));
654 v4.sin_family = AF_INET; 654 v4.sin_family = AF_INET;
655#if HAVE_SOCKADDR_IN_SIN_LEN 655#if HAVE_SOCKADDR_IN_SIN_LEN
656 v4.sin_len = sizeof (v4); 656 v4.sin_len = sizeof(v4);
657#endif 657#endif
658 memset (&v6, 0, sizeof (v6)); 658 memset(&v6, 0, sizeof(v6));
659 v6.sin6_family = AF_INET6; 659 v6.sin6_family = AF_INET6;
660#if HAVE_SOCKADDR_IN_SIN_LEN 660#if HAVE_SOCKADDR_IN_SIN_LEN
661 v6.sin6_len = sizeof (v6); 661 v6.sin6_len = sizeof(v6);
662#endif 662#endif
663 hostname = (const char *) &rh[1]; 663 hostname = (const char *)&rh[1];
664 if ( ( (rh->af == AF_UNSPEC) || 664 if (((rh->af == AF_UNSPEC) ||
665 (rh->af == AF_INET) ) && 665 (rh->af == AF_INET)) &&
666 (1 == inet_pton (AF_INET, 666 (1 == inet_pton(AF_INET,
667 hostname, 667 hostname,
668 &v4.sin_addr)) ) 668 &v4.sin_addr)))
669 {
670 rh->addr_callback (rh->cls,
671 (const struct sockaddr *) &v4,
672 sizeof (v4));
673 if ( (rh->af == AF_UNSPEC) &&
674 (GNUNET_SYSERR != rh->was_transmitted) &&
675 (1 == inet_pton (AF_INET6,
676 hostname,
677 &v6.sin6_addr)) )
678 { 669 {
679 /* this can happen on some systems IF "hostname" is "localhost" */ 670 rh->addr_callback(rh->cls,
680 rh->addr_callback (rh->cls, 671 (const struct sockaddr *)&v4,
681 (const struct sockaddr *) &v6, 672 sizeof(v4));
682 sizeof (v6)); 673 if ((rh->af == AF_UNSPEC) &&
674 (GNUNET_SYSERR != rh->was_transmitted) &&
675 (1 == inet_pton(AF_INET6,
676 hostname,
677 &v6.sin6_addr)))
678 {
679 /* this can happen on some systems IF "hostname" is "localhost" */
680 rh->addr_callback(rh->cls,
681 (const struct sockaddr *)&v6,
682 sizeof(v6));
683 }
684 if (GNUNET_SYSERR != rh->was_transmitted)
685 rh->addr_callback(rh->cls,
686 NULL,
687 0);
688 GNUNET_free(rh);
689 return;
690 }
691 if (((rh->af == AF_UNSPEC) ||
692 (rh->af == AF_INET6)) &&
693 (1 == inet_pton(AF_INET6,
694 hostname,
695 &v6.sin6_addr)))
696 {
697 rh->addr_callback(rh->cls,
698 (const struct sockaddr *)&v6,
699 sizeof(v6));
700 if (GNUNET_SYSERR != rh->was_transmitted)
701 rh->addr_callback(rh->cls,
702 NULL,
703 0);
704 GNUNET_free(rh);
705 return;
683 } 706 }
684 if (GNUNET_SYSERR != rh->was_transmitted)
685 rh->addr_callback (rh->cls,
686 NULL,
687 0);
688 GNUNET_free (rh);
689 return;
690 }
691 if ( ( (rh->af == AF_UNSPEC) ||
692 (rh->af == AF_INET6) ) &&
693 (1 == inet_pton (AF_INET6,
694 hostname,
695 &v6.sin6_addr) ) )
696 {
697 rh->addr_callback (rh->cls,
698 (const struct sockaddr *) &v6,
699 sizeof (v6));
700 if (GNUNET_SYSERR != rh->was_transmitted)
701 rh->addr_callback (rh->cls,
702 NULL,
703 0);
704 GNUNET_free (rh);
705 return;
706 }
707 /* why are we here? this task should not have been scheduled! */ 707 /* why are we here? this task should not have been scheduled! */
708 GNUNET_assert (0); 708 GNUNET_assert(0);
709 GNUNET_free (rh); 709 GNUNET_free(rh);
710} 710}
711 711
712 712
@@ -718,58 +718,61 @@ numeric_resolution (void *cls)
718 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request 718 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request
719 */ 719 */
720static void 720static void
721loopback_resolution (void *cls) 721loopback_resolution(void *cls)
722{ 722{
723 struct GNUNET_RESOLVER_RequestHandle *rh = cls; 723 struct GNUNET_RESOLVER_RequestHandle *rh = cls;
724 struct sockaddr_in v4; 724 struct sockaddr_in v4;
725 struct sockaddr_in6 v6; 725 struct sockaddr_in6 v6;
726 726
727 rh->task = NULL; 727 rh->task = NULL;
728 memset (&v4, 0, sizeof (v4)); 728 memset(&v4, 0, sizeof(v4));
729 v4.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 729 v4.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
730 v4.sin_family = AF_INET; 730 v4.sin_family = AF_INET;
731#if HAVE_SOCKADDR_IN_SIN_LEN 731#if HAVE_SOCKADDR_IN_SIN_LEN
732 v4.sin_len = sizeof (v4); 732 v4.sin_len = sizeof(v4);
733#endif 733#endif
734 memset (&v6, 0, sizeof (v6)); 734 memset(&v6, 0, sizeof(v6));
735 v6.sin6_family = AF_INET6; 735 v6.sin6_family = AF_INET6;
736#if HAVE_SOCKADDR_IN_SIN_LEN 736#if HAVE_SOCKADDR_IN_SIN_LEN
737 v6.sin6_len = sizeof (v6); 737 v6.sin6_len = sizeof(v6);
738#endif 738#endif
739 v6.sin6_addr = in6addr_loopback; 739 v6.sin6_addr = in6addr_loopback;
740 switch (rh->af) 740 switch (rh->af)
741 { 741 {
742 case AF_INET: 742 case AF_INET:
743 rh->addr_callback (rh->cls, 743 rh->addr_callback(rh->cls,
744 (const struct sockaddr *) &v4, 744 (const struct sockaddr *)&v4,
745 sizeof (v4)); 745 sizeof(v4));
746 break; 746 break;
747 case AF_INET6: 747
748 rh->addr_callback (rh->cls, 748 case AF_INET6:
749 (const struct sockaddr *) &v6, 749 rh->addr_callback(rh->cls,
750 sizeof (v6)); 750 (const struct sockaddr *)&v6,
751 break; 751 sizeof(v6));
752 case AF_UNSPEC: 752 break;
753 rh->addr_callback (rh->cls, 753
754 (const struct sockaddr *) &v6, 754 case AF_UNSPEC:
755 sizeof (v6)); 755 rh->addr_callback(rh->cls,
756 rh->addr_callback (rh->cls, 756 (const struct sockaddr *)&v6,
757 (const struct sockaddr *) &v4, 757 sizeof(v6));
758 sizeof (v4)); 758 rh->addr_callback(rh->cls,
759 759 (const struct sockaddr *)&v4,
760 break; 760 sizeof(v4));
761 default: 761
762 GNUNET_break (0); 762 break;
763 break; 763
764 } 764 default:
765 GNUNET_break(0);
766 break;
767 }
765 if (GNUNET_SYSERR != rh->was_transmitted) 768 if (GNUNET_SYSERR != rh->was_transmitted)
766 rh->addr_callback (rh->cls, 769 rh->addr_callback(rh->cls,
767 NULL, 770 NULL,
768 0); 771 0);
769 LOG (GNUNET_ERROR_TYPE_DEBUG, 772 LOG(GNUNET_ERROR_TYPE_DEBUG,
770 "Finished resolving hostname `%s'.\n", 773 "Finished resolving hostname `%s'.\n",
771 (const char *) &rh[1]); 774 (const char *)&rh[1]);
772 GNUNET_free (rh); 775 GNUNET_free(rh);
773} 776}
774 777
775 778
@@ -779,35 +782,35 @@ loopback_resolution (void *cls)
779 * @param cls NULL 782 * @param cls NULL
780 */ 783 */
781static void 784static void
782reconnect_task (void *cls) 785reconnect_task(void *cls)
783{ 786{
784 struct GNUNET_MQ_MessageHandler handlers[] = { 787 struct GNUNET_MQ_MessageHandler handlers[] = {
785 GNUNET_MQ_hd_var_size (response, 788 GNUNET_MQ_hd_var_size(response,
786 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE, 789 GNUNET_MESSAGE_TYPE_RESOLVER_RESPONSE,
787 struct GNUNET_RESOLVER_ResponseMessage, 790 struct GNUNET_RESOLVER_ResponseMessage,
788 NULL), 791 NULL),
789 GNUNET_MQ_handler_end () 792 GNUNET_MQ_handler_end()
790 }; 793 };
791 794
792 (void) cls; 795 (void)cls;
793 r_task = NULL; 796 r_task = NULL;
794 if (NULL == req_head) 797 if (NULL == req_head)
795 return; /* no work pending */ 798 return; /* no work pending */
796 LOG (GNUNET_ERROR_TYPE_DEBUG, 799 LOG(GNUNET_ERROR_TYPE_DEBUG,
797 "Trying to connect to DNS service\n"); 800 "Trying to connect to DNS service\n");
798 mq = GNUNET_CLIENT_connect (resolver_cfg, 801 mq = GNUNET_CLIENT_connect(resolver_cfg,
799 "resolver", 802 "resolver",
800 handlers, 803 handlers,
801 &mq_error_handler, 804 &mq_error_handler,
802 NULL); 805 NULL);
803 if (NULL == mq) 806 if (NULL == mq)
804 { 807 {
805 LOG (GNUNET_ERROR_TYPE_DEBUG, 808 LOG(GNUNET_ERROR_TYPE_DEBUG,
806 "Failed to connect, will try again later\n"); 809 "Failed to connect, will try again later\n");
807 reconnect (); 810 reconnect();
808 return; 811 return;
809 } 812 }
810 process_requests (); 813 process_requests();
811} 814}
812 815
813 816
@@ -815,46 +818,49 @@ reconnect_task (void *cls)
815 * Adjust exponential back-off and reconnect to the service. 818 * Adjust exponential back-off and reconnect to the service.
816 */ 819 */
817static void 820static void
818reconnect () 821reconnect()
819{ 822{
820 struct GNUNET_RESOLVER_RequestHandle *rh; 823 struct GNUNET_RESOLVER_RequestHandle *rh;
821 824
822 if (NULL != r_task) 825 if (NULL != r_task)
823 return; 826 return;
824 GNUNET_assert (NULL == mq); 827 GNUNET_assert(NULL == mq);
825 if (NULL != (rh = req_head)) 828 if (NULL != (rh = req_head))
826 {
827 switch (rh->was_transmitted)
828 { 829 {
829 case GNUNET_NO: 830 switch (rh->was_transmitted)
830 /* nothing more to do */ 831 {
831 break; 832 case GNUNET_NO:
832 case GNUNET_YES: 833 /* nothing more to do */
833 /* disconnected, transmit again! */ 834 break;
834 rh->was_transmitted = GNUNET_NO; 835
835 break; 836 case GNUNET_YES:
836 case GNUNET_SYSERR: 837 /* disconnected, transmit again! */
837 /* request was cancelled, remove entirely */ 838 rh->was_transmitted = GNUNET_NO;
838 GNUNET_CONTAINER_DLL_remove (req_head, 839 break;
839 req_tail, 840
840 rh); 841 case GNUNET_SYSERR:
841 GNUNET_free (rh); 842 /* request was cancelled, remove entirely */
842 check_disconnect (); 843 GNUNET_CONTAINER_DLL_remove(req_head,
843 break; 844 req_tail,
844 default: 845 rh);
845 GNUNET_assert (0); 846 GNUNET_free(rh);
846 break; 847 check_disconnect();
848 break;
849
850 default:
851 GNUNET_assert(0);
852 break;
853 }
847 } 854 }
848 } 855 LOG(GNUNET_ERROR_TYPE_DEBUG,
849 LOG (GNUNET_ERROR_TYPE_DEBUG, 856 "Will try to connect to DNS service in %s\n",
850 "Will try to connect to DNS service in %s\n", 857 GNUNET_STRINGS_relative_time_to_string(backoff,
851 GNUNET_STRINGS_relative_time_to_string (backoff, 858 GNUNET_YES));
852 GNUNET_YES)); 859 GNUNET_assert(NULL != resolver_cfg);
853 GNUNET_assert (NULL != resolver_cfg); 860 r_task = GNUNET_SCHEDULER_add_delayed(backoff,
854 r_task = GNUNET_SCHEDULER_add_delayed (backoff, 861 &reconnect_task,
855 &reconnect_task, 862 NULL);
856 NULL); 863 backoff = GNUNET_TIME_STD_BACKOFF(backoff);
857 backoff = GNUNET_TIME_STD_BACKOFF (backoff);
858} 864}
859 865
860 866
@@ -864,52 +870,52 @@ reconnect ()
864 * @param cls the `struct GNUNET_RESOLVER_RequestHandle *` 870 * @param cls the `struct GNUNET_RESOLVER_RequestHandle *`
865 */ 871 */
866static void 872static void
867handle_lookup_timeout (void *cls) 873handle_lookup_timeout(void *cls)
868{ 874{
869 struct GNUNET_RESOLVER_RequestHandle *rh = cls; 875 struct GNUNET_RESOLVER_RequestHandle *rh = cls;
870 876
871 rh->task = NULL; 877 rh->task = NULL;
872 if (GNUNET_NO == rh->direction) 878 if (GNUNET_NO == rh->direction)
873 { 879 {
874 LOG (GNUNET_ERROR_TYPE_INFO, 880 LOG(GNUNET_ERROR_TYPE_INFO,
875 _("Timeout trying to resolve hostname `%s'.\n"), 881 _("Timeout trying to resolve hostname `%s'.\n"),
876 (const char *) &rh[1]); 882 (const char *)&rh[1]);
877 if (NULL != rh->addr_callback) 883 if (NULL != rh->addr_callback)
878 rh->addr_callback (rh->cls, 884 rh->addr_callback(rh->cls,
879 NULL, 885 NULL,
880 0); 886 0);
881 } 887 }
882 else 888 else
883 { 889 {
884#if !defined(GNUNET_CULL_LOGGING) 890#if !defined(GNUNET_CULL_LOGGING)
885 char buf[INET6_ADDRSTRLEN]; 891 char buf[INET6_ADDRSTRLEN];
886 892
887 LOG (GNUNET_ERROR_TYPE_INFO, 893 LOG(GNUNET_ERROR_TYPE_INFO,
888 _("Timeout trying to resolve IP address `%s'.\n"), 894 _("Timeout trying to resolve IP address `%s'.\n"),
889 inet_ntop (rh->af, 895 inet_ntop(rh->af,
890 (const void *) &rh[1], 896 (const void *)&rh[1],
891 buf, 897 buf,
892 sizeof(buf))); 898 sizeof(buf)));
893#endif 899#endif
894 if (GNUNET_NO == rh->received_response) 900 if (GNUNET_NO == rh->received_response)
895 { 901 {
896 char *nret; 902 char *nret;
897 903
898 nret = no_resolve (rh->af, 904 nret = no_resolve(rh->af,
899 &rh[1], 905 &rh[1],
900 rh->data_len); 906 rh->data_len);
907 if (NULL != rh->name_callback)
908 rh->name_callback(rh->cls, nret);
909 GNUNET_free(nret);
910 }
911 /* finally, make termination call */
901 if (NULL != rh->name_callback) 912 if (NULL != rh->name_callback)
902 rh->name_callback (rh->cls, nret); 913 rh->name_callback(rh->cls,
903 GNUNET_free (nret); 914 NULL);
904 } 915 }
905 /* finally, make termination call */
906 if (NULL != rh->name_callback)
907 rh->name_callback (rh->cls,
908 NULL);
909 }
910 rh->was_transmitted = GNUNET_NO; 916 rh->was_transmitted = GNUNET_NO;
911 GNUNET_RESOLVER_request_cancel (rh); 917 GNUNET_RESOLVER_request_cancel(rh);
912 process_requests (); 918 process_requests();
913} 919}
914 920
915 921
@@ -924,83 +930,83 @@ handle_lookup_timeout (void *cls)
924 * @return handle that can be used to cancel the request, NULL on error 930 * @return handle that can be used to cancel the request, NULL on error
925 */ 931 */
926struct GNUNET_RESOLVER_RequestHandle * 932struct GNUNET_RESOLVER_RequestHandle *
927GNUNET_RESOLVER_ip_get (const char *hostname, 933GNUNET_RESOLVER_ip_get(const char *hostname,
928 int af, 934 int af,
929 struct GNUNET_TIME_Relative timeout, 935 struct GNUNET_TIME_Relative timeout,
930 GNUNET_RESOLVER_AddressCallback callback, 936 GNUNET_RESOLVER_AddressCallback callback,
931 void *callback_cls) 937 void *callback_cls)
932{ 938{
933 struct GNUNET_RESOLVER_RequestHandle *rh; 939 struct GNUNET_RESOLVER_RequestHandle *rh;
934 size_t slen; 940 size_t slen;
935 struct in_addr v4; 941 struct in_addr v4;
936 struct in6_addr v6; 942 struct in6_addr v6;
937 943
938 slen = strlen (hostname) + 1; 944 slen = strlen(hostname) + 1;
939 if (slen + sizeof (struct GNUNET_RESOLVER_GetMessage) >= 945 if (slen + sizeof(struct GNUNET_RESOLVER_GetMessage) >=
940 GNUNET_MAX_MESSAGE_SIZE) 946 GNUNET_MAX_MESSAGE_SIZE)
941 { 947 {
942 GNUNET_break (0); 948 GNUNET_break(0);
943 return NULL; 949 return NULL;
944 } 950 }
945 LOG (GNUNET_ERROR_TYPE_DEBUG, 951 LOG(GNUNET_ERROR_TYPE_DEBUG,
946 "Trying to resolve hostname `%s'.\n", 952 "Trying to resolve hostname `%s'.\n",
947 hostname); 953 hostname);
948 rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + slen); 954 rh = GNUNET_malloc(sizeof(struct GNUNET_RESOLVER_RequestHandle) + slen);
949 rh->af = af; 955 rh->af = af;
950 rh->id = ++last_request_id; 956 rh->id = ++last_request_id;
951 rh->addr_callback = callback; 957 rh->addr_callback = callback;
952 rh->cls = callback_cls; 958 rh->cls = callback_cls;
953 GNUNET_memcpy (&rh[1], 959 GNUNET_memcpy(&rh[1],
954 hostname, 960 hostname,
955 slen); 961 slen);
956 rh->data_len = slen; 962 rh->data_len = slen;
957 rh->timeout = GNUNET_TIME_relative_to_absolute (timeout); 963 rh->timeout = GNUNET_TIME_relative_to_absolute(timeout);
958 rh->direction = GNUNET_NO; 964 rh->direction = GNUNET_NO;
959 /* first, check if this is a numeric address */ 965 /* first, check if this is a numeric address */
960 if ( ( (1 == inet_pton (AF_INET, 966 if (((1 == inet_pton(AF_INET,
961 hostname, 967 hostname,
962 &v4)) && 968 &v4)) &&
963 ( (af == AF_INET) || 969 ((af == AF_INET) ||
964 (af == AF_UNSPEC) ) ) || 970 (af == AF_UNSPEC))) ||
965 ( (1 == inet_pton (AF_INET6, 971 ((1 == inet_pton(AF_INET6,
966 hostname, 972 hostname,
967 &v6)) && 973 &v6)) &&
968 ( (af == AF_INET6) || 974 ((af == AF_INET6) ||
969 (af == AF_UNSPEC)) ) ) 975 (af == AF_UNSPEC))))
970 { 976 {
971 rh->task = GNUNET_SCHEDULER_add_now (&numeric_resolution, 977 rh->task = GNUNET_SCHEDULER_add_now(&numeric_resolution,
972 rh); 978 rh);
973 return rh; 979 return rh;
974 } 980 }
975 /* then, check if this is a loopback address */ 981 /* then, check if this is a loopback address */
976 for (unsigned int i = 0; 982 for (unsigned int i = 0;
977 NULL != loopback[i]; 983 NULL != loopback[i];
978 i++) 984 i++)
979 if (0 == strcasecmp (loopback[i], 985 if (0 == strcasecmp(loopback[i],
980 hostname)) 986 hostname))
987 {
988 rh->task = GNUNET_SCHEDULER_add_now(&loopback_resolution,
989 rh);
990 return rh;
991 }
992 if (GNUNET_OK != check_config())
981 { 993 {
982 rh->task = GNUNET_SCHEDULER_add_now (&loopback_resolution, 994 GNUNET_free(rh);
983 rh); 995 return NULL;
984 return rh;
985 } 996 }
986 if (GNUNET_OK != check_config ()) 997 rh->task = GNUNET_SCHEDULER_add_delayed(timeout,
987 { 998 &handle_lookup_timeout,
988 GNUNET_free (rh); 999 rh);
989 return NULL; 1000 GNUNET_CONTAINER_DLL_insert_tail(req_head,
990 } 1001 req_tail,
991 rh->task = GNUNET_SCHEDULER_add_delayed (timeout, 1002 rh);
992 &handle_lookup_timeout,
993 rh);
994 GNUNET_CONTAINER_DLL_insert_tail (req_head,
995 req_tail,
996 rh);
997 rh->was_queued = GNUNET_YES; 1003 rh->was_queued = GNUNET_YES;
998 if (NULL != s_task) 1004 if (NULL != s_task)
999 { 1005 {
1000 GNUNET_SCHEDULER_cancel (s_task); 1006 GNUNET_SCHEDULER_cancel(s_task);
1001 s_task = NULL; 1007 s_task = NULL;
1002 } 1008 }
1003 process_requests (); 1009 process_requests();
1004 return rh; 1010 return rh;
1005} 1011}
1006 1012
@@ -1014,32 +1020,32 @@ GNUNET_RESOLVER_ip_get (const char *hostname,
1014 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request 1020 * @param cls `struct GNUNET_RESOLVER_RequestHandle` for the request
1015 */ 1021 */
1016static void 1022static void
1017numeric_reverse (void *cls) 1023numeric_reverse(void *cls)
1018{ 1024{
1019 struct GNUNET_RESOLVER_RequestHandle *rh = cls; 1025 struct GNUNET_RESOLVER_RequestHandle *rh = cls;
1020 char *result; 1026 char *result;
1021 1027
1022 rh->task = NULL; 1028 rh->task = NULL;
1023 result = no_resolve (rh->af, 1029 result = no_resolve(rh->af,
1024 &rh[1], 1030 &rh[1],
1025 rh->data_len); 1031 rh->data_len);
1026 LOG (GNUNET_ERROR_TYPE_DEBUG, 1032 LOG(GNUNET_ERROR_TYPE_DEBUG,
1027 "Resolver returns `%s'.\n", 1033 "Resolver returns `%s'.\n",
1028 result); 1034 result);
1029 if (NULL != result) 1035 if (NULL != result)
1030 { 1036 {
1031 rh->name_callback (rh->cls, 1037 rh->name_callback(rh->cls,
1032 result); 1038 result);
1033 GNUNET_free (result); 1039 GNUNET_free(result);
1034 } 1040 }
1035 rh->name_callback (rh->cls, 1041 rh->name_callback(rh->cls,
1036 NULL); 1042 NULL);
1037 if (NULL != rh->task) 1043 if (NULL != rh->task)
1038 { 1044 {
1039 GNUNET_SCHEDULER_cancel (rh->task); 1045 GNUNET_SCHEDULER_cancel(rh->task);
1040 rh->task = NULL; 1046 rh->task = NULL;
1041 } 1047 }
1042 GNUNET_free (rh); 1048 GNUNET_free(rh);
1043} 1049}
1044 1050
1045 1051
@@ -1056,71 +1062,73 @@ numeric_reverse (void *cls)
1056 * @return handle that can be used to cancel the request 1062 * @return handle that can be used to cancel the request
1057 */ 1063 */
1058struct GNUNET_RESOLVER_RequestHandle * 1064struct GNUNET_RESOLVER_RequestHandle *
1059GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa, 1065GNUNET_RESOLVER_hostname_get(const struct sockaddr *sa,
1060 socklen_t salen, 1066 socklen_t salen,
1061 int do_resolve, 1067 int do_resolve,
1062 struct GNUNET_TIME_Relative timeout, 1068 struct GNUNET_TIME_Relative timeout,
1063 GNUNET_RESOLVER_HostnameCallback callback, 1069 GNUNET_RESOLVER_HostnameCallback callback,
1064 void *cls) 1070 void *cls)
1065{ 1071{
1066 struct GNUNET_RESOLVER_RequestHandle *rh; 1072 struct GNUNET_RESOLVER_RequestHandle *rh;
1067 size_t ip_len; 1073 size_t ip_len;
1068 const void *ip; 1074 const void *ip;
1069 1075
1070 if (GNUNET_OK != check_config ()) 1076 if (GNUNET_OK != check_config())
1071 { 1077 {
1072 LOG (GNUNET_ERROR_TYPE_ERROR, 1078 LOG(GNUNET_ERROR_TYPE_ERROR,
1073 _("Resolver not configured correctly.\n")); 1079 _("Resolver not configured correctly.\n"));
1074 return NULL; 1080 return NULL;
1075 } 1081 }
1076 1082
1077 switch (sa->sa_family) 1083 switch (sa->sa_family)
1078 { 1084 {
1079 case AF_INET: 1085 case AF_INET:
1080 GNUNET_assert (salen == sizeof (struct sockaddr_in)); 1086 GNUNET_assert(salen == sizeof(struct sockaddr_in));
1081 ip_len = sizeof (struct in_addr); 1087 ip_len = sizeof(struct in_addr);
1082 ip = &((const struct sockaddr_in*)sa)->sin_addr; 1088 ip = &((const struct sockaddr_in*)sa)->sin_addr;
1083 break; 1089 break;
1084 case AF_INET6: 1090
1085 GNUNET_assert (salen == sizeof (struct sockaddr_in6)); 1091 case AF_INET6:
1086 ip_len = sizeof (struct in6_addr); 1092 GNUNET_assert(salen == sizeof(struct sockaddr_in6));
1087 ip = &((const struct sockaddr_in6*)sa)->sin6_addr; 1093 ip_len = sizeof(struct in6_addr);
1088 break; 1094 ip = &((const struct sockaddr_in6*)sa)->sin6_addr;
1089 default: 1095 break;
1090 GNUNET_break (0); 1096
1091 return NULL; 1097 default:
1092 } 1098 GNUNET_break(0);
1093 rh = GNUNET_malloc (sizeof (struct GNUNET_RESOLVER_RequestHandle) + salen); 1099 return NULL;
1100 }
1101 rh = GNUNET_malloc(sizeof(struct GNUNET_RESOLVER_RequestHandle) + salen);
1094 rh->name_callback = callback; 1102 rh->name_callback = callback;
1095 rh->cls = cls; 1103 rh->cls = cls;
1096 rh->af = sa->sa_family; 1104 rh->af = sa->sa_family;
1097 rh->id = ++last_request_id; 1105 rh->id = ++last_request_id;
1098 rh->timeout = GNUNET_TIME_relative_to_absolute (timeout); 1106 rh->timeout = GNUNET_TIME_relative_to_absolute(timeout);
1099 GNUNET_memcpy (&rh[1], 1107 GNUNET_memcpy(&rh[1],
1100 ip, 1108 ip,
1101 ip_len); 1109 ip_len);
1102 rh->data_len = ip_len; 1110 rh->data_len = ip_len;
1103 rh->direction = GNUNET_YES; 1111 rh->direction = GNUNET_YES;
1104 rh->received_response = GNUNET_NO; 1112 rh->received_response = GNUNET_NO;
1105 if (GNUNET_NO == do_resolve) 1113 if (GNUNET_NO == do_resolve)
1106 { 1114 {
1107 rh->task = GNUNET_SCHEDULER_add_now (&numeric_reverse, 1115 rh->task = GNUNET_SCHEDULER_add_now(&numeric_reverse,
1108 rh); 1116 rh);
1109 return rh; 1117 return rh;
1110 } 1118 }
1111 rh->task = GNUNET_SCHEDULER_add_delayed (timeout, 1119 rh->task = GNUNET_SCHEDULER_add_delayed(timeout,
1112 &handle_lookup_timeout, 1120 &handle_lookup_timeout,
1113 rh); 1121 rh);
1114 GNUNET_CONTAINER_DLL_insert_tail (req_head, 1122 GNUNET_CONTAINER_DLL_insert_tail(req_head,
1115 req_tail, 1123 req_tail,
1116 rh); 1124 rh);
1117 rh->was_queued = GNUNET_YES; 1125 rh->was_queued = GNUNET_YES;
1118 if (NULL != s_task) 1126 if (NULL != s_task)
1119 { 1127 {
1120 GNUNET_SCHEDULER_cancel (s_task); 1128 GNUNET_SCHEDULER_cancel(s_task);
1121 s_task = NULL; 1129 s_task = NULL;
1122 } 1130 }
1123 process_requests (); 1131 process_requests();
1124 return rh; 1132 return rh;
1125} 1133}
1126 1134
@@ -1131,78 +1139,78 @@ GNUNET_RESOLVER_hostname_get (const struct sockaddr *sa,
1131 * @return fqdn 1139 * @return fqdn
1132 */ 1140 */
1133char * 1141char *
1134GNUNET_RESOLVER_local_fqdn_get () 1142GNUNET_RESOLVER_local_fqdn_get()
1135{ 1143{
1136 char hostname[GNUNET_OS_get_hostname_max_length () + 1]; 1144 char hostname[GNUNET_OS_get_hostname_max_length() + 1];
1137 1145
1138 if (0 != gethostname (hostname, 1146 if (0 != gethostname(hostname,
1139 sizeof (hostname) - 1)) 1147 sizeof(hostname) - 1))
1140 { 1148 {
1141 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 1149 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1142 "gethostname"); 1150 "gethostname");
1143 return NULL; 1151 return NULL;
1144 } 1152 }
1145 LOG (GNUNET_ERROR_TYPE_DEBUG, 1153 LOG(GNUNET_ERROR_TYPE_DEBUG,
1146 "Resolving our FQDN `%s'\n", 1154 "Resolving our FQDN `%s'\n",
1147 hostname); 1155 hostname);
1148#if HAVE_GETADDRINFO 1156#if HAVE_GETADDRINFO
1149 { 1157 {
1150 struct addrinfo *ai; 1158 struct addrinfo *ai;
1151 int ret; 1159 int ret;
1152 char *rval; 1160 char *rval;
1153 1161
1154 if (0 != (ret = getaddrinfo (hostname, 1162 if (0 != (ret = getaddrinfo(hostname,
1155 NULL, 1163 NULL,
1156 NULL, 1164 NULL,
1157 &ai))) 1165 &ai)))
1158 { 1166 {
1159 LOG (GNUNET_ERROR_TYPE_ERROR, 1167 LOG(GNUNET_ERROR_TYPE_ERROR,
1160 _("Could not resolve our FQDN: %s\n"), 1168 _("Could not resolve our FQDN: %s\n"),
1161 gai_strerror (ret)); 1169 gai_strerror(ret));
1162 return NULL; 1170 return NULL;
1163 } 1171 }
1164 if (NULL != ai->ai_canonname) 1172 if (NULL != ai->ai_canonname)
1165 rval = GNUNET_strdup (ai->ai_canonname); 1173 rval = GNUNET_strdup(ai->ai_canonname);
1166 else 1174 else
1167 rval = GNUNET_strdup (hostname); 1175 rval = GNUNET_strdup(hostname);
1168 freeaddrinfo (ai); 1176 freeaddrinfo(ai);
1169 return rval; 1177 return rval;
1170 } 1178 }
1171#elif HAVE_GETHOSTBYNAME2 1179#elif HAVE_GETHOSTBYNAME2
1172 { 1180 {
1173 struct hostent *host; 1181 struct hostent *host;
1174 1182
1175 host = gethostbyname2 (hostname, 1183 host = gethostbyname2(hostname,
1176 AF_INET); 1184 AF_INET);
1177 if (NULL == host) 1185 if (NULL == host)
1178 host = gethostbyname2 (hostname, 1186 host = gethostbyname2(hostname,
1179 AF_INET6); 1187 AF_INET6);
1180 if (NULL == host) 1188 if (NULL == host)
1181 { 1189 {
1182 LOG (GNUNET_ERROR_TYPE_ERROR, 1190 LOG(GNUNET_ERROR_TYPE_ERROR,
1183 _("Could not resolve our FQDN: %s\n"), 1191 _("Could not resolve our FQDN: %s\n"),
1184 hstrerror (h_errno)); 1192 hstrerror(h_errno));
1185 return NULL; 1193 return NULL;
1186 } 1194 }
1187 return GNUNET_strdup (host->h_name); 1195 return GNUNET_strdup(host->h_name);
1188 } 1196 }
1189#elif HAVE_GETHOSTBYNAME 1197#elif HAVE_GETHOSTBYNAME
1190 { 1198 {
1191 struct hostent *host; 1199 struct hostent *host;
1192 1200
1193 host = gethostbyname (hostname); 1201 host = gethostbyname(hostname);
1194 if (NULL == host) 1202 if (NULL == host)
1195 { 1203 {
1196 LOG (GNUNET_ERROR_TYPE_ERROR, 1204 LOG(GNUNET_ERROR_TYPE_ERROR,
1197 _("Could not resolve our FQDN: %s\n"), 1205 _("Could not resolve our FQDN: %s\n"),
1198 hstrerror (h_errno)); 1206 hstrerror(h_errno));
1199 return NULL; 1207 return NULL;
1200 } 1208 }
1201 return GNUNET_strdup (host->h_name); 1209 return GNUNET_strdup(host->h_name);
1202 } 1210 }
1203#else 1211#else
1204 /* fallback: just hope name is already FQDN */ 1212 /* fallback: just hope name is already FQDN */
1205 return GNUNET_strdup (hostname); 1213 return GNUNET_strdup(hostname);
1206#endif 1214#endif
1207} 1215}
1208 1216
@@ -1217,27 +1225,27 @@ GNUNET_RESOLVER_local_fqdn_get ()
1217 * @return handle that can be used to cancel the request, NULL on error 1225 * @return handle that can be used to cancel the request, NULL on error
1218 */ 1226 */
1219struct GNUNET_RESOLVER_RequestHandle * 1227struct GNUNET_RESOLVER_RequestHandle *
1220GNUNET_RESOLVER_hostname_resolve (int af, 1228GNUNET_RESOLVER_hostname_resolve(int af,
1221 struct GNUNET_TIME_Relative timeout, 1229 struct GNUNET_TIME_Relative timeout,
1222 GNUNET_RESOLVER_AddressCallback callback, 1230 GNUNET_RESOLVER_AddressCallback callback,
1223 void *cls) 1231 void *cls)
1224{ 1232{
1225 char hostname[GNUNET_OS_get_hostname_max_length () + 1]; 1233 char hostname[GNUNET_OS_get_hostname_max_length() + 1];
1226 1234
1227 if (0 != gethostname (hostname, sizeof (hostname) - 1)) 1235 if (0 != gethostname(hostname, sizeof(hostname) - 1))
1228 { 1236 {
1229 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK, 1237 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR | GNUNET_ERROR_TYPE_BULK,
1230 "gethostname"); 1238 "gethostname");
1231 return NULL; 1239 return NULL;
1232 } 1240 }
1233 LOG (GNUNET_ERROR_TYPE_DEBUG, 1241 LOG(GNUNET_ERROR_TYPE_DEBUG,
1234 "Resolving our hostname `%s'\n", 1242 "Resolving our hostname `%s'\n",
1235 hostname); 1243 hostname);
1236 return GNUNET_RESOLVER_ip_get (hostname, 1244 return GNUNET_RESOLVER_ip_get(hostname,
1237 af, 1245 af,
1238 timeout, 1246 timeout,
1239 callback, 1247 callback,
1240 cls); 1248 cls);
1241} 1249}
1242 1250
1243 1251
@@ -1250,30 +1258,30 @@ GNUNET_RESOLVER_hostname_resolve (int af,
1250 * @param rh handle of request to cancel 1258 * @param rh handle of request to cancel
1251 */ 1259 */
1252void 1260void
1253GNUNET_RESOLVER_request_cancel (struct GNUNET_RESOLVER_RequestHandle *rh) 1261GNUNET_RESOLVER_request_cancel(struct GNUNET_RESOLVER_RequestHandle *rh)
1254{ 1262{
1255 if (GNUNET_NO == rh->direction) 1263 if (GNUNET_NO == rh->direction)
1256 LOG (GNUNET_ERROR_TYPE_DEBUG, 1264 LOG(GNUNET_ERROR_TYPE_DEBUG,
1257 "Asked to cancel request to resolve hostname `%s'.\n", 1265 "Asked to cancel request to resolve hostname `%s'.\n",
1258 (const char *) &rh[1]); 1266 (const char *)&rh[1]);
1259 if (NULL != rh->task) 1267 if (NULL != rh->task)
1260 { 1268 {
1261 GNUNET_SCHEDULER_cancel (rh->task); 1269 GNUNET_SCHEDULER_cancel(rh->task);
1262 rh->task = NULL; 1270 rh->task = NULL;
1263 } 1271 }
1264 if (GNUNET_NO == rh->was_transmitted) 1272 if (GNUNET_NO == rh->was_transmitted)
1265 { 1273 {
1266 if (GNUNET_YES == rh->was_queued) 1274 if (GNUNET_YES == rh->was_queued)
1267 GNUNET_CONTAINER_DLL_remove (req_head, 1275 GNUNET_CONTAINER_DLL_remove(req_head,
1268 req_tail, 1276 req_tail,
1269 rh); 1277 rh);
1270 GNUNET_free (rh); 1278 GNUNET_free(rh);
1271 check_disconnect (); 1279 check_disconnect();
1272 return; 1280 return;
1273 } 1281 }
1274 GNUNET_assert (GNUNET_YES == rh->was_transmitted); 1282 GNUNET_assert(GNUNET_YES == rh->was_transmitted);
1275 rh->was_transmitted = GNUNET_SYSERR; /* mark as cancelled */ 1283 rh->was_transmitted = GNUNET_SYSERR; /* mark as cancelled */
1276 check_disconnect (); 1284 check_disconnect();
1277} 1285}
1278 1286
1279 1287
diff --git a/src/util/scheduler.c b/src/util/scheduler.c
index c818e91ee..4bea5bd5d 100644
--- a/src/util/scheduler.c
+++ b/src/util/scheduler.c
@@ -11,7 +11,7 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
@@ -28,9 +28,9 @@
28// DEBUG 28// DEBUG
29#include <inttypes.h> 29#include <inttypes.h>
30 30
31#define LOG(kind,...) GNUNET_log_from (kind, "util-scheduler", __VA_ARGS__) 31#define LOG(kind, ...) GNUNET_log_from(kind, "util-scheduler", __VA_ARGS__)
32 32
33#define LOG_STRERROR(kind,syscall) GNUNET_log_from_strerror (kind, "util-scheduler", syscall) 33#define LOG_STRERROR(kind, syscall) GNUNET_log_from_strerror(kind, "util-scheduler", syscall)
34 34
35 35
36#if HAVE_EXECINFO_H 36#if HAVE_EXECINFO_H
@@ -76,8 +76,7 @@
76 * #GNUNET_SCHEDULER_do_work(). Contains the 76 * #GNUNET_SCHEDULER_do_work(). Contains the
77 * scheduler's internal state. 77 * scheduler's internal state.
78 */ 78 */
79struct GNUNET_SCHEDULER_Handle 79struct GNUNET_SCHEDULER_Handle {
80{
81 /** 80 /**
82 * Passed here to avoid constantly allocating/deallocating 81 * Passed here to avoid constantly allocating/deallocating
83 * this element, but generally we want to get rid of this. 82 * this element, but generally we want to get rid of this.
@@ -131,8 +130,7 @@ struct GNUNET_SCHEDULER_Handle
131/** 130/**
132 * Entry in list of pending tasks. 131 * Entry in list of pending tasks.
133 */ 132 */
134struct GNUNET_SCHEDULER_Task 133struct GNUNET_SCHEDULER_Task {
135{
136 /** 134 /**
137 * This is a linked list. 135 * This is a linked list.
138 */ 136 */
@@ -245,15 +243,13 @@ struct GNUNET_SCHEDULER_Task
245 * Asynchronous scope of the task that scheduled this scope, 243 * Asynchronous scope of the task that scheduled this scope,
246 */ 244 */
247 struct GNUNET_AsyncScopeSave scope; 245 struct GNUNET_AsyncScopeSave scope;
248
249}; 246};
250 247
251 248
252/** 249/**
253 * A struct representing an event the select driver is waiting for 250 * A struct representing an event the select driver is waiting for
254 */ 251 */
255struct Scheduled 252struct Scheduled {
256{
257 struct Scheduled *prev; 253 struct Scheduled *prev;
258 254
259 struct Scheduled *next; 255 struct Scheduled *next;
@@ -280,8 +276,7 @@ struct Scheduled
280/** 276/**
281 * Driver context used by GNUNET_SCHEDULER_run 277 * Driver context used by GNUNET_SCHEDULER_run
282 */ 278 */
283struct DriverContext 279struct DriverContext {
284{
285 /** 280 /**
286 * the head of a DLL containing information about the events the 281 * the head of a DLL containing information about the events the
287 * select driver is waiting for 282 * select driver is waiting for
@@ -430,8 +425,8 @@ static void *scheduler_select_cls;
430 * @return previously used select function, NULL for default 425 * @return previously used select function, NULL for default
431 */ 426 */
432void 427void
433GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select, 428GNUNET_SCHEDULER_set_select(GNUNET_SCHEDULER_select new_select,
434 void *new_select_cls) 429 void *new_select_cls)
435{ 430{
436 scheduler_select = new_select; 431 scheduler_select = new_select;
437 scheduler_select_cls = new_select_cls; 432 scheduler_select_cls = new_select_cls;
@@ -445,11 +440,11 @@ GNUNET_SCHEDULER_set_select (GNUNET_SCHEDULER_select new_select,
445 * @return p on success, 0 on error 440 * @return p on success, 0 on error
446 */ 441 */
447static enum GNUNET_SCHEDULER_Priority 442static enum GNUNET_SCHEDULER_Priority
448check_priority (enum GNUNET_SCHEDULER_Priority p) 443check_priority(enum GNUNET_SCHEDULER_Priority p)
449{ 444{
450 if ((p >= 0) && (p < GNUNET_SCHEDULER_PRIORITY_COUNT)) 445 if ((p >= 0) && (p < GNUNET_SCHEDULER_PRIORITY_COUNT))
451 return p; 446 return p;
452 GNUNET_assert (0); 447 GNUNET_assert(0);
453 return 0; /* make compiler happy */ 448 return 0; /* make compiler happy */
454} 449}
455 450
@@ -460,38 +455,38 @@ check_priority (enum GNUNET_SCHEDULER_Priority p)
460 * callback) 455 * callback)
461 */ 456 */
462struct GNUNET_TIME_Absolute 457struct GNUNET_TIME_Absolute
463get_timeout () 458get_timeout()
464{ 459{
465 struct GNUNET_SCHEDULER_Task *pos; 460 struct GNUNET_SCHEDULER_Task *pos;
466 struct GNUNET_TIME_Absolute now; 461 struct GNUNET_TIME_Absolute now;
467 struct GNUNET_TIME_Absolute timeout; 462 struct GNUNET_TIME_Absolute timeout;
468 463
469 pos = pending_timeout_head; 464 pos = pending_timeout_head;
470 now = GNUNET_TIME_absolute_get (); 465 now = GNUNET_TIME_absolute_get();
471 timeout = GNUNET_TIME_UNIT_FOREVER_ABS; 466 timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
472 if (NULL != pos) 467 if (NULL != pos)
473 {
474 if (0 != pos->reason)
475 { 468 {
476 return now; 469 if (0 != pos->reason)
477 } 470 {
478 else 471 return now;
479 { 472 }
480 timeout = pos->timeout; 473 else
474 {
475 timeout = pos->timeout;
476 }
481 } 477 }
482 }
483 for (pos = pending_head; NULL != pos; pos = pos->next) 478 for (pos = pending_head; NULL != pos; pos = pos->next)
484 {
485 if (0 != pos->reason)
486 { 479 {
487 return now; 480 if (0 != pos->reason)
488 } 481 {
489 else if ((pos->timeout.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) && 482 return now;
490 (timeout.abs_value_us > pos->timeout.abs_value_us)) 483 }
491 { 484 else if ((pos->timeout.abs_value_us != GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) &&
492 timeout = pos->timeout; 485 (timeout.abs_value_us > pos->timeout.abs_value_us))
486 {
487 timeout = pos->timeout;
488 }
493 } 489 }
494 }
495 return timeout; 490 return timeout;
496} 491}
497 492
@@ -502,13 +497,13 @@ get_timeout ()
502 * @param task task ready for execution 497 * @param task task ready for execution
503 */ 498 */
504static void 499static void
505queue_ready_task (struct GNUNET_SCHEDULER_Task *task) 500queue_ready_task(struct GNUNET_SCHEDULER_Task *task)
506{ 501{
507 enum GNUNET_SCHEDULER_Priority p = check_priority (task->priority); 502 enum GNUNET_SCHEDULER_Priority p = check_priority(task->priority);
508 503
509 GNUNET_CONTAINER_DLL_insert (ready_head[p], 504 GNUNET_CONTAINER_DLL_insert(ready_head[p],
510 ready_tail[p], 505 ready_tail[p],
511 task); 506 task);
512 task->in_ready_list = GNUNET_YES; 507 task->in_ready_list = GNUNET_YES;
513 ready_count++; 508 ready_count++;
514} 509}
@@ -521,30 +516,30 @@ queue_ready_task (struct GNUNET_SCHEDULER_Task *task)
521 * will be delayed until the next shutdown signal. 516 * will be delayed until the next shutdown signal.
522 */ 517 */
523void 518void
524GNUNET_SCHEDULER_shutdown () 519GNUNET_SCHEDULER_shutdown()
525{ 520{
526 struct GNUNET_SCHEDULER_Task *pos; 521 struct GNUNET_SCHEDULER_Task *pos;
527 522
528 LOG (GNUNET_ERROR_TYPE_DEBUG, 523 LOG(GNUNET_ERROR_TYPE_DEBUG,
529 "GNUNET_SCHEDULER_shutdown\n"); 524 "GNUNET_SCHEDULER_shutdown\n");
530 if (NULL != install_parent_control_task) 525 if (NULL != install_parent_control_task)
531 { 526 {
532 GNUNET_SCHEDULER_cancel (install_parent_control_task); 527 GNUNET_SCHEDULER_cancel(install_parent_control_task);
533 install_parent_control_task = NULL; 528 install_parent_control_task = NULL;
534 } 529 }
535 if (NULL != shutdown_pipe_task) 530 if (NULL != shutdown_pipe_task)
536 { 531 {
537 GNUNET_SCHEDULER_cancel (shutdown_pipe_task); 532 GNUNET_SCHEDULER_cancel(shutdown_pipe_task);
538 shutdown_pipe_task = NULL; 533 shutdown_pipe_task = NULL;
539 } 534 }
540 while (NULL != (pos = shutdown_head)) 535 while (NULL != (pos = shutdown_head))
541 { 536 {
542 GNUNET_CONTAINER_DLL_remove (shutdown_head, 537 GNUNET_CONTAINER_DLL_remove(shutdown_head,
543 shutdown_tail, 538 shutdown_tail,
544 pos); 539 pos);
545 pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN; 540 pos->reason |= GNUNET_SCHEDULER_REASON_SHUTDOWN;
546 queue_ready_task (pos); 541 queue_ready_task(pos);
547 } 542 }
548} 543}
549 544
550 545
@@ -554,17 +549,17 @@ GNUNET_SCHEDULER_shutdown ()
554 * @param t task to dump stack trace of 549 * @param t task to dump stack trace of
555 */ 550 */
556static void 551static void
557dump_backtrace (struct GNUNET_SCHEDULER_Task *t) 552dump_backtrace(struct GNUNET_SCHEDULER_Task *t)
558{ 553{
559#if EXECINFO 554#if EXECINFO
560 for (unsigned int i = 0; i < t->num_backtrace_strings; i++) 555 for (unsigned int i = 0; i < t->num_backtrace_strings; i++)
561 LOG (GNUNET_ERROR_TYPE_WARNING, 556 LOG(GNUNET_ERROR_TYPE_WARNING,
562 "Task %p trace %u: %s\n", 557 "Task %p trace %u: %s\n",
563 t, 558 t,
564 i, 559 i,
565 t->backtrace_strings[i]); 560 t->backtrace_strings[i]);
566#else 561#else
567 (void) t; 562 (void)t;
568#endif 563#endif
569} 564}
570 565
@@ -575,40 +570,40 @@ dump_backtrace (struct GNUNET_SCHEDULER_Task *t)
575 * @param t task to destroy 570 * @param t task to destroy
576 */ 571 */
577static void 572static void
578destroy_task (struct GNUNET_SCHEDULER_Task *t) 573destroy_task(struct GNUNET_SCHEDULER_Task *t)
579{ 574{
580 unsigned int i; 575 unsigned int i;
581 576
582 LOG (GNUNET_ERROR_TYPE_DEBUG, 577 LOG(GNUNET_ERROR_TYPE_DEBUG,
583 "destroying task %p\n", 578 "destroying task %p\n",
584 t); 579 t);
585 580
586 if (GNUNET_YES == t->own_handles) 581 if (GNUNET_YES == t->own_handles)
587 {
588 for (i = 0; i != t->fds_len; ++i)
589 { 582 {
590 const struct GNUNET_NETWORK_Handle *fd = t->fds[i].fd; 583 for (i = 0; i != t->fds_len; ++i)
591 const struct GNUNET_DISK_FileHandle *fh = t->fds[i].fh; 584 {
592 if (fd) 585 const struct GNUNET_NETWORK_Handle *fd = t->fds[i].fd;
593 { 586 const struct GNUNET_DISK_FileHandle *fh = t->fds[i].fh;
594 GNUNET_NETWORK_socket_free_memory_only_ ((struct GNUNET_NETWORK_Handle *) fd); 587 if (fd)
595 } 588 {
596 if (fh) 589 GNUNET_NETWORK_socket_free_memory_only_((struct GNUNET_NETWORK_Handle *)fd);
597 { 590 }
598 // FIXME: on WIN32 this is not enough! A function 591 if (fh)
599 // GNUNET_DISK_file_free_memory_only would be nice 592 {
600 GNUNET_free ((void *) fh); 593 // FIXME: on WIN32 this is not enough! A function
601 } 594 // GNUNET_DISK_file_free_memory_only would be nice
595 GNUNET_free((void *)fh);
596 }
597 }
602 } 598 }
603 }
604 if (t->fds_len > 1) 599 if (t->fds_len > 1)
605 { 600 {
606 GNUNET_array_grow (t->fds, t->fds_len, 0); 601 GNUNET_array_grow(t->fds, t->fds_len, 0);
607 } 602 }
608#if EXECINFO 603#if EXECINFO
609 GNUNET_free (t->backtrace_strings); 604 GNUNET_free(t->backtrace_strings);
610#endif 605#endif
611 GNUNET_free (t); 606 GNUNET_free(t);
612} 607}
613 608
614 609
@@ -628,7 +623,7 @@ static pid_t my_pid;
628 */ 623 */
629#ifndef MINGW 624#ifndef MINGW
630static void 625static void
631sighandler_pipe () 626sighandler_pipe()
632{ 627{
633 return; 628 return;
634} 629}
@@ -657,23 +652,23 @@ sighandler_pipe ()
657 * Signal handler called for signals that should cause us to shutdown. 652 * Signal handler called for signals that should cause us to shutdown.
658 */ 653 */
659static void 654static void
660sighandler_shutdown () 655sighandler_shutdown()
661{ 656{
662 static char c; 657 static char c;
663 int old_errno = errno; /* backup errno */ 658 int old_errno = errno; /* backup errno */
664 659
665 if (getpid () != my_pid) 660 if (getpid() != my_pid)
666 _exit (1); /* we have fork'ed since the signal handler was created, 661 _exit(1); /* we have fork'ed since the signal handler was created,
667 * ignore the signal, see https://gnunet.org/vfork discussion */ 662 * ignore the signal, see https://gnunet.org/vfork discussion */
668 GNUNET_DISK_file_write (GNUNET_DISK_pipe_handle 663 GNUNET_DISK_file_write(GNUNET_DISK_pipe_handle
669 (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE), 664 (shutdown_pipe_handle, GNUNET_DISK_PIPE_END_WRITE),
670 &c, sizeof (c)); 665 &c, sizeof(c));
671 errno = old_errno; 666 errno = old_errno;
672} 667}
673 668
674 669
675static void 670static void
676shutdown_if_no_lifeness () 671shutdown_if_no_lifeness()
677{ 672{
678 struct GNUNET_SCHEDULER_Task *t; 673 struct GNUNET_SCHEDULER_Task *t;
679 674
@@ -689,13 +684,13 @@ shutdown_if_no_lifeness ()
689 if (GNUNET_YES == t->lifeness) 684 if (GNUNET_YES == t->lifeness)
690 return; 685 return;
691 /* No lifeness! */ 686 /* No lifeness! */
692 GNUNET_SCHEDULER_shutdown (); 687 GNUNET_SCHEDULER_shutdown();
693} 688}
694 689
695 690
696static int 691static int
697select_loop (struct GNUNET_SCHEDULER_Handle *sh, 692select_loop(struct GNUNET_SCHEDULER_Handle *sh,
698 struct DriverContext *context); 693 struct DriverContext *context);
699 694
700 695
701/** 696/**
@@ -713,26 +708,26 @@ select_loop (struct GNUNET_SCHEDULER_Handle *sh,
713 * @param task_cls closure of @a task 708 * @param task_cls closure of @a task
714 */ 709 */
715void 710void
716GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_TaskCallback task, 711GNUNET_SCHEDULER_run(GNUNET_SCHEDULER_TaskCallback task,
717 void *task_cls) 712 void *task_cls)
718{ 713{
719 struct GNUNET_SCHEDULER_Handle *sh; 714 struct GNUNET_SCHEDULER_Handle *sh;
720 struct GNUNET_SCHEDULER_Driver *driver; 715 struct GNUNET_SCHEDULER_Driver *driver;
721 struct DriverContext context = {.scheduled_head = NULL, 716 struct DriverContext context = { .scheduled_head = NULL,
722 .scheduled_tail = NULL, 717 .scheduled_tail = NULL,
723 .timeout = GNUNET_TIME_absolute_get ()}; 718 .timeout = GNUNET_TIME_absolute_get() };
724 719
725 driver = GNUNET_SCHEDULER_driver_select (); 720 driver = GNUNET_SCHEDULER_driver_select();
726 driver->cls = &context; 721 driver->cls = &context;
727 sh = GNUNET_SCHEDULER_driver_init (driver); 722 sh = GNUNET_SCHEDULER_driver_init(driver);
728 GNUNET_SCHEDULER_add_with_reason_and_priority (task, 723 GNUNET_SCHEDULER_add_with_reason_and_priority(task,
729 task_cls, 724 task_cls,
730 GNUNET_SCHEDULER_REASON_STARTUP, 725 GNUNET_SCHEDULER_REASON_STARTUP,
731 GNUNET_SCHEDULER_PRIORITY_DEFAULT); 726 GNUNET_SCHEDULER_PRIORITY_DEFAULT);
732 select_loop (sh, 727 select_loop(sh,
733 &context); 728 &context);
734 GNUNET_SCHEDULER_driver_done (sh); 729 GNUNET_SCHEDULER_driver_done(sh);
735 GNUNET_free (driver); 730 GNUNET_free(driver);
736} 731}
737 732
738 733
@@ -743,9 +738,9 @@ GNUNET_SCHEDULER_run (GNUNET_SCHEDULER_TaskCallback task,
743 * @return current tasks' scheduler context 738 * @return current tasks' scheduler context
744 */ 739 */
745const struct GNUNET_SCHEDULER_TaskContext * 740const struct GNUNET_SCHEDULER_TaskContext *
746GNUNET_SCHEDULER_get_task_context () 741GNUNET_SCHEDULER_get_task_context()
747{ 742{
748 GNUNET_assert (NULL != active_task); 743 GNUNET_assert(NULL != active_task);
749 return &tc; 744 return &tc;
750} 745}
751 746
@@ -760,33 +755,33 @@ GNUNET_SCHEDULER_get_task_context ()
760 * @return number of tasks pending right now 755 * @return number of tasks pending right now
761 */ 756 */
762unsigned int 757unsigned int
763GNUNET_SCHEDULER_get_load (enum GNUNET_SCHEDULER_Priority p) 758GNUNET_SCHEDULER_get_load(enum GNUNET_SCHEDULER_Priority p)
764{ 759{
765 struct GNUNET_SCHEDULER_Task *pos; 760 struct GNUNET_SCHEDULER_Task *pos;
766 unsigned int ret; 761 unsigned int ret;
767 762
768 GNUNET_assert (NULL != active_task); 763 GNUNET_assert(NULL != active_task);
769 if (p == GNUNET_SCHEDULER_PRIORITY_COUNT) 764 if (p == GNUNET_SCHEDULER_PRIORITY_COUNT)
770 return ready_count; 765 return ready_count;
771 if (p == GNUNET_SCHEDULER_PRIORITY_KEEP) 766 if (p == GNUNET_SCHEDULER_PRIORITY_KEEP)
772 p = current_priority; 767 p = current_priority;
773 ret = 0; 768 ret = 0;
774 for (pos = ready_head[check_priority (p)]; NULL != pos; pos = pos->next) 769 for (pos = ready_head[check_priority(p)]; NULL != pos; pos = pos->next)
775 ret++; 770 ret++;
776 return ret; 771 return ret;
777} 772}
778 773
779 774
780void 775void
781init_fd_info (struct GNUNET_SCHEDULER_Task *t, 776init_fd_info(struct GNUNET_SCHEDULER_Task *t,
782 const struct GNUNET_NETWORK_Handle *const *read_nh, 777 const struct GNUNET_NETWORK_Handle *const *read_nh,
783 unsigned int read_nh_len, 778 unsigned int read_nh_len,
784 const struct GNUNET_NETWORK_Handle *const *write_nh, 779 const struct GNUNET_NETWORK_Handle *const *write_nh,
785 unsigned int write_nh_len, 780 unsigned int write_nh_len,
786 const struct GNUNET_DISK_FileHandle *const *read_fh, 781 const struct GNUNET_DISK_FileHandle *const *read_fh,
787 unsigned int read_fh_len, 782 unsigned int read_fh_len,
788 const struct GNUNET_DISK_FileHandle *const *write_fh, 783 const struct GNUNET_DISK_FileHandle *const *write_fh,
789 unsigned int write_fh_len) 784 unsigned int write_fh_len)
790{ 785{
791 // FIXME: if we have exactly two network handles / exactly two file handles 786 // FIXME: if we have exactly two network handles / exactly two file handles
792 // and they are equal, we can make one FdInfo with both 787 // and they are equal, we can make one FdInfo with both
@@ -795,90 +790,90 @@ init_fd_info (struct GNUNET_SCHEDULER_Task *t,
795 790
796 t->fds_len = read_nh_len + write_nh_len + read_fh_len + write_fh_len; 791 t->fds_len = read_nh_len + write_nh_len + read_fh_len + write_fh_len;
797 if (1 == t->fds_len) 792 if (1 == t->fds_len)
798 {
799 fdi = &t->fdx;
800 t->fds = fdi;
801 if (1 == read_nh_len)
802 { 793 {
803 GNUNET_assert (NULL != read_nh); 794 fdi = &t->fdx;
804 GNUNET_assert (NULL != *read_nh); 795 t->fds = fdi;
805 fdi->fd = *read_nh; 796 if (1 == read_nh_len)
806 fdi->et = GNUNET_SCHEDULER_ET_IN; 797 {
807 fdi->sock = GNUNET_NETWORK_get_fd (*read_nh); 798 GNUNET_assert(NULL != read_nh);
808 t->read_fd = fdi->sock; 799 GNUNET_assert(NULL != *read_nh);
809 t->write_fd = -1; 800 fdi->fd = *read_nh;
801 fdi->et = GNUNET_SCHEDULER_ET_IN;
802 fdi->sock = GNUNET_NETWORK_get_fd(*read_nh);
803 t->read_fd = fdi->sock;
804 t->write_fd = -1;
805 }
806 else if (1 == write_nh_len)
807 {
808 GNUNET_assert(NULL != write_nh);
809 GNUNET_assert(NULL != *write_nh);
810 fdi->fd = *write_nh;
811 fdi->et = GNUNET_SCHEDULER_ET_OUT;
812 fdi->sock = GNUNET_NETWORK_get_fd(*write_nh);
813 t->read_fd = -1;
814 t->write_fd = fdi->sock;
815 }
816 else if (1 == read_fh_len)
817 {
818 GNUNET_assert(NULL != read_fh);
819 GNUNET_assert(NULL != *read_fh);
820 fdi->fh = *read_fh;
821 fdi->et = GNUNET_SCHEDULER_ET_IN;
822 fdi->sock = (*read_fh)->fd; // FIXME: does not work under WIN32
823 t->read_fd = fdi->sock;
824 t->write_fd = -1;
825 }
826 else
827 {
828 GNUNET_assert(NULL != write_fh);
829 GNUNET_assert(NULL != *write_fh);
830 fdi->fh = *write_fh;
831 fdi->et = GNUNET_SCHEDULER_ET_OUT;
832 fdi->sock = (*write_fh)->fd; // FIXME: does not work under WIN32
833 t->read_fd = -1;
834 t->write_fd = fdi->sock;
835 }
810 } 836 }
811 else if (1 == write_nh_len) 837 else
812 { 838 {
813 GNUNET_assert (NULL != write_nh); 839 fdi = GNUNET_new_array(t->fds_len, struct GNUNET_SCHEDULER_FdInfo);
814 GNUNET_assert (NULL != *write_nh); 840 t->fds = fdi;
815 fdi->fd = *write_nh;
816 fdi->et = GNUNET_SCHEDULER_ET_OUT;
817 fdi->sock = GNUNET_NETWORK_get_fd (*write_nh);
818 t->read_fd = -1; 841 t->read_fd = -1;
819 t->write_fd = fdi->sock;
820 }
821 else if (1 == read_fh_len)
822 {
823 GNUNET_assert (NULL != read_fh);
824 GNUNET_assert (NULL != *read_fh);
825 fdi->fh = *read_fh;
826 fdi->et = GNUNET_SCHEDULER_ET_IN;
827 fdi->sock = (*read_fh)->fd; // FIXME: does not work under WIN32
828 t->read_fd = fdi->sock;
829 t->write_fd = -1; 842 t->write_fd = -1;
843 unsigned int i;
844 for (i = 0; i != read_nh_len; ++i)
845 {
846 fdi->fd = read_nh[i];
847 GNUNET_assert(NULL != fdi->fd);
848 fdi->et = GNUNET_SCHEDULER_ET_IN;
849 fdi->sock = GNUNET_NETWORK_get_fd(read_nh[i]);
850 ++fdi;
851 }
852 for (i = 0; i != write_nh_len; ++i)
853 {
854 fdi->fd = write_nh[i];
855 GNUNET_assert(NULL != fdi->fd);
856 fdi->et = GNUNET_SCHEDULER_ET_OUT;
857 fdi->sock = GNUNET_NETWORK_get_fd(write_nh[i]);
858 ++fdi;
859 }
860 for (i = 0; i != read_fh_len; ++i)
861 {
862 fdi->fh = read_fh[i];
863 GNUNET_assert(NULL != fdi->fh);
864 fdi->et = GNUNET_SCHEDULER_ET_IN;
865 fdi->sock = (read_fh[i])->fd; // FIXME: does not work under WIN32
866 ++fdi;
867 }
868 for (i = 0; i != write_fh_len; ++i)
869 {
870 fdi->fh = write_fh[i];
871 GNUNET_assert(NULL != fdi->fh);
872 fdi->et = GNUNET_SCHEDULER_ET_OUT;
873 fdi->sock = (write_fh[i])->fd; // FIXME: does not work under WIN32
874 ++fdi;
875 }
830 } 876 }
831 else
832 {
833 GNUNET_assert (NULL != write_fh);
834 GNUNET_assert (NULL != *write_fh);
835 fdi->fh = *write_fh;
836 fdi->et = GNUNET_SCHEDULER_ET_OUT;
837 fdi->sock = (*write_fh)->fd; // FIXME: does not work under WIN32
838 t->read_fd = -1;
839 t->write_fd = fdi->sock;
840 }
841 }
842 else
843 {
844 fdi = GNUNET_new_array (t->fds_len, struct GNUNET_SCHEDULER_FdInfo);
845 t->fds = fdi;
846 t->read_fd = -1;
847 t->write_fd = -1;
848 unsigned int i;
849 for (i = 0; i != read_nh_len; ++i)
850 {
851 fdi->fd = read_nh[i];
852 GNUNET_assert (NULL != fdi->fd);
853 fdi->et = GNUNET_SCHEDULER_ET_IN;
854 fdi->sock = GNUNET_NETWORK_get_fd (read_nh[i]);
855 ++fdi;
856 }
857 for (i = 0; i != write_nh_len; ++i)
858 {
859 fdi->fd = write_nh[i];
860 GNUNET_assert (NULL != fdi->fd);
861 fdi->et = GNUNET_SCHEDULER_ET_OUT;
862 fdi->sock = GNUNET_NETWORK_get_fd (write_nh[i]);
863 ++fdi;
864 }
865 for (i = 0; i != read_fh_len; ++i)
866 {
867 fdi->fh = read_fh[i];
868 GNUNET_assert (NULL != fdi->fh);
869 fdi->et = GNUNET_SCHEDULER_ET_IN;
870 fdi->sock = (read_fh[i])->fd; // FIXME: does not work under WIN32
871 ++fdi;
872 }
873 for (i = 0; i != write_fh_len; ++i)
874 {
875 fdi->fh = write_fh[i];
876 GNUNET_assert (NULL != fdi->fh);
877 fdi->et = GNUNET_SCHEDULER_ET_OUT;
878 fdi->sock = (write_fh[i])->fd; // FIXME: does not work under WIN32
879 ++fdi;
880 }
881 }
882} 877}
883 878
884 879
@@ -896,56 +891,56 @@ init_fd_info (struct GNUNET_SCHEDULER_Task *t,
896 * @a driver_func on it, or -1 if no updating not desired. 891 * @a driver_func on it, or -1 if no updating not desired.
897 */ 892 */
898static void 893static void
899driver_add_multiple (struct GNUNET_SCHEDULER_Task *t) 894driver_add_multiple(struct GNUNET_SCHEDULER_Task *t)
900{ 895{
901 struct GNUNET_SCHEDULER_FdInfo *fdi; 896 struct GNUNET_SCHEDULER_FdInfo *fdi;
902 int success = GNUNET_YES; 897 int success = GNUNET_YES;
903 898
904 for (unsigned int i = 0; i != t->fds_len; ++i) 899 for (unsigned int i = 0; i != t->fds_len; ++i)
905 { 900 {
906 fdi = &t->fds[i]; 901 fdi = &t->fds[i];
907 success = scheduler_driver->add (scheduler_driver->cls, 902 success = scheduler_driver->add(scheduler_driver->cls,
908 t, 903 t,
909 fdi) && success; 904 fdi) && success;
910 fdi->et = GNUNET_SCHEDULER_ET_NONE; 905 fdi->et = GNUNET_SCHEDULER_ET_NONE;
911 } 906 }
912 if (GNUNET_YES != success) 907 if (GNUNET_YES != success)
913 { 908 {
914 LOG (GNUNET_ERROR_TYPE_ERROR, 909 LOG(GNUNET_ERROR_TYPE_ERROR,
915 "driver could not add task\n"); 910 "driver could not add task\n");
916 } 911 }
917} 912}
918 913
919 914
920static void 915static void
921install_parent_control_handler (void *cls) 916install_parent_control_handler(void *cls)
922{ 917{
923 (void) cls; 918 (void)cls;
924 install_parent_control_task = NULL; 919 install_parent_control_task = NULL;
925 GNUNET_OS_install_parent_control_handler (NULL); 920 GNUNET_OS_install_parent_control_handler(NULL);
926} 921}
927 922
928 923
929static void 924static void
930shutdown_pipe_cb (void *cls) 925shutdown_pipe_cb(void *cls)
931{ 926{
932 char c; 927 char c;
933 const struct GNUNET_DISK_FileHandle *pr; 928 const struct GNUNET_DISK_FileHandle *pr;
934 929
935 (void) cls; 930 (void)cls;
936 shutdown_pipe_task = NULL; 931 shutdown_pipe_task = NULL;
937 pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle, 932 pr = GNUNET_DISK_pipe_handle(shutdown_pipe_handle,
938 GNUNET_DISK_PIPE_END_READ); 933 GNUNET_DISK_PIPE_END_READ);
939 GNUNET_assert (! GNUNET_DISK_handle_invalid (pr)); 934 GNUNET_assert(!GNUNET_DISK_handle_invalid(pr));
940 /* consume the signal */ 935 /* consume the signal */
941 GNUNET_DISK_file_read (pr, &c, sizeof (c)); 936 GNUNET_DISK_file_read(pr, &c, sizeof(c));
942 /* mark all active tasks as ready due to shutdown */ 937 /* mark all active tasks as ready due to shutdown */
943 GNUNET_SCHEDULER_shutdown (); 938 GNUNET_SCHEDULER_shutdown();
944 shutdown_pipe_task = 939 shutdown_pipe_task =
945 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 940 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
946 pr, 941 pr,
947 &shutdown_pipe_cb, 942 &shutdown_pipe_cb,
948 NULL); 943 NULL);
949} 944}
950 945
951 946
@@ -962,62 +957,62 @@ shutdown_pipe_cb (void *cls)
962 * @return original closure of the task 957 * @return original closure of the task
963 */ 958 */
964void * 959void *
965GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task) 960GNUNET_SCHEDULER_cancel(struct GNUNET_SCHEDULER_Task *task)
966{ 961{
967 enum GNUNET_SCHEDULER_Priority p; 962 enum GNUNET_SCHEDULER_Priority p;
968 int is_fd_task; 963 int is_fd_task;
969 void *ret; 964 void *ret;
970 965
971 LOG (GNUNET_ERROR_TYPE_DEBUG, 966 LOG(GNUNET_ERROR_TYPE_DEBUG,
972 "canceling task %p\n", 967 "canceling task %p\n",
973 task); 968 task);
974 969
975 /* scheduler must be running */ 970 /* scheduler must be running */
976 GNUNET_assert (NULL != scheduler_driver); 971 GNUNET_assert(NULL != scheduler_driver);
977 is_fd_task = (NULL != task->fds); 972 is_fd_task = (NULL != task->fds);
978 if (is_fd_task) 973 if (is_fd_task)
979 {
980 int del_result = scheduler_driver->del (scheduler_driver->cls, task);
981 if (GNUNET_OK != del_result)
982 {
983 LOG (GNUNET_ERROR_TYPE_ERROR,
984 "driver could not delete task\n");
985 GNUNET_assert (0);
986 }
987 }
988 if (! task->in_ready_list)
989 {
990 if (is_fd_task)
991 { 974 {
992 GNUNET_CONTAINER_DLL_remove (pending_head, 975 int del_result = scheduler_driver->del(scheduler_driver->cls, task);
993 pending_tail, 976 if (GNUNET_OK != del_result)
994 task); 977 {
978 LOG(GNUNET_ERROR_TYPE_ERROR,
979 "driver could not delete task\n");
980 GNUNET_assert(0);
981 }
995 } 982 }
996 else if (GNUNET_YES == task->on_shutdown) 983 if (!task->in_ready_list)
997 { 984 {
998 GNUNET_CONTAINER_DLL_remove (shutdown_head, 985 if (is_fd_task)
999 shutdown_tail, 986 {
1000 task); 987 GNUNET_CONTAINER_DLL_remove(pending_head,
988 pending_tail,
989 task);
990 }
991 else if (GNUNET_YES == task->on_shutdown)
992 {
993 GNUNET_CONTAINER_DLL_remove(shutdown_head,
994 shutdown_tail,
995 task);
996 }
997 else
998 {
999 GNUNET_CONTAINER_DLL_remove(pending_timeout_head,
1000 pending_timeout_tail,
1001 task);
1002 if (pending_timeout_last == task)
1003 pending_timeout_last = NULL;
1004 }
1001 } 1005 }
1002 else 1006 else
1003 { 1007 {
1004 GNUNET_CONTAINER_DLL_remove (pending_timeout_head, 1008 p = check_priority(task->priority);
1005 pending_timeout_tail, 1009 GNUNET_CONTAINER_DLL_remove(ready_head[p],
1006 task); 1010 ready_tail[p],
1007 if (pending_timeout_last == task) 1011 task);
1008 pending_timeout_last = NULL; 1012 ready_count--;
1009 } 1013 }
1010 }
1011 else
1012 {
1013 p = check_priority (task->priority);
1014 GNUNET_CONTAINER_DLL_remove (ready_head[p],
1015 ready_tail[p],
1016 task);
1017 ready_count--;
1018 }
1019 ret = task->callback_cls; 1014 ret = task->callback_cls;
1020 destroy_task (task); 1015 destroy_task(task);
1021 return ret; 1016 return ret;
1022} 1017}
1023 1018
@@ -1028,19 +1023,19 @@ GNUNET_SCHEDULER_cancel (struct GNUNET_SCHEDULER_Task *task)
1028 * @param t task to initialize 1023 * @param t task to initialize
1029 */ 1024 */
1030static void 1025static void
1031init_backtrace (struct GNUNET_SCHEDULER_Task *t) 1026init_backtrace(struct GNUNET_SCHEDULER_Task *t)
1032{ 1027{
1033#if EXECINFO 1028#if EXECINFO
1034 void *backtrace_array[MAX_TRACE_DEPTH]; 1029 void *backtrace_array[MAX_TRACE_DEPTH];
1035 1030
1036 t->num_backtrace_strings 1031 t->num_backtrace_strings
1037 = backtrace (backtrace_array, MAX_TRACE_DEPTH); 1032 = backtrace(backtrace_array, MAX_TRACE_DEPTH);
1038 t->backtrace_strings = 1033 t->backtrace_strings =
1039 backtrace_symbols (backtrace_array, 1034 backtrace_symbols(backtrace_array,
1040 t->num_backtrace_strings); 1035 t->num_backtrace_strings);
1041 dump_backtrace (t); 1036 dump_backtrace(t);
1042#else 1037#else
1043 (void) t; 1038 (void)t;
1044#endif 1039#endif
1045} 1040}
1046 1041
@@ -1056,32 +1051,32 @@ init_backtrace (struct GNUNET_SCHEDULER_Task *t)
1056 * @param priority priority to use for the task 1051 * @param priority priority to use for the task
1057 */ 1052 */
1058void 1053void
1059GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback task, 1054GNUNET_SCHEDULER_add_with_reason_and_priority(GNUNET_SCHEDULER_TaskCallback task,
1060 void *task_cls, 1055 void *task_cls,
1061 enum GNUNET_SCHEDULER_Reason reason, 1056 enum GNUNET_SCHEDULER_Reason reason,
1062 enum GNUNET_SCHEDULER_Priority priority) 1057 enum GNUNET_SCHEDULER_Priority priority)
1063{ 1058{
1064 struct GNUNET_SCHEDULER_Task *t; 1059 struct GNUNET_SCHEDULER_Task *t;
1065 1060
1066 /* scheduler must be running */ 1061 /* scheduler must be running */
1067 GNUNET_assert (NULL != scheduler_driver); 1062 GNUNET_assert(NULL != scheduler_driver);
1068 GNUNET_assert (NULL != task); 1063 GNUNET_assert(NULL != task);
1069 t = GNUNET_new (struct GNUNET_SCHEDULER_Task); 1064 t = GNUNET_new(struct GNUNET_SCHEDULER_Task);
1070 t->read_fd = -1; 1065 t->read_fd = -1;
1071 t->write_fd = -1; 1066 t->write_fd = -1;
1072 t->callback = task; 1067 t->callback = task;
1073 t->callback_cls = task_cls; 1068 t->callback_cls = task_cls;
1074#if PROFILE_DELAYS 1069#if PROFILE_DELAYS
1075 t->start_time = GNUNET_TIME_absolute_get (); 1070 t->start_time = GNUNET_TIME_absolute_get();
1076#endif 1071#endif
1077 t->reason = reason; 1072 t->reason = reason;
1078 t->priority = check_priority (priority); 1073 t->priority = check_priority(priority);
1079 t->lifeness = current_lifeness; 1074 t->lifeness = current_lifeness;
1080 LOG (GNUNET_ERROR_TYPE_DEBUG, 1075 LOG(GNUNET_ERROR_TYPE_DEBUG,
1081 "Adding continuation task %p\n", 1076 "Adding continuation task %p\n",
1082 t); 1077 t);
1083 init_backtrace (t); 1078 init_backtrace(t);
1084 queue_ready_task (t); 1079 queue_ready_task(t);
1085} 1080}
1086 1081
1087 1082
@@ -1097,68 +1092,68 @@ GNUNET_SCHEDULER_add_with_reason_and_priority (GNUNET_SCHEDULER_TaskCallback tas
1097 * only valid until @a task is started! 1092 * only valid until @a task is started!
1098 */ 1093 */
1099struct GNUNET_SCHEDULER_Task * 1094struct GNUNET_SCHEDULER_Task *
1100GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at, 1095GNUNET_SCHEDULER_add_at_with_priority(struct GNUNET_TIME_Absolute at,
1101 enum GNUNET_SCHEDULER_Priority priority, 1096 enum GNUNET_SCHEDULER_Priority priority,
1102 GNUNET_SCHEDULER_TaskCallback task, 1097 GNUNET_SCHEDULER_TaskCallback task,
1103 void *task_cls) 1098 void *task_cls)
1104{ 1099{
1105 struct GNUNET_SCHEDULER_Task *t; 1100 struct GNUNET_SCHEDULER_Task *t;
1106 struct GNUNET_SCHEDULER_Task *pos; 1101 struct GNUNET_SCHEDULER_Task *pos;
1107 struct GNUNET_SCHEDULER_Task *prev; 1102 struct GNUNET_SCHEDULER_Task *prev;
1108 1103
1109 /* scheduler must be running */ 1104 /* scheduler must be running */
1110 GNUNET_assert (NULL != scheduler_driver); 1105 GNUNET_assert(NULL != scheduler_driver);
1111 GNUNET_assert (NULL != task); 1106 GNUNET_assert(NULL != task);
1112 t = GNUNET_new (struct GNUNET_SCHEDULER_Task); 1107 t = GNUNET_new(struct GNUNET_SCHEDULER_Task);
1113 GNUNET_async_scope_get (&t->scope); 1108 GNUNET_async_scope_get(&t->scope);
1114 t->callback = task; 1109 t->callback = task;
1115 t->callback_cls = task_cls; 1110 t->callback_cls = task_cls;
1116 t->read_fd = -1; 1111 t->read_fd = -1;
1117 t->write_fd = -1; 1112 t->write_fd = -1;
1118#if PROFILE_DELAYS 1113#if PROFILE_DELAYS
1119 t->start_time = GNUNET_TIME_absolute_get (); 1114 t->start_time = GNUNET_TIME_absolute_get();
1120#endif 1115#endif
1121 t->timeout = at; 1116 t->timeout = at;
1122 t->priority = check_priority (priority); 1117 t->priority = check_priority(priority);
1123 t->lifeness = current_lifeness; 1118 t->lifeness = current_lifeness;
1124 /* try tail first (optimization in case we are 1119 /* try tail first (optimization in case we are
1125 * appending to a long list of tasks with timeouts) */ 1120 * appending to a long list of tasks with timeouts) */
1126 if ( (NULL == pending_timeout_head) || 1121 if ((NULL == pending_timeout_head) ||
1127 (at.abs_value_us < pending_timeout_head->timeout.abs_value_us) ) 1122 (at.abs_value_us < pending_timeout_head->timeout.abs_value_us))
1128 { 1123 {
1129 GNUNET_CONTAINER_DLL_insert (pending_timeout_head, 1124 GNUNET_CONTAINER_DLL_insert(pending_timeout_head,
1130 pending_timeout_tail, 1125 pending_timeout_tail,
1131 t); 1126 t);
1132 } 1127 }
1133 else 1128 else
1134 {
1135 /* first move from heuristic start backwards to before start time */
1136 prev = pending_timeout_last;
1137 while ( (NULL != prev) &&
1138 (prev->timeout.abs_value_us > t->timeout.abs_value_us) )
1139 prev = prev->prev;
1140 /* now, move from heuristic start (or head of list) forward to insertion point */
1141 if (NULL == prev)
1142 pos = pending_timeout_head;
1143 else
1144 pos = prev->next;
1145 while ((NULL != pos) && (pos->timeout.abs_value_us <= t->timeout.abs_value_us))
1146 { 1129 {
1147 prev = pos; 1130 /* first move from heuristic start backwards to before start time */
1148 pos = pos->next; 1131 prev = pending_timeout_last;
1132 while ((NULL != prev) &&
1133 (prev->timeout.abs_value_us > t->timeout.abs_value_us))
1134 prev = prev->prev;
1135 /* now, move from heuristic start (or head of list) forward to insertion point */
1136 if (NULL == prev)
1137 pos = pending_timeout_head;
1138 else
1139 pos = prev->next;
1140 while ((NULL != pos) && (pos->timeout.abs_value_us <= t->timeout.abs_value_us))
1141 {
1142 prev = pos;
1143 pos = pos->next;
1144 }
1145 GNUNET_CONTAINER_DLL_insert_after(pending_timeout_head,
1146 pending_timeout_tail,
1147 prev,
1148 t);
1149 } 1149 }
1150 GNUNET_CONTAINER_DLL_insert_after (pending_timeout_head,
1151 pending_timeout_tail,
1152 prev,
1153 t);
1154 }
1155 /* finally, update heuristic insertion point to last insertion... */ 1150 /* finally, update heuristic insertion point to last insertion... */
1156 pending_timeout_last = t; 1151 pending_timeout_last = t;
1157 1152
1158 LOG (GNUNET_ERROR_TYPE_DEBUG, 1153 LOG(GNUNET_ERROR_TYPE_DEBUG,
1159 "Adding task %p\n", 1154 "Adding task %p\n",
1160 t); 1155 t);
1161 init_backtrace (t); 1156 init_backtrace(t);
1162 return t; 1157 return t;
1163} 1158}
1164 1159
@@ -1175,15 +1170,15 @@ GNUNET_SCHEDULER_add_at_with_priority (struct GNUNET_TIME_Absolute at,
1175 * only valid until @a task is started! 1170 * only valid until @a task is started!
1176 */ 1171 */
1177struct GNUNET_SCHEDULER_Task * 1172struct GNUNET_SCHEDULER_Task *
1178GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay, 1173GNUNET_SCHEDULER_add_delayed_with_priority(struct GNUNET_TIME_Relative delay,
1179 enum GNUNET_SCHEDULER_Priority priority, 1174 enum GNUNET_SCHEDULER_Priority priority,
1180 GNUNET_SCHEDULER_TaskCallback task, 1175 GNUNET_SCHEDULER_TaskCallback task,
1181 void *task_cls) 1176 void *task_cls)
1182{ 1177{
1183 return GNUNET_SCHEDULER_add_at_with_priority (GNUNET_TIME_relative_to_absolute (delay), 1178 return GNUNET_SCHEDULER_add_at_with_priority(GNUNET_TIME_relative_to_absolute(delay),
1184 priority, 1179 priority,
1185 task, 1180 task,
1186 task_cls); 1181 task_cls);
1187} 1182}
1188 1183
1189 1184
@@ -1197,14 +1192,14 @@ GNUNET_SCHEDULER_add_delayed_with_priority (struct GNUNET_TIME_Relative delay,
1197 * only valid until @a task is started! 1192 * only valid until @a task is started!
1198 */ 1193 */
1199struct GNUNET_SCHEDULER_Task * 1194struct GNUNET_SCHEDULER_Task *
1200GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio, 1195GNUNET_SCHEDULER_add_with_priority(enum GNUNET_SCHEDULER_Priority prio,
1201 GNUNET_SCHEDULER_TaskCallback task, 1196 GNUNET_SCHEDULER_TaskCallback task,
1202 void *task_cls) 1197 void *task_cls)
1203{ 1198{
1204 return GNUNET_SCHEDULER_add_delayed_with_priority (GNUNET_TIME_UNIT_ZERO, 1199 return GNUNET_SCHEDULER_add_delayed_with_priority(GNUNET_TIME_UNIT_ZERO,
1205 prio, 1200 prio,
1206 task, 1201 task,
1207 task_cls); 1202 task_cls);
1208} 1203}
1209 1204
1210 1205
@@ -1220,14 +1215,14 @@ GNUNET_SCHEDULER_add_with_priority (enum GNUNET_SCHEDULER_Priority prio,
1220 * only valid until @a task is started! 1215 * only valid until @a task is started!
1221 */ 1216 */
1222struct GNUNET_SCHEDULER_Task * 1217struct GNUNET_SCHEDULER_Task *
1223GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at, 1218GNUNET_SCHEDULER_add_at(struct GNUNET_TIME_Absolute at,
1224 GNUNET_SCHEDULER_TaskCallback task, 1219 GNUNET_SCHEDULER_TaskCallback task,
1225 void *task_cls) 1220 void *task_cls)
1226{ 1221{
1227 return GNUNET_SCHEDULER_add_at_with_priority (at, 1222 return GNUNET_SCHEDULER_add_at_with_priority(at,
1228 GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1223 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1229 task, 1224 task,
1230 task_cls); 1225 task_cls);
1231} 1226}
1232 1227
1233 1228
@@ -1243,14 +1238,14 @@ GNUNET_SCHEDULER_add_at (struct GNUNET_TIME_Absolute at,
1243 * only valid until @a task is started! 1238 * only valid until @a task is started!
1244 */ 1239 */
1245struct GNUNET_SCHEDULER_Task * 1240struct GNUNET_SCHEDULER_Task *
1246GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay, 1241GNUNET_SCHEDULER_add_delayed(struct GNUNET_TIME_Relative delay,
1247 GNUNET_SCHEDULER_TaskCallback task, 1242 GNUNET_SCHEDULER_TaskCallback task,
1248 void *task_cls) 1243 void *task_cls)
1249{ 1244{
1250 return GNUNET_SCHEDULER_add_delayed_with_priority (delay, 1245 return GNUNET_SCHEDULER_add_delayed_with_priority(delay,
1251 GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1246 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1252 task, 1247 task,
1253 task_cls); 1248 task_cls);
1254} 1249}
1255 1250
1256 1251
@@ -1270,12 +1265,12 @@ GNUNET_SCHEDULER_add_delayed (struct GNUNET_TIME_Relative delay,
1270 * only valid until @a task is started! 1265 * only valid until @a task is started!
1271 */ 1266 */
1272struct GNUNET_SCHEDULER_Task * 1267struct GNUNET_SCHEDULER_Task *
1273GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task, 1268GNUNET_SCHEDULER_add_now(GNUNET_SCHEDULER_TaskCallback task,
1274 void *task_cls) 1269 void *task_cls)
1275{ 1270{
1276 return GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_ZERO, 1271 return GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_ZERO,
1277 task, 1272 task,
1278 task_cls); 1273 task_cls);
1279} 1274}
1280 1275
1281 1276
@@ -1290,34 +1285,34 @@ GNUNET_SCHEDULER_add_now (GNUNET_SCHEDULER_TaskCallback task,
1290 * only valid until @a task is started! 1285 * only valid until @a task is started!
1291 */ 1286 */
1292struct GNUNET_SCHEDULER_Task * 1287struct GNUNET_SCHEDULER_Task *
1293GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task, 1288GNUNET_SCHEDULER_add_shutdown(GNUNET_SCHEDULER_TaskCallback task,
1294 void *task_cls) 1289 void *task_cls)
1295{ 1290{
1296 struct GNUNET_SCHEDULER_Task *t; 1291 struct GNUNET_SCHEDULER_Task *t;
1297 1292
1298 /* scheduler must be running */ 1293 /* scheduler must be running */
1299 GNUNET_assert (NULL != scheduler_driver); 1294 GNUNET_assert(NULL != scheduler_driver);
1300 GNUNET_assert (NULL != task); 1295 GNUNET_assert(NULL != task);
1301 t = GNUNET_new (struct GNUNET_SCHEDULER_Task); 1296 t = GNUNET_new(struct GNUNET_SCHEDULER_Task);
1302 GNUNET_async_scope_get (&t->scope); 1297 GNUNET_async_scope_get(&t->scope);
1303 t->callback = task; 1298 t->callback = task;
1304 t->callback_cls = task_cls; 1299 t->callback_cls = task_cls;
1305 t->read_fd = -1; 1300 t->read_fd = -1;
1306 t->write_fd = -1; 1301 t->write_fd = -1;
1307#if PROFILE_DELAYS 1302#if PROFILE_DELAYS
1308 t->start_time = GNUNET_TIME_absolute_get (); 1303 t->start_time = GNUNET_TIME_absolute_get();
1309#endif 1304#endif
1310 t->timeout = GNUNET_TIME_UNIT_FOREVER_ABS; 1305 t->timeout = GNUNET_TIME_UNIT_FOREVER_ABS;
1311 t->priority = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN; 1306 t->priority = GNUNET_SCHEDULER_PRIORITY_SHUTDOWN;
1312 t->on_shutdown = GNUNET_YES; 1307 t->on_shutdown = GNUNET_YES;
1313 t->lifeness = GNUNET_NO; 1308 t->lifeness = GNUNET_NO;
1314 GNUNET_CONTAINER_DLL_insert (shutdown_head, 1309 GNUNET_CONTAINER_DLL_insert(shutdown_head,
1315 shutdown_tail, 1310 shutdown_tail,
1316 t); 1311 t);
1317 LOG (GNUNET_ERROR_TYPE_DEBUG, 1312 LOG(GNUNET_ERROR_TYPE_DEBUG,
1318 "Adding shutdown task %p\n", 1313 "Adding shutdown task %p\n",
1319 t); 1314 t);
1320 init_backtrace (t); 1315 init_backtrace(t);
1321 return t; 1316 return t;
1322} 1317}
1323 1318
@@ -1337,13 +1332,13 @@ GNUNET_SCHEDULER_add_shutdown (GNUNET_SCHEDULER_TaskCallback task,
1337 * only valid until @a task is started! 1332 * only valid until @a task is started!
1338 */ 1333 */
1339struct GNUNET_SCHEDULER_Task * 1334struct GNUNET_SCHEDULER_Task *
1340GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness, 1335GNUNET_SCHEDULER_add_now_with_lifeness(int lifeness,
1341 GNUNET_SCHEDULER_TaskCallback task, 1336 GNUNET_SCHEDULER_TaskCallback task,
1342 void *task_cls) 1337 void *task_cls)
1343{ 1338{
1344 struct GNUNET_SCHEDULER_Task *ret; 1339 struct GNUNET_SCHEDULER_Task *ret;
1345 1340
1346 ret = GNUNET_SCHEDULER_add_now (task, task_cls); 1341 ret = GNUNET_SCHEDULER_add_now(task, task_cls);
1347 ret->lifeness = lifeness; 1342 ret->lifeness = lifeness;
1348 return ret; 1343 return ret;
1349} 1344}
@@ -1357,21 +1352,21 @@ GNUNET_SCHEDULER_add_now_with_lifeness (int lifeness,
1357 * @param raw_fd the raw file descriptor to check 1352 * @param raw_fd the raw file descriptor to check
1358 */ 1353 */
1359void 1354void
1360check_fd (struct GNUNET_SCHEDULER_Task *t, int raw_fd) 1355check_fd(struct GNUNET_SCHEDULER_Task *t, int raw_fd)
1361{ 1356{
1362 if (-1 != raw_fd) 1357 if (-1 != raw_fd)
1363 {
1364 int flags = fcntl (raw_fd, F_GETFD);
1365
1366 if ((flags == -1) && (errno == EBADF))
1367 { 1358 {
1368 LOG (GNUNET_ERROR_TYPE_ERROR, 1359 int flags = fcntl(raw_fd, F_GETFD);
1369 "Got invalid file descriptor %d!\n", 1360
1370 raw_fd); 1361 if ((flags == -1) && (errno == EBADF))
1371 init_backtrace (t); 1362 {
1372 GNUNET_assert (0); 1363 LOG(GNUNET_ERROR_TYPE_ERROR,
1364 "Got invalid file descriptor %d!\n",
1365 raw_fd);
1366 init_backtrace(t);
1367 GNUNET_assert(0);
1368 }
1373 } 1369 }
1374 }
1375} 1370}
1376#endif 1371#endif
1377 1372
@@ -1403,52 +1398,52 @@ check_fd (struct GNUNET_SCHEDULER_Task *t, int raw_fd)
1403 */ 1398 */
1404#ifndef MINGW 1399#ifndef MINGW
1405static struct GNUNET_SCHEDULER_Task * 1400static struct GNUNET_SCHEDULER_Task *
1406add_without_sets (struct GNUNET_TIME_Relative delay, 1401add_without_sets(struct GNUNET_TIME_Relative delay,
1407 enum GNUNET_SCHEDULER_Priority priority, 1402 enum GNUNET_SCHEDULER_Priority priority,
1408 const struct GNUNET_NETWORK_Handle *read_nh, 1403 const struct GNUNET_NETWORK_Handle *read_nh,
1409 const struct GNUNET_NETWORK_Handle *write_nh, 1404 const struct GNUNET_NETWORK_Handle *write_nh,
1410 const struct GNUNET_DISK_FileHandle *read_fh, 1405 const struct GNUNET_DISK_FileHandle *read_fh,
1411 const struct GNUNET_DISK_FileHandle *write_fh, 1406 const struct GNUNET_DISK_FileHandle *write_fh,
1412 GNUNET_SCHEDULER_TaskCallback task, 1407 GNUNET_SCHEDULER_TaskCallback task,
1413 void *task_cls) 1408 void *task_cls)
1414{ 1409{
1415 struct GNUNET_SCHEDULER_Task *t; 1410 struct GNUNET_SCHEDULER_Task *t;
1416 1411
1417 /* scheduler must be running */ 1412 /* scheduler must be running */
1418 GNUNET_assert (NULL != scheduler_driver); 1413 GNUNET_assert(NULL != scheduler_driver);
1419 GNUNET_assert (NULL != task); 1414 GNUNET_assert(NULL != task);
1420 t = GNUNET_new (struct GNUNET_SCHEDULER_Task); 1415 t = GNUNET_new(struct GNUNET_SCHEDULER_Task);
1421 GNUNET_async_scope_get (&t->scope); 1416 GNUNET_async_scope_get(&t->scope);
1422 init_fd_info (t, 1417 init_fd_info(t,
1423 &read_nh, 1418 &read_nh,
1424 read_nh ? 1 : 0, 1419 read_nh ? 1 : 0,
1425 &write_nh, 1420 &write_nh,
1426 write_nh ? 1 : 0, 1421 write_nh ? 1 : 0,
1427 &read_fh, 1422 &read_fh,
1428 read_fh ? 1 : 0, 1423 read_fh ? 1 : 0,
1429 &write_fh, 1424 &write_fh,
1430 write_fh ? 1 : 0); 1425 write_fh ? 1 : 0);
1431 t->callback = task; 1426 t->callback = task;
1432 t->callback_cls = task_cls; 1427 t->callback_cls = task_cls;
1433#if DEBUG_FDS 1428#if DEBUG_FDS
1434 check_fd (t, NULL != read_nh ? GNUNET_NETWORK_get_fd (read_nh) : -1); 1429 check_fd(t, NULL != read_nh ? GNUNET_NETWORK_get_fd(read_nh) : -1);
1435 check_fd (t, NULL != write_nh ? GNUNET_NETWORK_get_fd (write_nh) : -1); 1430 check_fd(t, NULL != write_nh ? GNUNET_NETWORK_get_fd(write_nh) : -1);
1436 check_fd (t, NULL != read_fh ? read_fh->fd : -1); 1431 check_fd(t, NULL != read_fh ? read_fh->fd : -1);
1437 check_fd (t, NULL != write_fh ? write_fh->fd : -1); 1432 check_fd(t, NULL != write_fh ? write_fh->fd : -1);
1438#endif 1433#endif
1439#if PROFILE_DELAYS 1434#if PROFILE_DELAYS
1440 t->start_time = GNUNET_TIME_absolute_get (); 1435 t->start_time = GNUNET_TIME_absolute_get();
1441#endif 1436#endif
1442 t->timeout = GNUNET_TIME_relative_to_absolute (delay); 1437 t->timeout = GNUNET_TIME_relative_to_absolute(delay);
1443 t->priority = check_priority ((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority); 1438 t->priority = check_priority((priority == GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : priority);
1444 t->lifeness = current_lifeness; 1439 t->lifeness = current_lifeness;
1445 GNUNET_CONTAINER_DLL_insert (pending_head, 1440 GNUNET_CONTAINER_DLL_insert(pending_head,
1446 pending_tail, 1441 pending_tail,
1447 t); 1442 t);
1448 driver_add_multiple (t); 1443 driver_add_multiple(t);
1449 max_priority_added = GNUNET_MAX (max_priority_added, 1444 max_priority_added = GNUNET_MAX(max_priority_added,
1450 t->priority); 1445 t->priority);
1451 init_backtrace (t); 1446 init_backtrace(t);
1452 return t; 1447 return t;
1453} 1448}
1454#endif 1449#endif
@@ -1475,14 +1470,14 @@ add_without_sets (struct GNUNET_TIME_Relative delay,
1475 * only valid until @a task is started! 1470 * only valid until @a task is started!
1476 */ 1471 */
1477struct GNUNET_SCHEDULER_Task * 1472struct GNUNET_SCHEDULER_Task *
1478GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay, 1473GNUNET_SCHEDULER_add_read_net(struct GNUNET_TIME_Relative delay,
1479 struct GNUNET_NETWORK_Handle *rfd, 1474 struct GNUNET_NETWORK_Handle *rfd,
1480 GNUNET_SCHEDULER_TaskCallback task, 1475 GNUNET_SCHEDULER_TaskCallback task,
1481 void *task_cls) 1476 void *task_cls)
1482{ 1477{
1483 return GNUNET_SCHEDULER_add_read_net_with_priority (delay, 1478 return GNUNET_SCHEDULER_add_read_net_with_priority(delay,
1484 GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1479 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1485 rfd, task, task_cls); 1480 rfd, task, task_cls);
1486} 1481}
1487 1482
1488 1483
@@ -1509,17 +1504,17 @@ GNUNET_SCHEDULER_add_read_net (struct GNUNET_TIME_Relative delay,
1509 * only valid until @a task is started! 1504 * only valid until @a task is started!
1510 */ 1505 */
1511struct GNUNET_SCHEDULER_Task * 1506struct GNUNET_SCHEDULER_Task *
1512GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay, 1507GNUNET_SCHEDULER_add_read_net_with_priority(struct GNUNET_TIME_Relative delay,
1513 enum GNUNET_SCHEDULER_Priority priority, 1508 enum GNUNET_SCHEDULER_Priority priority,
1514 struct GNUNET_NETWORK_Handle *rfd, 1509 struct GNUNET_NETWORK_Handle *rfd,
1515 GNUNET_SCHEDULER_TaskCallback task, 1510 GNUNET_SCHEDULER_TaskCallback task,
1516 void *task_cls) 1511 void *task_cls)
1517{ 1512{
1518 return GNUNET_SCHEDULER_add_net_with_priority (delay, priority, 1513 return GNUNET_SCHEDULER_add_net_with_priority(delay, priority,
1519 rfd, 1514 rfd,
1520 GNUNET_YES, 1515 GNUNET_YES,
1521 GNUNET_NO, 1516 GNUNET_NO,
1522 task, task_cls); 1517 task, task_cls);
1523} 1518}
1524 1519
1525 1520
@@ -1545,16 +1540,16 @@ GNUNET_SCHEDULER_add_read_net_with_priority (struct GNUNET_TIME_Relative delay,
1545 * only valid until @a task is started! 1540 * only valid until @a task is started!
1546 */ 1541 */
1547struct GNUNET_SCHEDULER_Task * 1542struct GNUNET_SCHEDULER_Task *
1548GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay, 1543GNUNET_SCHEDULER_add_write_net(struct GNUNET_TIME_Relative delay,
1549 struct GNUNET_NETWORK_Handle *wfd, 1544 struct GNUNET_NETWORK_Handle *wfd,
1550 GNUNET_SCHEDULER_TaskCallback task, 1545 GNUNET_SCHEDULER_TaskCallback task,
1551 void *task_cls) 1546 void *task_cls)
1552{ 1547{
1553 return GNUNET_SCHEDULER_add_net_with_priority (delay, 1548 return GNUNET_SCHEDULER_add_net_with_priority(delay,
1554 GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1549 GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1555 wfd, 1550 wfd,
1556 GNUNET_NO, GNUNET_YES, 1551 GNUNET_NO, GNUNET_YES,
1557 task, task_cls); 1552 task, task_cls);
1558} 1553}
1559 1554
1560/** 1555/**
@@ -1581,40 +1576,40 @@ GNUNET_SCHEDULER_add_write_net (struct GNUNET_TIME_Relative delay,
1581 * only valid until "task" is started! 1576 * only valid until "task" is started!
1582 */ 1577 */
1583struct GNUNET_SCHEDULER_Task * 1578struct GNUNET_SCHEDULER_Task *
1584GNUNET_SCHEDULER_add_net_with_priority (struct GNUNET_TIME_Relative delay, 1579GNUNET_SCHEDULER_add_net_with_priority(struct GNUNET_TIME_Relative delay,
1585 enum GNUNET_SCHEDULER_Priority priority, 1580 enum GNUNET_SCHEDULER_Priority priority,
1586 struct GNUNET_NETWORK_Handle *fd, 1581 struct GNUNET_NETWORK_Handle *fd,
1587 int on_read, 1582 int on_read,
1588 int on_write, 1583 int on_write,
1589 GNUNET_SCHEDULER_TaskCallback task, 1584 GNUNET_SCHEDULER_TaskCallback task,
1590 void *task_cls) 1585 void *task_cls)
1591{ 1586{
1592 /* scheduler must be running */ 1587 /* scheduler must be running */
1593 GNUNET_assert (NULL != scheduler_driver); 1588 GNUNET_assert(NULL != scheduler_driver);
1594 1589
1595#if MINGW 1590#if MINGW
1596 struct GNUNET_NETWORK_FDSet *s; 1591 struct GNUNET_NETWORK_FDSet *s;
1597 struct GNUNET_SCHEDULER_Task * ret; 1592 struct GNUNET_SCHEDULER_Task * ret;
1598 1593
1599 GNUNET_assert (NULL != fd); 1594 GNUNET_assert(NULL != fd);
1600 s = GNUNET_NETWORK_fdset_create (); 1595 s = GNUNET_NETWORK_fdset_create();
1601 GNUNET_NETWORK_fdset_set (s, fd); 1596 GNUNET_NETWORK_fdset_set(s, fd);
1602 ret = GNUNET_SCHEDULER_add_select ( 1597 ret = GNUNET_SCHEDULER_add_select(
1603 priority, delay, 1598 priority, delay,
1604 on_read ? s : NULL, 1599 on_read ? s : NULL,
1605 on_write ? s : NULL, 1600 on_write ? s : NULL,
1606 task, task_cls); 1601 task, task_cls);
1607 GNUNET_NETWORK_fdset_destroy (s); 1602 GNUNET_NETWORK_fdset_destroy(s);
1608 return ret; 1603 return ret;
1609#else 1604#else
1610 GNUNET_assert (on_read || on_write); 1605 GNUNET_assert(on_read || on_write);
1611 GNUNET_assert (GNUNET_NETWORK_get_fd (fd) >= 0); 1606 GNUNET_assert(GNUNET_NETWORK_get_fd(fd) >= 0);
1612 return add_without_sets (delay, priority, 1607 return add_without_sets(delay, priority,
1613 on_read ? fd : NULL, 1608 on_read ? fd : NULL,
1614 on_write ? fd : NULL, 1609 on_write ? fd : NULL,
1615 NULL, 1610 NULL,
1616 NULL, 1611 NULL,
1617 task, task_cls); 1612 task, task_cls);
1618#endif 1613#endif
1619} 1614}
1620 1615
@@ -1640,14 +1635,14 @@ GNUNET_SCHEDULER_add_net_with_priority (struct GNUNET_TIME_Relative delay,
1640 * only valid until @a task is started! 1635 * only valid until @a task is started!
1641 */ 1636 */
1642struct GNUNET_SCHEDULER_Task * 1637struct GNUNET_SCHEDULER_Task *
1643GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay, 1638GNUNET_SCHEDULER_add_read_file(struct GNUNET_TIME_Relative delay,
1644 const struct GNUNET_DISK_FileHandle *rfd, 1639 const struct GNUNET_DISK_FileHandle *rfd,
1645 GNUNET_SCHEDULER_TaskCallback task, void *task_cls) 1640 GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1646{ 1641{
1647 return GNUNET_SCHEDULER_add_file_with_priority ( 1642 return GNUNET_SCHEDULER_add_file_with_priority(
1648 delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1643 delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1649 rfd, GNUNET_YES, GNUNET_NO, 1644 rfd, GNUNET_YES, GNUNET_NO,
1650 task, task_cls); 1645 task, task_cls);
1651} 1646}
1652 1647
1653 1648
@@ -1672,14 +1667,14 @@ GNUNET_SCHEDULER_add_read_file (struct GNUNET_TIME_Relative delay,
1672 * only valid until @a task is started! 1667 * only valid until @a task is started!
1673 */ 1668 */
1674struct GNUNET_SCHEDULER_Task * 1669struct GNUNET_SCHEDULER_Task *
1675GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay, 1670GNUNET_SCHEDULER_add_write_file(struct GNUNET_TIME_Relative delay,
1676 const struct GNUNET_DISK_FileHandle *wfd, 1671 const struct GNUNET_DISK_FileHandle *wfd,
1677 GNUNET_SCHEDULER_TaskCallback task, void *task_cls) 1672 GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1678{ 1673{
1679 return GNUNET_SCHEDULER_add_file_with_priority ( 1674 return GNUNET_SCHEDULER_add_file_with_priority(
1680 delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT, 1675 delay, GNUNET_SCHEDULER_PRIORITY_DEFAULT,
1681 wfd, GNUNET_NO, GNUNET_YES, 1676 wfd, GNUNET_NO, GNUNET_YES,
1682 task, task_cls); 1677 task, task_cls);
1683} 1678}
1684 1679
1685 1680
@@ -1707,48 +1702,48 @@ GNUNET_SCHEDULER_add_write_file (struct GNUNET_TIME_Relative delay,
1707 * only valid until @a task is started! 1702 * only valid until @a task is started!
1708 */ 1703 */
1709struct GNUNET_SCHEDULER_Task * 1704struct GNUNET_SCHEDULER_Task *
1710GNUNET_SCHEDULER_add_file_with_priority (struct GNUNET_TIME_Relative delay, 1705GNUNET_SCHEDULER_add_file_with_priority(struct GNUNET_TIME_Relative delay,
1711 enum GNUNET_SCHEDULER_Priority priority, 1706 enum GNUNET_SCHEDULER_Priority priority,
1712 const struct GNUNET_DISK_FileHandle *fd, 1707 const struct GNUNET_DISK_FileHandle *fd,
1713 int on_read, int on_write, 1708 int on_read, int on_write,
1714 GNUNET_SCHEDULER_TaskCallback task, void *task_cls) 1709 GNUNET_SCHEDULER_TaskCallback task, void *task_cls)
1715{ 1710{
1716 /* scheduler must be running */ 1711 /* scheduler must be running */
1717 GNUNET_assert (NULL != scheduler_driver); 1712 GNUNET_assert(NULL != scheduler_driver);
1718 1713
1719#if MINGW 1714#if MINGW
1720 struct GNUNET_NETWORK_FDSet *s; 1715 struct GNUNET_NETWORK_FDSet *s;
1721 struct GNUNET_SCHEDULER_Task * ret; 1716 struct GNUNET_SCHEDULER_Task * ret;
1722 1717
1723 GNUNET_assert (NULL != fd); 1718 GNUNET_assert(NULL != fd);
1724 s = GNUNET_NETWORK_fdset_create (); 1719 s = GNUNET_NETWORK_fdset_create();
1725 GNUNET_NETWORK_fdset_handle_set (s, fd); 1720 GNUNET_NETWORK_fdset_handle_set(s, fd);
1726 ret = GNUNET_SCHEDULER_add_select ( 1721 ret = GNUNET_SCHEDULER_add_select(
1727 priority, delay, 1722 priority, delay,
1728 on_read ? s : NULL, 1723 on_read ? s : NULL,
1729 on_write ? s : NULL, 1724 on_write ? s : NULL,
1730 task, task_cls); 1725 task, task_cls);
1731 GNUNET_NETWORK_fdset_destroy (s); 1726 GNUNET_NETWORK_fdset_destroy(s);
1732 return ret; 1727 return ret;
1733#else 1728#else
1734 GNUNET_assert (on_read || on_write); 1729 GNUNET_assert(on_read || on_write);
1735 GNUNET_assert (fd->fd >= 0); 1730 GNUNET_assert(fd->fd >= 0);
1736 return add_without_sets (delay, priority, 1731 return add_without_sets(delay, priority,
1737 NULL, 1732 NULL,
1738 NULL, 1733 NULL,
1739 on_read ? fd : NULL, 1734 on_read ? fd : NULL,
1740 on_write ? fd : NULL, 1735 on_write ? fd : NULL,
1741 task, task_cls); 1736 task, task_cls);
1742#endif 1737#endif
1743} 1738}
1744 1739
1745 1740
1746void 1741void
1747extract_handles (const struct GNUNET_NETWORK_FDSet *fdset, 1742extract_handles(const struct GNUNET_NETWORK_FDSet *fdset,
1748 const struct GNUNET_NETWORK_Handle ***ntarget, 1743 const struct GNUNET_NETWORK_Handle ***ntarget,
1749 unsigned int *extracted_nhandles, 1744 unsigned int *extracted_nhandles,
1750 const struct GNUNET_DISK_FileHandle ***ftarget, 1745 const struct GNUNET_DISK_FileHandle ***ftarget,
1751 unsigned int *extracted_fhandles) 1746 unsigned int *extracted_fhandles)
1752{ 1747{
1753 // FIXME: this implementation only works for unix, for WIN32 the file handles 1748 // FIXME: this implementation only works for unix, for WIN32 the file handles
1754 // in fdset must be handled separately 1749 // in fdset must be handled separately
@@ -1762,31 +1757,31 @@ extract_handles (const struct GNUNET_NETWORK_FDSet *fdset,
1762 nhandles_len = 0; 1757 nhandles_len = 0;
1763 fhandles_len = 0; 1758 fhandles_len = 0;
1764 for (int sock = 0; sock != fdset->nsds; ++sock) 1759 for (int sock = 0; sock != fdset->nsds; ++sock)
1765 {
1766 if (GNUNET_YES == GNUNET_NETWORK_fdset_test_native (fdset, sock))
1767 { 1760 {
1768 struct GNUNET_NETWORK_Handle *nhandle; 1761 if (GNUNET_YES == GNUNET_NETWORK_fdset_test_native(fdset, sock))
1769 struct GNUNET_DISK_FileHandle *fhandle;
1770
1771 nhandle = GNUNET_NETWORK_socket_box_native (sock);
1772 if (NULL != nhandle)
1773 {
1774 GNUNET_array_append (nhandles, nhandles_len, nhandle);
1775 }
1776 else
1777 {
1778 fhandle = GNUNET_DISK_get_handle_from_int_fd (sock);
1779 if (NULL != fhandle)
1780 { 1762 {
1781 GNUNET_array_append (fhandles, fhandles_len, fhandle); 1763 struct GNUNET_NETWORK_Handle *nhandle;
1764 struct GNUNET_DISK_FileHandle *fhandle;
1765
1766 nhandle = GNUNET_NETWORK_socket_box_native(sock);
1767 if (NULL != nhandle)
1768 {
1769 GNUNET_array_append(nhandles, nhandles_len, nhandle);
1770 }
1771 else
1772 {
1773 fhandle = GNUNET_DISK_get_handle_from_int_fd(sock);
1774 if (NULL != fhandle)
1775 {
1776 GNUNET_array_append(fhandles, fhandles_len, fhandle);
1777 }
1778 else
1779 {
1780 GNUNET_assert(0);
1781 }
1782 }
1782 } 1783 }
1783 else
1784 {
1785 GNUNET_assert (0);
1786 }
1787 }
1788 } 1784 }
1789 }
1790 *ntarget = nhandles_len > 0 ? nhandles : NULL; 1785 *ntarget = nhandles_len > 0 ? nhandles : NULL;
1791 *ftarget = fhandles_len > 0 ? fhandles : NULL; 1786 *ftarget = fhandles_len > 0 ? fhandles : NULL;
1792 *extracted_nhandles = nhandles_len; 1787 *extracted_nhandles = nhandles_len;
@@ -1826,12 +1821,12 @@ extract_handles (const struct GNUNET_NETWORK_FDSet *fdset,
1826 * only valid until @a task is started! 1821 * only valid until @a task is started!
1827 */ 1822 */
1828struct GNUNET_SCHEDULER_Task * 1823struct GNUNET_SCHEDULER_Task *
1829GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio, 1824GNUNET_SCHEDULER_add_select(enum GNUNET_SCHEDULER_Priority prio,
1830 struct GNUNET_TIME_Relative delay, 1825 struct GNUNET_TIME_Relative delay,
1831 const struct GNUNET_NETWORK_FDSet *rs, 1826 const struct GNUNET_NETWORK_FDSet *rs,
1832 const struct GNUNET_NETWORK_FDSet *ws, 1827 const struct GNUNET_NETWORK_FDSet *ws,
1833 GNUNET_SCHEDULER_TaskCallback task, 1828 GNUNET_SCHEDULER_TaskCallback task,
1834 void *task_cls) 1829 void *task_cls)
1835{ 1830{
1836 struct GNUNET_SCHEDULER_Task *t; 1831 struct GNUNET_SCHEDULER_Task *t;
1837 const struct GNUNET_NETWORK_Handle **read_nhandles = NULL; 1832 const struct GNUNET_NETWORK_Handle **read_nhandles = NULL;
@@ -1844,8 +1839,8 @@ GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1844 unsigned int write_fhandles_len = 0; 1839 unsigned int write_fhandles_len = 0;
1845 1840
1846 /* scheduler must be running */ 1841 /* scheduler must be running */
1847 GNUNET_assert (NULL != scheduler_driver); 1842 GNUNET_assert(NULL != scheduler_driver);
1848 GNUNET_assert (NULL != task); 1843 GNUNET_assert(NULL != task);
1849 int no_rs = (NULL == rs); 1844 int no_rs = (NULL == rs);
1850 int no_ws = (NULL == ws); 1845 int no_ws = (NULL == ws);
1851 int empty_rs = (NULL != rs) && (0 == rs->nsds); 1846 int empty_rs = (NULL != rs) && (0 == rs->nsds);
@@ -1854,25 +1849,25 @@ GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1854 (empty_rs && empty_ws) || 1849 (empty_rs && empty_ws) ||
1855 (no_rs && empty_ws) || 1850 (no_rs && empty_ws) ||
1856 (no_ws && empty_rs); 1851 (no_ws && empty_rs);
1857 if (! no_fds) 1852 if (!no_fds)
1858 {
1859 if (NULL != rs)
1860 { 1853 {
1861 extract_handles (rs, 1854 if (NULL != rs)
1862 &read_nhandles, 1855 {
1863 &read_nhandles_len, 1856 extract_handles(rs,
1864 &read_fhandles, 1857 &read_nhandles,
1865 &read_fhandles_len); 1858 &read_nhandles_len,
1866 } 1859 &read_fhandles,
1867 if (NULL != ws) 1860 &read_fhandles_len);
1868 { 1861 }
1869 extract_handles (ws, 1862 if (NULL != ws)
1870 &write_nhandles, 1863 {
1871 &write_nhandles_len, 1864 extract_handles(ws,
1872 &write_fhandles, 1865 &write_nhandles,
1873 &write_fhandles_len); 1866 &write_nhandles_len,
1867 &write_fhandles,
1868 &write_fhandles_len);
1869 }
1874 } 1870 }
1875 }
1876 /** 1871 /**
1877 * here we consider the case that a GNUNET_NETWORK_FDSet might be empty 1872 * here we consider the case that a GNUNET_NETWORK_FDSet might be empty
1878 * although its maximum FD number (nsds) is greater than 0. We handle 1873 * although its maximum FD number (nsds) is greater than 0. We handle
@@ -1885,49 +1880,49 @@ GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1885 (0 == write_nhandles_len) && 1880 (0 == write_nhandles_len) &&
1886 (0 == write_fhandles_len); 1881 (0 == write_fhandles_len);
1887 if (no_fds || no_fds_extracted) 1882 if (no_fds || no_fds_extracted)
1888 return GNUNET_SCHEDULER_add_delayed_with_priority (delay, 1883 return GNUNET_SCHEDULER_add_delayed_with_priority(delay,
1889 prio, 1884 prio,
1890 task, 1885 task,
1891 task_cls); 1886 task_cls);
1892 t = GNUNET_new (struct GNUNET_SCHEDULER_Task); 1887 t = GNUNET_new(struct GNUNET_SCHEDULER_Task);
1893 GNUNET_async_scope_get (&t->scope); 1888 GNUNET_async_scope_get(&t->scope);
1894 init_fd_info (t, 1889 init_fd_info(t,
1895 read_nhandles, 1890 read_nhandles,
1896 read_nhandles_len, 1891 read_nhandles_len,
1897 write_nhandles, 1892 write_nhandles,
1898 write_nhandles_len, 1893 write_nhandles_len,
1899 read_fhandles, 1894 read_fhandles,
1900 read_fhandles_len, 1895 read_fhandles_len,
1901 write_fhandles, 1896 write_fhandles,
1902 write_fhandles_len); 1897 write_fhandles_len);
1903 t->callback = task; 1898 t->callback = task;
1904 t->callback_cls = task_cls; 1899 t->callback_cls = task_cls;
1905 t->own_handles = GNUNET_YES; 1900 t->own_handles = GNUNET_YES;
1906 /* free the arrays of pointers to network / file handles, the actual 1901 /* free the arrays of pointers to network / file handles, the actual
1907 * handles will be freed in destroy_task */ 1902 * handles will be freed in destroy_task */
1908 GNUNET_array_grow (read_nhandles, read_nhandles_len, 0); 1903 GNUNET_array_grow(read_nhandles, read_nhandles_len, 0);
1909 GNUNET_array_grow (write_nhandles, write_nhandles_len, 0); 1904 GNUNET_array_grow(write_nhandles, write_nhandles_len, 0);
1910 GNUNET_array_grow (read_fhandles, read_fhandles_len, 0); 1905 GNUNET_array_grow(read_fhandles, read_fhandles_len, 0);
1911 GNUNET_array_grow (write_fhandles, write_fhandles_len, 0); 1906 GNUNET_array_grow(write_fhandles, write_fhandles_len, 0);
1912#if PROFILE_DELAYS 1907#if PROFILE_DELAYS
1913 t->start_time = GNUNET_TIME_absolute_get (); 1908 t->start_time = GNUNET_TIME_absolute_get();
1914#endif 1909#endif
1915 t->timeout = GNUNET_TIME_relative_to_absolute (delay); 1910 t->timeout = GNUNET_TIME_relative_to_absolute(delay);
1916 t->priority = 1911 t->priority =
1917 check_priority ((prio == 1912 check_priority((prio ==
1918 GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority : 1913 GNUNET_SCHEDULER_PRIORITY_KEEP) ? current_priority :
1919 prio); 1914 prio);
1920 t->lifeness = current_lifeness; 1915 t->lifeness = current_lifeness;
1921 GNUNET_CONTAINER_DLL_insert (pending_head, 1916 GNUNET_CONTAINER_DLL_insert(pending_head,
1922 pending_tail, 1917 pending_tail,
1923 t); 1918 t);
1924 driver_add_multiple (t); 1919 driver_add_multiple(t);
1925 max_priority_added = GNUNET_MAX (max_priority_added, 1920 max_priority_added = GNUNET_MAX(max_priority_added,
1926 t->priority); 1921 t->priority);
1927 LOG (GNUNET_ERROR_TYPE_DEBUG, 1922 LOG(GNUNET_ERROR_TYPE_DEBUG,
1928 "Adding task %p\n", 1923 "Adding task %p\n",
1929 t); 1924 t);
1930 init_backtrace (t); 1925 init_backtrace(t);
1931 return t; 1926 return t;
1932} 1927}
1933 1928
@@ -1944,27 +1939,27 @@ GNUNET_SCHEDULER_add_select (enum GNUNET_SCHEDULER_Priority prio,
1944 * @param fdi information about the related FD 1939 * @param fdi information about the related FD
1945 */ 1940 */
1946void 1941void
1947GNUNET_SCHEDULER_task_ready (struct GNUNET_SCHEDULER_Task *task, 1942GNUNET_SCHEDULER_task_ready(struct GNUNET_SCHEDULER_Task *task,
1948 struct GNUNET_SCHEDULER_FdInfo *fdi) 1943 struct GNUNET_SCHEDULER_FdInfo *fdi)
1949{ 1944{
1950 enum GNUNET_SCHEDULER_Reason reason; 1945 enum GNUNET_SCHEDULER_Reason reason;
1951 1946
1952 reason = task->reason; 1947 reason = task->reason;
1953 if ( (0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) && 1948 if ((0 == (reason & GNUNET_SCHEDULER_REASON_READ_READY)) &&
1954 (0 != (GNUNET_SCHEDULER_ET_IN & fdi->et)) ) 1949 (0 != (GNUNET_SCHEDULER_ET_IN & fdi->et)))
1955 reason |= GNUNET_SCHEDULER_REASON_READ_READY; 1950 reason |= GNUNET_SCHEDULER_REASON_READ_READY;
1956 if ( (0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) && 1951 if ((0 == (reason & GNUNET_SCHEDULER_REASON_WRITE_READY)) &&
1957 (0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et)) ) 1952 (0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et)))
1958 reason |= GNUNET_SCHEDULER_REASON_WRITE_READY; 1953 reason |= GNUNET_SCHEDULER_REASON_WRITE_READY;
1959 reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE; 1954 reason |= GNUNET_SCHEDULER_REASON_PREREQ_DONE;
1960 task->reason = reason; 1955 task->reason = reason;
1961 if (GNUNET_NO == task->in_ready_list) 1956 if (GNUNET_NO == task->in_ready_list)
1962 { 1957 {
1963 GNUNET_CONTAINER_DLL_remove (pending_head, 1958 GNUNET_CONTAINER_DLL_remove(pending_head,
1964 pending_tail, 1959 pending_tail,
1965 task); 1960 task);
1966 queue_ready_task (task); 1961 queue_ready_task(task);
1967 } 1962 }
1968} 1963}
1969 1964
1970 1965
@@ -1989,173 +1984,173 @@ GNUNET_SCHEDULER_task_ready (struct GNUNET_SCHEDULER_Task *task,
1989 * if we are done running tasks (yield to block) 1984 * if we are done running tasks (yield to block)
1990 */ 1985 */
1991int 1986int
1992GNUNET_SCHEDULER_do_work (struct GNUNET_SCHEDULER_Handle *sh) 1987GNUNET_SCHEDULER_do_work(struct GNUNET_SCHEDULER_Handle *sh)
1993{ 1988{
1994 enum GNUNET_SCHEDULER_Priority p; 1989 enum GNUNET_SCHEDULER_Priority p;
1995 struct GNUNET_SCHEDULER_Task *pos; 1990 struct GNUNET_SCHEDULER_Task *pos;
1996 struct GNUNET_TIME_Absolute now; 1991 struct GNUNET_TIME_Absolute now;
1997 1992
1998 /* check for tasks that reached the timeout! */ 1993 /* check for tasks that reached the timeout! */
1999 now = GNUNET_TIME_absolute_get (); 1994 now = GNUNET_TIME_absolute_get();
2000 pos = pending_timeout_head; 1995 pos = pending_timeout_head;
2001 while (NULL != pos) 1996 while (NULL != pos)
2002 { 1997 {
2003 struct GNUNET_SCHEDULER_Task *next = pos->next; 1998 struct GNUNET_SCHEDULER_Task *next = pos->next;
2004 if (now.abs_value_us >= pos->timeout.abs_value_us) 1999 if (now.abs_value_us >= pos->timeout.abs_value_us)
2005 pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT; 2000 pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
2006 if (0 == pos->reason) 2001 if (0 == pos->reason)
2007 break; 2002 break;
2008 GNUNET_CONTAINER_DLL_remove (pending_timeout_head, 2003 GNUNET_CONTAINER_DLL_remove(pending_timeout_head,
2009 pending_timeout_tail, 2004 pending_timeout_tail,
2010 pos); 2005 pos);
2011 if (pending_timeout_last == pos) 2006 if (pending_timeout_last == pos)
2012 pending_timeout_last = NULL; 2007 pending_timeout_last = NULL;
2013 queue_ready_task (pos); 2008 queue_ready_task(pos);
2014 pos = next; 2009 pos = next;
2015 } 2010 }
2016 pos = pending_head; 2011 pos = pending_head;
2017 while (NULL != pos) 2012 while (NULL != pos)
2018 {
2019 struct GNUNET_SCHEDULER_Task *next = pos->next;
2020 if (now.abs_value_us >= pos->timeout.abs_value_us)
2021 { 2013 {
2022 pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT; 2014 struct GNUNET_SCHEDULER_Task *next = pos->next;
2023 GNUNET_CONTAINER_DLL_remove (pending_head, 2015 if (now.abs_value_us >= pos->timeout.abs_value_us)
2024 pending_tail, 2016 {
2025 pos); 2017 pos->reason |= GNUNET_SCHEDULER_REASON_TIMEOUT;
2026 queue_ready_task (pos); 2018 GNUNET_CONTAINER_DLL_remove(pending_head,
2019 pending_tail,
2020 pos);
2021 queue_ready_task(pos);
2022 }
2023 pos = next;
2027 } 2024 }
2028 pos = next;
2029 }
2030 2025
2031 if (0 == ready_count) 2026 if (0 == ready_count)
2032 {
2033 struct GNUNET_TIME_Absolute timeout = get_timeout ();
2034
2035 if (timeout.abs_value_us > now.abs_value_us)
2036 {
2037 /**
2038 * The event loop called this function before the current timeout was
2039 * reached (and no FD tasks are ready). This is acceptable if
2040 *
2041 * - the system time was changed while the driver was waiting for
2042 * the timeout
2043 * - an external event loop called GNUnet API functions outside of
2044 * the callbacks called in GNUNET_SCHEDULER_do_work and thus
2045 * wasn't notified about the new timeout
2046 *
2047 * It might also mean we are busy-waiting because of a programming
2048 * error in the external event loop.
2049 */
2050 LOG (GNUNET_ERROR_TYPE_DEBUG,
2051 "GNUNET_SCHEDULER_do_work did not find any ready "
2052 "tasks and timeout has not been reached yet.\n");
2053 }
2054 else
2055 {
2056 /**
2057 * the current timeout was reached but no ready tasks were found,
2058 * internal scheduler error!
2059 */
2060 GNUNET_assert (0);
2061 }
2062 }
2063 else
2064 {
2065 /* find out which task priority level we are going to
2066 process this time */
2067 max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
2068 GNUNET_assert (NULL == ready_head[GNUNET_SCHEDULER_PRIORITY_KEEP]);
2069 /* yes, p>0 is correct, 0 is "KEEP" which should
2070 * always be an empty queue (see assertion)! */
2071 for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
2072 { 2027 {
2073 pos = ready_head[p]; 2028 struct GNUNET_TIME_Absolute timeout = get_timeout();
2074 if (NULL != pos)
2075 break;
2076 }
2077 GNUNET_assert (NULL != pos); /* ready_count wrong? */
2078 2029
2079 /* process all tasks at this priority level, then yield */ 2030 if (timeout.abs_value_us > now.abs_value_us)
2080 while (NULL != (pos = ready_head[p]))
2081 {
2082 GNUNET_CONTAINER_DLL_remove (ready_head[p],
2083 ready_tail[p],
2084 pos);
2085 ready_count--;
2086 current_priority = pos->priority;
2087 current_lifeness = pos->lifeness;
2088 active_task = pos;
2089#if PROFILE_DELAYS
2090 if (GNUNET_TIME_absolute_get_duration (pos->start_time).rel_value_us >
2091 DELAY_THRESHOLD.rel_value_us)
2092 {
2093 LOG (GNUNET_ERROR_TYPE_DEBUG,
2094 "Task %p took %s to be scheduled\n",
2095 pos,
2096 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (pos->start_time),
2097 GNUNET_YES));
2098 }
2099#endif
2100 tc.reason = pos->reason;
2101 GNUNET_NETWORK_fdset_zero (sh->rs);
2102 GNUNET_NETWORK_fdset_zero (sh->ws);
2103 // FIXME: do we have to remove FdInfos from fds if they are not ready?
2104 tc.fds_len = pos->fds_len;
2105 tc.fds = pos->fds;
2106 for (unsigned int i = 0; i != pos->fds_len; ++i)
2107 {
2108 struct GNUNET_SCHEDULER_FdInfo *fdi = &pos->fds[i];
2109 if (0 != (GNUNET_SCHEDULER_ET_IN & fdi->et))
2110 { 2031 {
2111 GNUNET_NETWORK_fdset_set_native (sh->rs, 2032 /**
2112 fdi->sock); 2033 * The event loop called this function before the current timeout was
2034 * reached (and no FD tasks are ready). This is acceptable if
2035 *
2036 * - the system time was changed while the driver was waiting for
2037 * the timeout
2038 * - an external event loop called GNUnet API functions outside of
2039 * the callbacks called in GNUNET_SCHEDULER_do_work and thus
2040 * wasn't notified about the new timeout
2041 *
2042 * It might also mean we are busy-waiting because of a programming
2043 * error in the external event loop.
2044 */
2045 LOG(GNUNET_ERROR_TYPE_DEBUG,
2046 "GNUNET_SCHEDULER_do_work did not find any ready "
2047 "tasks and timeout has not been reached yet.\n");
2113 } 2048 }
2114 if (0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et)) 2049 else
2115 { 2050 {
2116 GNUNET_NETWORK_fdset_set_native (sh->ws, 2051 /**
2117 fdi->sock); 2052 * the current timeout was reached but no ready tasks were found,
2053 * internal scheduler error!
2054 */
2055 GNUNET_assert(0);
2118 } 2056 }
2119 } 2057 }
2120 tc.read_ready = sh->rs; 2058 else
2121 tc.write_ready = sh->ws; 2059 {
2122 LOG (GNUNET_ERROR_TYPE_DEBUG, 2060 /* find out which task priority level we are going to
2123 "Running task %p\n", 2061 process this time */
2124 pos); 2062 max_priority_added = GNUNET_SCHEDULER_PRIORITY_KEEP;
2125 GNUNET_assert (NULL != pos->callback); 2063 GNUNET_assert(NULL == ready_head[GNUNET_SCHEDULER_PRIORITY_KEEP]);
2126 { 2064 /* yes, p>0 is correct, 0 is "KEEP" which should
2127 struct GNUNET_AsyncScopeSave old_scope; 2065 * always be an empty queue (see assertion)! */
2128 if (pos->scope.have_scope) 2066 for (p = GNUNET_SCHEDULER_PRIORITY_COUNT - 1; p > 0; p--)
2129 GNUNET_async_scope_enter (&pos->scope.scope_id, &old_scope);
2130 else
2131 GNUNET_async_scope_get (&old_scope);
2132 pos->callback (pos->callback_cls);
2133 GNUNET_async_scope_restore (&old_scope);
2134 }
2135 if (NULL != pos->fds)
2136 {
2137 int del_result = scheduler_driver->del (scheduler_driver->cls, pos);
2138 if (GNUNET_OK != del_result)
2139 { 2067 {
2140 LOG (GNUNET_ERROR_TYPE_ERROR, 2068 pos = ready_head[p];
2141 "driver could not delete task %p\n", pos); 2069 if (NULL != pos)
2142 GNUNET_assert (0); 2070 break;
2071 }
2072 GNUNET_assert(NULL != pos); /* ready_count wrong? */
2073
2074 /* process all tasks at this priority level, then yield */
2075 while (NULL != (pos = ready_head[p]))
2076 {
2077 GNUNET_CONTAINER_DLL_remove(ready_head[p],
2078 ready_tail[p],
2079 pos);
2080 ready_count--;
2081 current_priority = pos->priority;
2082 current_lifeness = pos->lifeness;
2083 active_task = pos;
2084#if PROFILE_DELAYS
2085 if (GNUNET_TIME_absolute_get_duration(pos->start_time).rel_value_us >
2086 DELAY_THRESHOLD.rel_value_us)
2087 {
2088 LOG(GNUNET_ERROR_TYPE_DEBUG,
2089 "Task %p took %s to be scheduled\n",
2090 pos,
2091 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(pos->start_time),
2092 GNUNET_YES));
2093 }
2094#endif
2095 tc.reason = pos->reason;
2096 GNUNET_NETWORK_fdset_zero(sh->rs);
2097 GNUNET_NETWORK_fdset_zero(sh->ws);
2098 // FIXME: do we have to remove FdInfos from fds if they are not ready?
2099 tc.fds_len = pos->fds_len;
2100 tc.fds = pos->fds;
2101 for (unsigned int i = 0; i != pos->fds_len; ++i)
2102 {
2103 struct GNUNET_SCHEDULER_FdInfo *fdi = &pos->fds[i];
2104 if (0 != (GNUNET_SCHEDULER_ET_IN & fdi->et))
2105 {
2106 GNUNET_NETWORK_fdset_set_native(sh->rs,
2107 fdi->sock);
2108 }
2109 if (0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et))
2110 {
2111 GNUNET_NETWORK_fdset_set_native(sh->ws,
2112 fdi->sock);
2113 }
2114 }
2115 tc.read_ready = sh->rs;
2116 tc.write_ready = sh->ws;
2117 LOG(GNUNET_ERROR_TYPE_DEBUG,
2118 "Running task %p\n",
2119 pos);
2120 GNUNET_assert(NULL != pos->callback);
2121 {
2122 struct GNUNET_AsyncScopeSave old_scope;
2123 if (pos->scope.have_scope)
2124 GNUNET_async_scope_enter(&pos->scope.scope_id, &old_scope);
2125 else
2126 GNUNET_async_scope_get(&old_scope);
2127 pos->callback(pos->callback_cls);
2128 GNUNET_async_scope_restore(&old_scope);
2129 }
2130 if (NULL != pos->fds)
2131 {
2132 int del_result = scheduler_driver->del(scheduler_driver->cls, pos);
2133 if (GNUNET_OK != del_result)
2134 {
2135 LOG(GNUNET_ERROR_TYPE_ERROR,
2136 "driver could not delete task %p\n", pos);
2137 GNUNET_assert(0);
2138 }
2139 }
2140 active_task = NULL;
2141 dump_backtrace(pos);
2142 destroy_task(pos);
2143 } 2143 }
2144 }
2145 active_task = NULL;
2146 dump_backtrace (pos);
2147 destroy_task (pos);
2148 } 2144 }
2149 } 2145 shutdown_if_no_lifeness();
2150 shutdown_if_no_lifeness ();
2151 if (0 == ready_count) 2146 if (0 == ready_count)
2152 { 2147 {
2153 scheduler_driver->set_wakeup (scheduler_driver->cls, 2148 scheduler_driver->set_wakeup(scheduler_driver->cls,
2154 get_timeout ()); 2149 get_timeout());
2155 return GNUNET_NO; 2150 return GNUNET_NO;
2156 } 2151 }
2157 scheduler_driver->set_wakeup (scheduler_driver->cls, 2152 scheduler_driver->set_wakeup(scheduler_driver->cls,
2158 GNUNET_TIME_absolute_get ()); 2153 GNUNET_TIME_absolute_get());
2159 return GNUNET_YES; 2154 return GNUNET_YES;
2160} 2155}
2161 2156
@@ -2192,64 +2187,64 @@ GNUNET_SCHEDULER_do_work (struct GNUNET_SCHEDULER_Handle *sh)
2192 * #GNUNET_SCHEDULER_driver_done 2187 * #GNUNET_SCHEDULER_driver_done
2193 */ 2188 */
2194struct GNUNET_SCHEDULER_Handle * 2189struct GNUNET_SCHEDULER_Handle *
2195GNUNET_SCHEDULER_driver_init (const struct GNUNET_SCHEDULER_Driver *driver) 2190GNUNET_SCHEDULER_driver_init(const struct GNUNET_SCHEDULER_Driver *driver)
2196{ 2191{
2197 struct GNUNET_SCHEDULER_Handle *sh; 2192 struct GNUNET_SCHEDULER_Handle *sh;
2198 const struct GNUNET_DISK_FileHandle *pr; 2193 const struct GNUNET_DISK_FileHandle *pr;
2199 2194
2200 /* scheduler must not be running */ 2195 /* scheduler must not be running */
2201 GNUNET_assert (NULL == scheduler_driver); 2196 GNUNET_assert(NULL == scheduler_driver);
2202 GNUNET_assert (NULL == shutdown_pipe_handle); 2197 GNUNET_assert(NULL == shutdown_pipe_handle);
2203 /* general set-up */ 2198 /* general set-up */
2204 sh = GNUNET_new (struct GNUNET_SCHEDULER_Handle); 2199 sh = GNUNET_new(struct GNUNET_SCHEDULER_Handle);
2205 shutdown_pipe_handle = GNUNET_DISK_pipe (GNUNET_NO, 2200 shutdown_pipe_handle = GNUNET_DISK_pipe(GNUNET_NO,
2206 GNUNET_NO, 2201 GNUNET_NO,
2207 GNUNET_NO, 2202 GNUNET_NO,
2208 GNUNET_NO); 2203 GNUNET_NO);
2209 GNUNET_assert (NULL != shutdown_pipe_handle); 2204 GNUNET_assert(NULL != shutdown_pipe_handle);
2210 pr = GNUNET_DISK_pipe_handle (shutdown_pipe_handle, 2205 pr = GNUNET_DISK_pipe_handle(shutdown_pipe_handle,
2211 GNUNET_DISK_PIPE_END_READ); 2206 GNUNET_DISK_PIPE_END_READ);
2212 my_pid = getpid (); 2207 my_pid = getpid();
2213 scheduler_driver = driver; 2208 scheduler_driver = driver;
2214 2209
2215 /* install signal handlers */ 2210 /* install signal handlers */
2216 LOG (GNUNET_ERROR_TYPE_DEBUG, 2211 LOG(GNUNET_ERROR_TYPE_DEBUG,
2217 "Registering signal handlers\n"); 2212 "Registering signal handlers\n");
2218 sh->shc_int = GNUNET_SIGNAL_handler_install (SIGINT, 2213 sh->shc_int = GNUNET_SIGNAL_handler_install(SIGINT,
2214 &sighandler_shutdown);
2215 sh->shc_term = GNUNET_SIGNAL_handler_install(SIGTERM,
2219 &sighandler_shutdown); 2216 &sighandler_shutdown);
2220 sh->shc_term = GNUNET_SIGNAL_handler_install (SIGTERM,
2221 &sighandler_shutdown);
2222#if (SIGTERM != GNUNET_TERM_SIG) 2217#if (SIGTERM != GNUNET_TERM_SIG)
2223 sh->shc_gterm = GNUNET_SIGNAL_handler_install (GNUNET_TERM_SIG, 2218 sh->shc_gterm = GNUNET_SIGNAL_handler_install(GNUNET_TERM_SIG,
2224 &sighandler_shutdown); 2219 &sighandler_shutdown);
2225#endif 2220#endif
2226#ifndef MINGW 2221#ifndef MINGW
2227 sh->shc_pipe = GNUNET_SIGNAL_handler_install (SIGPIPE, 2222 sh->shc_pipe = GNUNET_SIGNAL_handler_install(SIGPIPE,
2228 &sighandler_pipe); 2223 &sighandler_pipe);
2229 sh->shc_quit = GNUNET_SIGNAL_handler_install (SIGQUIT, 2224 sh->shc_quit = GNUNET_SIGNAL_handler_install(SIGQUIT,
2230 &sighandler_shutdown);
2231 sh->shc_hup = GNUNET_SIGNAL_handler_install (SIGHUP,
2232 &sighandler_shutdown); 2225 &sighandler_shutdown);
2226 sh->shc_hup = GNUNET_SIGNAL_handler_install(SIGHUP,
2227 &sighandler_shutdown);
2233#endif 2228#endif
2234 2229
2235 /* Setup initial tasks */ 2230 /* Setup initial tasks */
2236 current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT; 2231 current_priority = GNUNET_SCHEDULER_PRIORITY_DEFAULT;
2237 current_lifeness = GNUNET_NO; 2232 current_lifeness = GNUNET_NO;
2238 install_parent_control_task = 2233 install_parent_control_task =
2239 GNUNET_SCHEDULER_add_now (&install_parent_control_handler, 2234 GNUNET_SCHEDULER_add_now(&install_parent_control_handler,
2240 NULL); 2235 NULL);
2241 shutdown_pipe_task = 2236 shutdown_pipe_task =
2242 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 2237 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
2243 pr, 2238 pr,
2244 &shutdown_pipe_cb, 2239 &shutdown_pipe_cb,
2245 NULL); 2240 NULL);
2246 current_lifeness = GNUNET_YES; 2241 current_lifeness = GNUNET_YES;
2247 scheduler_driver->set_wakeup (scheduler_driver->cls, 2242 scheduler_driver->set_wakeup(scheduler_driver->cls,
2248 get_timeout ()); 2243 get_timeout());
2249 /* begin main event loop */ 2244 /* begin main event loop */
2250 sh->rs = GNUNET_NETWORK_fdset_create (); 2245 sh->rs = GNUNET_NETWORK_fdset_create();
2251 sh->ws = GNUNET_NETWORK_fdset_create (); 2246 sh->ws = GNUNET_NETWORK_fdset_create();
2252 GNUNET_NETWORK_fdset_handle_set (sh->rs, pr); 2247 GNUNET_NETWORK_fdset_handle_set(sh->rs, pr);
2253 return sh; 2248 return sh;
2254} 2249}
2255 2250
@@ -2269,244 +2264,245 @@ GNUNET_SCHEDULER_driver_init (const struct GNUNET_SCHEDULER_Driver *driver)
2269 * @param sh the handle returned by #GNUNET_SCHEDULER_driver_init 2264 * @param sh the handle returned by #GNUNET_SCHEDULER_driver_init
2270 */ 2265 */
2271void 2266void
2272GNUNET_SCHEDULER_driver_done (struct GNUNET_SCHEDULER_Handle *sh) 2267GNUNET_SCHEDULER_driver_done(struct GNUNET_SCHEDULER_Handle *sh)
2273{ 2268{
2274 GNUNET_assert (NULL == pending_head); 2269 GNUNET_assert(NULL == pending_head);
2275 GNUNET_assert (NULL == pending_timeout_head); 2270 GNUNET_assert(NULL == pending_timeout_head);
2276 GNUNET_assert (NULL == shutdown_head); 2271 GNUNET_assert(NULL == shutdown_head);
2277 for (int i = 0; i != GNUNET_SCHEDULER_PRIORITY_COUNT; ++i) 2272 for (int i = 0; i != GNUNET_SCHEDULER_PRIORITY_COUNT; ++i)
2278 { 2273 {
2279 GNUNET_assert (NULL == ready_head[i]); 2274 GNUNET_assert(NULL == ready_head[i]);
2280 } 2275 }
2281 GNUNET_NETWORK_fdset_destroy (sh->rs); 2276 GNUNET_NETWORK_fdset_destroy(sh->rs);
2282 GNUNET_NETWORK_fdset_destroy (sh->ws); 2277 GNUNET_NETWORK_fdset_destroy(sh->ws);
2283 2278
2284 /* uninstall signal handlers */ 2279 /* uninstall signal handlers */
2285 GNUNET_SIGNAL_handler_uninstall (sh->shc_int); 2280 GNUNET_SIGNAL_handler_uninstall(sh->shc_int);
2286 GNUNET_SIGNAL_handler_uninstall (sh->shc_term); 2281 GNUNET_SIGNAL_handler_uninstall(sh->shc_term);
2287#if (SIGTERM != GNUNET_TERM_SIG) 2282#if (SIGTERM != GNUNET_TERM_SIG)
2288 GNUNET_SIGNAL_handler_uninstall (sh->shc_gterm); 2283 GNUNET_SIGNAL_handler_uninstall(sh->shc_gterm);
2289#endif 2284#endif
2290#ifndef MINGW 2285#ifndef MINGW
2291 GNUNET_SIGNAL_handler_uninstall (sh->shc_pipe); 2286 GNUNET_SIGNAL_handler_uninstall(sh->shc_pipe);
2292 GNUNET_SIGNAL_handler_uninstall (sh->shc_quit); 2287 GNUNET_SIGNAL_handler_uninstall(sh->shc_quit);
2293 GNUNET_SIGNAL_handler_uninstall (sh->shc_hup); 2288 GNUNET_SIGNAL_handler_uninstall(sh->shc_hup);
2294#endif 2289#endif
2295 GNUNET_DISK_pipe_close (shutdown_pipe_handle); 2290 GNUNET_DISK_pipe_close(shutdown_pipe_handle);
2296 shutdown_pipe_handle = NULL; 2291 shutdown_pipe_handle = NULL;
2297 scheduler_driver = NULL; 2292 scheduler_driver = NULL;
2298 GNUNET_free (sh); 2293 GNUNET_free(sh);
2299} 2294}
2300 2295
2301 2296
2302static int 2297static int
2303select_loop (struct GNUNET_SCHEDULER_Handle *sh, 2298select_loop(struct GNUNET_SCHEDULER_Handle *sh,
2304 struct DriverContext *context) 2299 struct DriverContext *context)
2305{ 2300{
2306 struct GNUNET_NETWORK_FDSet *rs; 2301 struct GNUNET_NETWORK_FDSet *rs;
2307 struct GNUNET_NETWORK_FDSet *ws; 2302 struct GNUNET_NETWORK_FDSet *ws;
2308 int select_result; 2303 int select_result;
2309 2304
2310 GNUNET_assert (NULL != context); 2305 GNUNET_assert(NULL != context);
2311 rs = GNUNET_NETWORK_fdset_create (); 2306 rs = GNUNET_NETWORK_fdset_create();
2312 ws = GNUNET_NETWORK_fdset_create (); 2307 ws = GNUNET_NETWORK_fdset_create();
2313 while ( (NULL != context->scheduled_head) || 2308 while ((NULL != context->scheduled_head) ||
2314 (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != context->timeout.abs_value_us) ) 2309 (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us != context->timeout.abs_value_us))
2315 {
2316 LOG (GNUNET_ERROR_TYPE_DEBUG,
2317 "select timeout = %s\n",
2318 GNUNET_STRINGS_absolute_time_to_string (context->timeout));
2319
2320 GNUNET_NETWORK_fdset_zero (rs);
2321 GNUNET_NETWORK_fdset_zero (ws);
2322
2323 for (struct Scheduled *pos = context->scheduled_head;
2324 NULL != pos;
2325 pos = pos->next)
2326 { 2310 {
2327 if (0 != (GNUNET_SCHEDULER_ET_IN & pos->et)) 2311 LOG(GNUNET_ERROR_TYPE_DEBUG,
2328 { 2312 "select timeout = %s\n",
2329 GNUNET_NETWORK_fdset_set_native (rs, pos->fdi->sock); 2313 GNUNET_STRINGS_absolute_time_to_string(context->timeout));
2330 } 2314
2331 if (0 != (GNUNET_SCHEDULER_ET_OUT & pos->et)) 2315 GNUNET_NETWORK_fdset_zero(rs);
2332 { 2316 GNUNET_NETWORK_fdset_zero(ws);
2333 GNUNET_NETWORK_fdset_set_native (ws, pos->fdi->sock);
2334 }
2335 }
2336 struct GNUNET_TIME_Relative time_remaining =
2337 GNUNET_TIME_absolute_get_remaining (context->timeout);
2338 if (NULL == scheduler_select)
2339 {
2340 select_result = GNUNET_NETWORK_socket_select (rs,
2341 ws,
2342 NULL,
2343 time_remaining);
2344 }
2345 else
2346 {
2347 select_result = scheduler_select (scheduler_select_cls,
2348 rs,
2349 ws,
2350 NULL,
2351 time_remaining);
2352 }
2353 if (select_result == GNUNET_SYSERR)
2354 {
2355 if (errno == EINTR)
2356 continue;
2357 2317
2358 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, 2318 for (struct Scheduled *pos = context->scheduled_head;
2359 "select"); 2319 NULL != pos;
2320 pos = pos->next)
2321 {
2322 if (0 != (GNUNET_SCHEDULER_ET_IN & pos->et))
2323 {
2324 GNUNET_NETWORK_fdset_set_native(rs, pos->fdi->sock);
2325 }
2326 if (0 != (GNUNET_SCHEDULER_ET_OUT & pos->et))
2327 {
2328 GNUNET_NETWORK_fdset_set_native(ws, pos->fdi->sock);
2329 }
2330 }
2331 struct GNUNET_TIME_Relative time_remaining =
2332 GNUNET_TIME_absolute_get_remaining(context->timeout);
2333 if (NULL == scheduler_select)
2334 {
2335 select_result = GNUNET_NETWORK_socket_select(rs,
2336 ws,
2337 NULL,
2338 time_remaining);
2339 }
2340 else
2341 {
2342 select_result = scheduler_select(scheduler_select_cls,
2343 rs,
2344 ws,
2345 NULL,
2346 time_remaining);
2347 }
2348 if (select_result == GNUNET_SYSERR)
2349 {
2350 if (errno == EINTR)
2351 continue;
2352
2353 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR,
2354 "select");
2360#ifndef MINGW 2355#ifndef MINGW
2361#if USE_LSOF 2356#if USE_LSOF
2362 char lsof[512]; 2357 char lsof[512];
2363 2358
2364 snprintf (lsof, 2359 snprintf(lsof,
2365 sizeof (lsof), 2360 sizeof(lsof),
2366 "lsof -p %d", 2361 "lsof -p %d",
2367 getpid ()); 2362 getpid());
2368 (void) close (1); 2363 (void)close(1);
2369 (void) dup2 (2, 1); 2364 (void)dup2(2, 1);
2370 if (0 != system (lsof)) 2365 if (0 != system(lsof))
2371 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, 2366 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING,
2372 "system"); 2367 "system");
2373#endif 2368#endif
2374#endif 2369#endif
2375#if DEBUG_FDS 2370#if DEBUG_FDS
2376 for (struct Scheduled *s = context->scheduled_head; 2371 for (struct Scheduled *s = context->scheduled_head;
2377 NULL != s; 2372 NULL != s;
2378 s = s->next) 2373 s = s->next)
2379 { 2374 {
2380 int flags = fcntl (s->fdi->sock, 2375 int flags = fcntl(s->fdi->sock,
2381 F_GETFD); 2376 F_GETFD);
2382 2377
2383 if ( (flags == -1) && 2378 if ((flags == -1) &&
2384 (EBADF == errno) ) 2379 (EBADF == errno))
2385 { 2380 {
2386 LOG (GNUNET_ERROR_TYPE_ERROR, 2381 LOG(GNUNET_ERROR_TYPE_ERROR,
2387 "Got invalid file descriptor %d!\n", 2382 "Got invalid file descriptor %d!\n",
2388 s->fdi->sock); 2383 s->fdi->sock);
2389#if EXECINFO 2384#if EXECINFO
2390 dump_backtrace (s->task); 2385 dump_backtrace(s->task);
2391#endif 2386#endif
2392 } 2387 }
2393 } 2388 }
2394#endif 2389#endif
2395 GNUNET_assert (0); 2390 GNUNET_assert(0);
2396 GNUNET_NETWORK_fdset_destroy (rs); 2391 GNUNET_NETWORK_fdset_destroy(rs);
2397 GNUNET_NETWORK_fdset_destroy (ws); 2392 GNUNET_NETWORK_fdset_destroy(ws);
2398 return GNUNET_SYSERR; 2393 return GNUNET_SYSERR;
2399 }
2400 if (select_result > 0)
2401 {
2402 for (struct Scheduled *pos = context->scheduled_head;
2403 NULL != pos;
2404 pos = pos->next)
2405 {
2406 int is_ready = GNUNET_NO;
2407
2408 if (0 != (GNUNET_SCHEDULER_ET_IN & pos->et) &&
2409 GNUNET_YES ==
2410 GNUNET_NETWORK_fdset_test_native (rs,
2411 pos->fdi->sock))
2412 {
2413 pos->fdi->et |= GNUNET_SCHEDULER_ET_IN;
2414 is_ready = GNUNET_YES;
2415 } 2394 }
2416 if (0 != (GNUNET_SCHEDULER_ET_OUT & pos->et) && 2395 if (select_result > 0)
2417 GNUNET_YES ==
2418 GNUNET_NETWORK_fdset_test_native (ws,
2419 pos->fdi->sock))
2420 { 2396 {
2421 pos->fdi->et |= GNUNET_SCHEDULER_ET_OUT; 2397 for (struct Scheduled *pos = context->scheduled_head;
2422 is_ready = GNUNET_YES; 2398 NULL != pos;
2399 pos = pos->next)
2400 {
2401 int is_ready = GNUNET_NO;
2402
2403 if (0 != (GNUNET_SCHEDULER_ET_IN & pos->et) &&
2404 GNUNET_YES ==
2405 GNUNET_NETWORK_fdset_test_native(rs,
2406 pos->fdi->sock))
2407 {
2408 pos->fdi->et |= GNUNET_SCHEDULER_ET_IN;
2409 is_ready = GNUNET_YES;
2410 }
2411 if (0 != (GNUNET_SCHEDULER_ET_OUT & pos->et) &&
2412 GNUNET_YES ==
2413 GNUNET_NETWORK_fdset_test_native(ws,
2414 pos->fdi->sock))
2415 {
2416 pos->fdi->et |= GNUNET_SCHEDULER_ET_OUT;
2417 is_ready = GNUNET_YES;
2418 }
2419 if (GNUNET_YES == is_ready)
2420 {
2421 GNUNET_SCHEDULER_task_ready(pos->task,
2422 pos->fdi);
2423 }
2424 }
2423 } 2425 }
2424 if (GNUNET_YES == is_ready) 2426 if (GNUNET_YES == GNUNET_SCHEDULER_do_work(sh))
2425 { 2427 {
2426 GNUNET_SCHEDULER_task_ready (pos->task, 2428 LOG(GNUNET_ERROR_TYPE_DEBUG,
2427 pos->fdi); 2429 "scheduler has more tasks ready!\n");
2428 } 2430 }
2429 }
2430 } 2431 }
2431 if (GNUNET_YES == GNUNET_SCHEDULER_do_work (sh)) 2432 GNUNET_NETWORK_fdset_destroy(rs);
2432 { 2433 GNUNET_NETWORK_fdset_destroy(ws);
2433 LOG (GNUNET_ERROR_TYPE_DEBUG,
2434 "scheduler has more tasks ready!\n");
2435 }
2436 }
2437 GNUNET_NETWORK_fdset_destroy (rs);
2438 GNUNET_NETWORK_fdset_destroy (ws);
2439 return GNUNET_OK; 2434 return GNUNET_OK;
2440} 2435}
2441 2436
2442 2437
2443static int 2438static int
2444select_add (void *cls, 2439select_add(void *cls,
2445 struct GNUNET_SCHEDULER_Task *task, 2440 struct GNUNET_SCHEDULER_Task *task,
2446 struct GNUNET_SCHEDULER_FdInfo *fdi) 2441 struct GNUNET_SCHEDULER_FdInfo *fdi)
2447{ 2442{
2448 struct DriverContext *context = cls; 2443 struct DriverContext *context = cls;
2449 GNUNET_assert (NULL != context); 2444
2450 GNUNET_assert (NULL != task); 2445 GNUNET_assert(NULL != context);
2451 GNUNET_assert (NULL != fdi); 2446 GNUNET_assert(NULL != task);
2452 GNUNET_assert (0 != (GNUNET_SCHEDULER_ET_IN & fdi->et) || 2447 GNUNET_assert(NULL != fdi);
2453 0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et)); 2448 GNUNET_assert(0 != (GNUNET_SCHEDULER_ET_IN & fdi->et) ||
2449 0 != (GNUNET_SCHEDULER_ET_OUT & fdi->et));
2454 2450
2455 if (!((NULL != fdi->fd) ^ (NULL != fdi->fh)) || (fdi->sock < 0)) 2451 if (!((NULL != fdi->fd) ^ (NULL != fdi->fh)) || (fdi->sock < 0))
2456 { 2452 {
2457 /* exactly one out of {fd, hf} must be != NULL and the OS handle must be valid */ 2453 /* exactly one out of {fd, hf} must be != NULL and the OS handle must be valid */
2458 return GNUNET_SYSERR; 2454 return GNUNET_SYSERR;
2459 } 2455 }
2460 2456
2461 struct Scheduled *scheduled = GNUNET_new (struct Scheduled); 2457 struct Scheduled *scheduled = GNUNET_new(struct Scheduled);
2462 scheduled->task = task; 2458 scheduled->task = task;
2463 scheduled->fdi = fdi; 2459 scheduled->fdi = fdi;
2464 scheduled->et = fdi->et; 2460 scheduled->et = fdi->et;
2465 2461
2466 GNUNET_CONTAINER_DLL_insert (context->scheduled_head, 2462 GNUNET_CONTAINER_DLL_insert(context->scheduled_head,
2467 context->scheduled_tail, 2463 context->scheduled_tail,
2468 scheduled); 2464 scheduled);
2469 return GNUNET_OK; 2465 return GNUNET_OK;
2470} 2466}
2471 2467
2472 2468
2473static int 2469static int
2474select_del (void *cls, 2470select_del(void *cls,
2475 struct GNUNET_SCHEDULER_Task *task) 2471 struct GNUNET_SCHEDULER_Task *task)
2476{ 2472{
2477 struct DriverContext *context; 2473 struct DriverContext *context;
2478 struct Scheduled *pos; 2474 struct Scheduled *pos;
2479 int ret; 2475 int ret;
2480 2476
2481 GNUNET_assert (NULL != cls); 2477 GNUNET_assert(NULL != cls);
2482 2478
2483 context = cls; 2479 context = cls;
2484 ret = GNUNET_SYSERR; 2480 ret = GNUNET_SYSERR;
2485 pos = context->scheduled_head; 2481 pos = context->scheduled_head;
2486 while (NULL != pos) 2482 while (NULL != pos)
2487 {
2488 struct Scheduled *next = pos->next;
2489 if (pos->task == task)
2490 { 2483 {
2491 GNUNET_CONTAINER_DLL_remove (context->scheduled_head, 2484 struct Scheduled *next = pos->next;
2492 context->scheduled_tail, 2485 if (pos->task == task)
2493 pos); 2486 {
2494 GNUNET_free (pos); 2487 GNUNET_CONTAINER_DLL_remove(context->scheduled_head,
2495 ret = GNUNET_OK; 2488 context->scheduled_tail,
2489 pos);
2490 GNUNET_free(pos);
2491 ret = GNUNET_OK;
2492 }
2493 pos = next;
2496 } 2494 }
2497 pos = next;
2498 }
2499 return ret; 2495 return ret;
2500} 2496}
2501 2497
2502 2498
2503static void 2499static void
2504select_set_wakeup (void *cls, 2500select_set_wakeup(void *cls,
2505 struct GNUNET_TIME_Absolute dt) 2501 struct GNUNET_TIME_Absolute dt)
2506{ 2502{
2507 struct DriverContext *context = cls; 2503 struct DriverContext *context = cls;
2508 2504
2509 GNUNET_assert (NULL != context); 2505 GNUNET_assert(NULL != context);
2510 context->timeout = dt; 2506 context->timeout = dt;
2511} 2507}
2512 2508
@@ -2517,10 +2513,11 @@ select_set_wakeup (void *cls,
2517 * @return NULL on error 2513 * @return NULL on error
2518 */ 2514 */
2519struct GNUNET_SCHEDULER_Driver * 2515struct GNUNET_SCHEDULER_Driver *
2520GNUNET_SCHEDULER_driver_select () 2516GNUNET_SCHEDULER_driver_select()
2521{ 2517{
2522 struct GNUNET_SCHEDULER_Driver *select_driver; 2518 struct GNUNET_SCHEDULER_Driver *select_driver;
2523 select_driver = GNUNET_new (struct GNUNET_SCHEDULER_Driver); 2519
2520 select_driver = GNUNET_new(struct GNUNET_SCHEDULER_Driver);
2524 2521
2525 select_driver->add = &select_add; 2522 select_driver->add = &select_add;
2526 select_driver->del = &select_del; 2523 select_driver->del = &select_del;
@@ -2543,14 +2540,14 @@ GNUNET_SCHEDULER_driver_select ()
2543 * @param aid the asynchronous scope id to enter 2540 * @param aid the asynchronous scope id to enter
2544 */ 2541 */
2545void 2542void
2546GNUNET_SCHEDULER_begin_async_scope (struct GNUNET_AsyncScopeId *aid) 2543GNUNET_SCHEDULER_begin_async_scope(struct GNUNET_AsyncScopeId *aid)
2547{ 2544{
2548 struct GNUNET_AsyncScopeSave dummy_old_scope; 2545 struct GNUNET_AsyncScopeSave dummy_old_scope;
2549 2546
2550 GNUNET_assert (NULL != active_task); 2547 GNUNET_assert(NULL != active_task);
2551 /* Since we're in a task, the context will be automatically 2548 /* Since we're in a task, the context will be automatically
2552 restored by the scheduler. */ 2549 restored by the scheduler. */
2553 GNUNET_async_scope_enter (aid, &dummy_old_scope); 2550 GNUNET_async_scope_enter(aid, &dummy_old_scope);
2554} 2551}
2555 2552
2556 2553
diff --git a/src/util/service.c b/src/util/service.c
index 5986b0158..089d3ef35 100644
--- a/src/util/service.c
+++ b/src/util/service.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/service.c 22 * @file util/service.c
@@ -37,21 +37,19 @@
37#endif 37#endif
38 38
39 39
40#define LOG(kind, ...) GNUNET_log_from (kind, "util-service", __VA_ARGS__) 40#define LOG(kind, ...) GNUNET_log_from(kind, "util-service", __VA_ARGS__)
41 41
42#define LOG_STRERROR(kind, syscall) \ 42#define LOG_STRERROR(kind, syscall) \
43 GNUNET_log_from_strerror (kind, "util-service", syscall) 43 GNUNET_log_from_strerror(kind, "util-service", syscall)
44 44
45#define LOG_STRERROR_FILE(kind, syscall, filename) \ 45#define LOG_STRERROR_FILE(kind, syscall, filename) \
46 GNUNET_log_from_strerror_file (kind, "util-service", syscall, filename) 46 GNUNET_log_from_strerror_file(kind, "util-service", syscall, filename)
47 47
48 48
49/** 49/**
50 * Information the service tracks per listen operation. 50 * Information the service tracks per listen operation.
51 */ 51 */
52struct ServiceListenContext 52struct ServiceListenContext {
53{
54
55 /** 53 /**
56 * Kept in a DLL. 54 * Kept in a DLL.
57 */ 55 */
@@ -82,8 +80,7 @@ struct ServiceListenContext
82/** 80/**
83 * Reasons why we might be suspended. 81 * Reasons why we might be suspended.
84 */ 82 */
85enum SuspendReason 83enum SuspendReason {
86{
87 /** 84 /**
88 * We are running normally. 85 * We are running normally.
89 */ 86 */
@@ -114,8 +111,7 @@ enum SuspendReason
114/** 111/**
115 * Handle to a service. 112 * Handle to a service.
116 */ 113 */
117struct GNUNET_SERVICE_Handle 114struct GNUNET_SERVICE_Handle {
118{
119 /** 115 /**
120 * Our configuration. 116 * Our configuration.
121 */ 117 */
@@ -247,9 +243,7 @@ struct GNUNET_SERVICE_Handle
247/** 243/**
248 * Handle to a client that is connected to a service. 244 * Handle to a client that is connected to a service.
249 */ 245 */
250struct GNUNET_SERVICE_Client 246struct GNUNET_SERVICE_Client {
251{
252
253 /** 247 /**
254 * Kept in a DLL. 248 * Kept in a DLL.
255 */ 249 */
@@ -359,15 +353,15 @@ struct GNUNET_SERVICE_Client
359 * @return #GNUNET_YES if we have non-monitoring clients left 353 * @return #GNUNET_YES if we have non-monitoring clients left
360 */ 354 */
361static int 355static int
362have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh) 356have_non_monitor_clients(struct GNUNET_SERVICE_Handle *sh)
363{ 357{
364 for (struct GNUNET_SERVICE_Client *client = sh->clients_head; NULL != client; 358 for (struct GNUNET_SERVICE_Client *client = sh->clients_head; NULL != client;
365 client = client->next) 359 client = client->next)
366 { 360 {
367 if (client->is_monitor) 361 if (client->is_monitor)
368 continue; 362 continue;
369 return GNUNET_YES; 363 return GNUNET_YES;
370 } 364 }
371 return GNUNET_NO; 365 return GNUNET_NO;
372} 366}
373 367
@@ -380,20 +374,20 @@ have_non_monitor_clients (struct GNUNET_SERVICE_Handle *sh)
380 * @param sr reason for suspending accepting connections 374 * @param sr reason for suspending accepting connections
381 */ 375 */
382static void 376static void
383do_suspend (struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr) 377do_suspend(struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr)
384{ 378{
385 struct ServiceListenContext *slc; 379 struct ServiceListenContext *slc;
386 380
387 GNUNET_assert (0 == (sh->suspend_state & sr)); 381 GNUNET_assert(0 == (sh->suspend_state & sr));
388 sh->suspend_state |= sr; 382 sh->suspend_state |= sr;
389 for (slc = sh->slc_head; NULL != slc; slc = slc->next) 383 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
390 {
391 if (NULL != slc->listen_task)
392 { 384 {
393 GNUNET_SCHEDULER_cancel (slc->listen_task); 385 if (NULL != slc->listen_task)
394 slc->listen_task = NULL; 386 {
387 GNUNET_SCHEDULER_cancel(slc->listen_task);
388 slc->listen_task = NULL;
389 }
395 } 390 }
396 }
397} 391}
398 392
399 393
@@ -406,27 +400,29 @@ do_suspend (struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr)
406 * @param cls our `struct GNUNET_SERVICE_Handle` 400 * @param cls our `struct GNUNET_SERVICE_Handle`
407 */ 401 */
408static void 402static void
409service_shutdown (void *cls) 403service_shutdown(void *cls)
410{ 404{
411 struct GNUNET_SERVICE_Handle *sh = cls; 405 struct GNUNET_SERVICE_Handle *sh = cls;
412 406
413 switch (sh->options) 407 switch (sh->options)
414 { 408 {
415 case GNUNET_SERVICE_OPTION_NONE: 409 case GNUNET_SERVICE_OPTION_NONE:
416 GNUNET_SERVICE_shutdown (sh); 410 GNUNET_SERVICE_shutdown(sh);
417 break; 411 break;
418 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN: 412
419 /* This task should never be run if we are using 413 case GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN:
420 the manual shutdown. */ 414 /* This task should never be run if we are using
421 GNUNET_assert (0); 415 the manual shutdown. */
422 break; 416 GNUNET_assert(0);
423 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN: 417 break;
424 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN)) 418
425 do_suspend (sh, SUSPEND_STATE_SHUTDOWN); 419 case GNUNET_SERVICE_OPTION_SOFT_SHUTDOWN:
426 if (GNUNET_NO == have_non_monitor_clients (sh)) 420 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
427 GNUNET_SERVICE_shutdown (sh); 421 do_suspend(sh, SUSPEND_STATE_SHUTDOWN);
428 break; 422 if (GNUNET_NO == have_non_monitor_clients(sh))
429 } 423 GNUNET_SERVICE_shutdown(sh);
424 break;
425 }
430} 426}
431 427
432 428
@@ -438,8 +434,8 @@ service_shutdown (void *cls)
438 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is 434 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
439 */ 435 */
440static int 436static int
441check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list, 437check_ipv4_listed(const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
442 const struct in_addr *add) 438 const struct in_addr *add)
443{ 439{
444 unsigned int i; 440 unsigned int i;
445 441
@@ -447,12 +443,12 @@ check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
447 return GNUNET_NO; 443 return GNUNET_NO;
448 i = 0; 444 i = 0;
449 while ((0 != list[i].network.s_addr) || (0 != list[i].netmask.s_addr)) 445 while ((0 != list[i].network.s_addr) || (0 != list[i].netmask.s_addr))
450 { 446 {
451 if ((add->s_addr & list[i].netmask.s_addr) == 447 if ((add->s_addr & list[i].netmask.s_addr) ==
452 (list[i].network.s_addr & list[i].netmask.s_addr)) 448 (list[i].network.s_addr & list[i].netmask.s_addr))
453 return GNUNET_YES; 449 return GNUNET_YES;
454 i++; 450 i++;
455 } 451 }
456 return GNUNET_NO; 452 return GNUNET_NO;
457} 453}
458 454
@@ -465,8 +461,8 @@ check_ipv4_listed (const struct GNUNET_STRINGS_IPv4NetworkPolicy *list,
465 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is 461 * @return #GNUNET_NO if the IP is not in the list, #GNUNET_YES if it it is
466 */ 462 */
467static int 463static int
468check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list, 464check_ipv6_listed(const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
469 const struct in6_addr *ip) 465 const struct in6_addr *ip)
470{ 466{
471 unsigned int i; 467 unsigned int i;
472 unsigned int j; 468 unsigned int j;
@@ -475,17 +471,17 @@ check_ipv6_listed (const struct GNUNET_STRINGS_IPv6NetworkPolicy *list,
475 return GNUNET_NO; 471 return GNUNET_NO;
476 i = 0; 472 i = 0;
477NEXT: 473NEXT:
478 while (0 != GNUNET_is_zero (&list[i].network)) 474 while (0 != GNUNET_is_zero(&list[i].network))
479 { 475 {
480 for (j = 0; j < sizeof (struct in6_addr) / sizeof (int); j++) 476 for (j = 0; j < sizeof(struct in6_addr) / sizeof(int); j++)
481 if (((((int *) ip)[j] & ((int *) &list[i].netmask)[j])) != 477 if (((((int *)ip)[j] & ((int *)&list[i].netmask)[j])) !=
482 (((int *) &list[i].network)[j] & ((int *) &list[i].netmask)[j])) 478 (((int *)&list[i].network)[j] & ((int *)&list[i].netmask)[j]))
483 { 479 {
484 i++; 480 i++;
485 goto NEXT; 481 goto NEXT;
486 } 482 }
487 return GNUNET_YES; 483 return GNUNET_YES;
488 } 484 }
489 return GNUNET_NO; 485 return GNUNET_NO;
490} 486}
491 487
@@ -497,63 +493,63 @@ NEXT:
497 * @param cls the `struct GNUNET_SERVICE_Client *` to send to 493 * @param cls the `struct GNUNET_SERVICE_Client *` to send to
498 */ 494 */
499static void 495static void
500do_send (void *cls) 496do_send(void *cls)
501{ 497{
502 struct GNUNET_SERVICE_Client *client = cls; 498 struct GNUNET_SERVICE_Client *client = cls;
503 ssize_t ret; 499 ssize_t ret;
504 size_t left; 500 size_t left;
505 const char *buf; 501 const char *buf;
506 502
507 LOG (GNUNET_ERROR_TYPE_DEBUG, 503 LOG(GNUNET_ERROR_TYPE_DEBUG,
508 "service: sending message with type %u\n", 504 "service: sending message with type %u\n",
509 ntohs (client->msg->type)); 505 ntohs(client->msg->type));
510 506
511 507
512 client->send_task = NULL; 508 client->send_task = NULL;
513 buf = (const char *) client->msg; 509 buf = (const char *)client->msg;
514 left = ntohs (client->msg->size) - client->msg_pos; 510 left = ntohs(client->msg->size) - client->msg_pos;
515 ret = GNUNET_NETWORK_socket_send (client->sock, &buf[client->msg_pos], left); 511 ret = GNUNET_NETWORK_socket_send(client->sock, &buf[client->msg_pos], left);
516 GNUNET_assert (ret <= (ssize_t) left); 512 GNUNET_assert(ret <= (ssize_t)left);
517 if (0 == ret) 513 if (0 == ret)
518 {
519 LOG (GNUNET_ERROR_TYPE_DEBUG, "no data send");
520 GNUNET_MQ_inject_error (client->mq, GNUNET_MQ_ERROR_WRITE);
521 return;
522 }
523 if (-1 == ret)
524 {
525 if ((EAGAIN == errno) || (EINTR == errno))
526 { 514 {
527 /* ignore */ 515 LOG(GNUNET_ERROR_TYPE_DEBUG, "no data send");
528 ret = 0; 516 GNUNET_MQ_inject_error(client->mq, GNUNET_MQ_ERROR_WRITE);
517 return;
529 } 518 }
530 else 519 if (-1 == ret)
531 { 520 {
532 if (EPIPE != errno) 521 if ((EAGAIN == errno) || (EINTR == errno))
533 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "send"); 522 {
534 LOG (GNUNET_ERROR_TYPE_DEBUG, 523 /* ignore */
535 "socket send returned with error code %i", 524 ret = 0;
536 errno); 525 }
537 GNUNET_MQ_inject_error (client->mq, GNUNET_MQ_ERROR_WRITE); 526 else
538 return; 527 {
528 if (EPIPE != errno)
529 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "send");
530 LOG(GNUNET_ERROR_TYPE_DEBUG,
531 "socket send returned with error code %i",
532 errno);
533 GNUNET_MQ_inject_error(client->mq, GNUNET_MQ_ERROR_WRITE);
534 return;
535 }
539 } 536 }
540 }
541 if (0 == client->msg_pos) 537 if (0 == client->msg_pos)
542 { 538 {
543 GNUNET_MQ_impl_send_in_flight (client->mq); 539 GNUNET_MQ_impl_send_in_flight(client->mq);
544 } 540 }
545 client->msg_pos += ret; 541 client->msg_pos += ret;
546 if (left > (size_t) ret) 542 if (left > (size_t)ret)
547 { 543 {
548 GNUNET_assert (NULL == client->drop_task); 544 GNUNET_assert(NULL == client->drop_task);
549 client->send_task = 545 client->send_task =
550 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, 546 GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
551 client->sock, 547 client->sock,
552 &do_send, 548 &do_send,
553 client); 549 client);
554 return; 550 return;
555 } 551 }
556 GNUNET_MQ_impl_send_continue (client->mq); 552 GNUNET_MQ_impl_send_continue(client->mq);
557} 553}
558 554
559 555
@@ -566,27 +562,27 @@ do_send (void *cls)
566 * @param impl_state our `struct GNUNET_SERVICE_Client *` 562 * @param impl_state our `struct GNUNET_SERVICE_Client *`
567 */ 563 */
568static void 564static void
569service_mq_send (struct GNUNET_MQ_Handle *mq, 565service_mq_send(struct GNUNET_MQ_Handle *mq,
570 const struct GNUNET_MessageHeader *msg, 566 const struct GNUNET_MessageHeader *msg,
571 void *impl_state) 567 void *impl_state)
572{ 568{
573 struct GNUNET_SERVICE_Client *client = impl_state; 569 struct GNUNET_SERVICE_Client *client = impl_state;
574 570
575 (void) mq; 571 (void)mq;
576 if (NULL != client->drop_task) 572 if (NULL != client->drop_task)
577 return; /* we're going down right now, do not try to send */ 573 return; /* we're going down right now, do not try to send */
578 GNUNET_assert (NULL == client->send_task); 574 GNUNET_assert(NULL == client->send_task);
579 LOG (GNUNET_ERROR_TYPE_DEBUG, 575 LOG(GNUNET_ERROR_TYPE_DEBUG,
580 "Sending message of type %u and size %u to client\n", 576 "Sending message of type %u and size %u to client\n",
581 ntohs (msg->type), 577 ntohs(msg->type),
582 ntohs (msg->size)); 578 ntohs(msg->size));
583 client->msg = msg; 579 client->msg = msg;
584 client->msg_pos = 0; 580 client->msg_pos = 0;
585 client->send_task = 581 client->send_task =
586 GNUNET_SCHEDULER_add_write_net (GNUNET_TIME_UNIT_FOREVER_REL, 582 GNUNET_SCHEDULER_add_write_net(GNUNET_TIME_UNIT_FOREVER_REL,
587 client->sock, 583 client->sock,
588 &do_send, 584 &do_send,
589 client); 585 client);
590} 586}
591 587
592 588
@@ -597,14 +593,14 @@ service_mq_send (struct GNUNET_MQ_Handle *mq,
597 * @param impl_state state specific to the implementation 593 * @param impl_state state specific to the implementation
598 */ 594 */
599static void 595static void
600service_mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state) 596service_mq_cancel(struct GNUNET_MQ_Handle *mq, void *impl_state)
601{ 597{
602 struct GNUNET_SERVICE_Client *client = impl_state; 598 struct GNUNET_SERVICE_Client *client = impl_state;
603 599
604 (void) mq; 600 (void)mq;
605 GNUNET_assert (0 == client->msg_pos); 601 GNUNET_assert(0 == client->msg_pos);
606 client->msg = NULL; 602 client->msg = NULL;
607 GNUNET_SCHEDULER_cancel (client->send_task); 603 GNUNET_SCHEDULER_cancel(client->send_task);
608 client->send_task = NULL; 604 client->send_task = NULL;
609} 605}
610 606
@@ -619,20 +615,20 @@ service_mq_cancel (struct GNUNET_MQ_Handle *mq, void *impl_state)
619 * @param error error code 615 * @param error error code
620 */ 616 */
621static void 617static void
622service_mq_error_handler (void *cls, enum GNUNET_MQ_Error error) 618service_mq_error_handler(void *cls, enum GNUNET_MQ_Error error)
623{ 619{
624 struct GNUNET_SERVICE_Client *client = cls; 620 struct GNUNET_SERVICE_Client *client = cls;
625 struct GNUNET_SERVICE_Handle *sh = client->sh; 621 struct GNUNET_SERVICE_Handle *sh = client->sh;
626 622
627 if ((GNUNET_MQ_ERROR_NO_MATCH == error) && (GNUNET_NO == sh->require_found)) 623 if ((GNUNET_MQ_ERROR_NO_MATCH == error) && (GNUNET_NO == sh->require_found))
628 { 624 {
629 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 625 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
630 "No handler for message of type %u found\n", 626 "No handler for message of type %u found\n",
631 (unsigned int) client->warn_type); 627 (unsigned int)client->warn_type);
632 GNUNET_SERVICE_client_continue (client); 628 GNUNET_SERVICE_client_continue(client);
633 return; /* ignore error */ 629 return; /* ignore error */
634 } 630 }
635 GNUNET_SERVICE_client_drop (client); 631 GNUNET_SERVICE_client_drop(client);
636} 632}
637 633
638 634
@@ -642,24 +638,24 @@ service_mq_error_handler (void *cls, enum GNUNET_MQ_Error error)
642 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from 638 * @param cls our `struct GNUNET_SERVICE_Client *` to process more requests from
643 */ 639 */
644static void 640static void
645warn_no_client_continue (void *cls) 641warn_no_client_continue(void *cls)
646{ 642{
647 struct GNUNET_SERVICE_Client *client = cls; 643 struct GNUNET_SERVICE_Client *client = cls;
648 644
649 GNUNET_break ( 645 GNUNET_break(
650 0 != 646 0 !=
651 client->warn_type); /* type should never be 0 here, as we don't use 0 */ 647 client->warn_type); /* type should never be 0 here, as we don't use 0 */
652 client->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, 648 client->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES,
653 &warn_no_client_continue, 649 &warn_no_client_continue,
654 client); 650 client);
655 LOG ( 651 LOG(
656 GNUNET_ERROR_TYPE_WARNING, 652 GNUNET_ERROR_TYPE_WARNING,
657 _ ( 653 _(
658 "Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"), 654 "Processing code for message of type %u did not call `GNUNET_SERVICE_client_continue' after %s\n"),
659 (unsigned int) client->warn_type, 655 (unsigned int)client->warn_type,
660 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration ( 656 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(
661 client->warn_start), 657 client->warn_start),
662 GNUNET_YES)); 658 GNUNET_YES));
663} 659}
664 660
665 661
@@ -675,23 +671,23 @@ warn_no_client_continue (void *cls)
675 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped 671 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the client was dropped
676 */ 672 */
677static int 673static int
678service_client_mst_cb (void *cls, const struct GNUNET_MessageHeader *message) 674service_client_mst_cb(void *cls, const struct GNUNET_MessageHeader *message)
679{ 675{
680 struct GNUNET_SERVICE_Client *client = cls; 676 struct GNUNET_SERVICE_Client *client = cls;
681 677
682 LOG (GNUNET_ERROR_TYPE_DEBUG, 678 LOG(GNUNET_ERROR_TYPE_DEBUG,
683 "Received message of type %u and size %u from client\n", 679 "Received message of type %u and size %u from client\n",
684 ntohs (message->type), 680 ntohs(message->type),
685 ntohs (message->size)); 681 ntohs(message->size));
686 GNUNET_assert (GNUNET_NO == client->needs_continue); 682 GNUNET_assert(GNUNET_NO == client->needs_continue);
687 client->needs_continue = GNUNET_YES; 683 client->needs_continue = GNUNET_YES;
688 client->warn_type = ntohs (message->type); 684 client->warn_type = ntohs(message->type);
689 client->warn_start = GNUNET_TIME_absolute_get (); 685 client->warn_start = GNUNET_TIME_absolute_get();
690 GNUNET_assert (NULL == client->warn_task); 686 GNUNET_assert(NULL == client->warn_task);
691 client->warn_task = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, 687 client->warn_task = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES,
692 &warn_no_client_continue, 688 &warn_no_client_continue,
693 client); 689 client);
694 GNUNET_MQ_inject_message (client->mq, message); 690 GNUNET_MQ_inject_message(client->mq, message);
695 if (NULL != client->drop_task) 691 if (NULL != client->drop_task)
696 return GNUNET_SYSERR; 692 return GNUNET_SYSERR;
697 return GNUNET_OK; 693 return GNUNET_OK;
@@ -705,37 +701,37 @@ service_client_mst_cb (void *cls, const struct GNUNET_MessageHeader *message)
705 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data. 701 * @param cls the `struct GNUNET_SERVICE_Client` that sent us data.
706 */ 702 */
707static void 703static void
708service_client_recv (void *cls) 704service_client_recv(void *cls)
709{ 705{
710 struct GNUNET_SERVICE_Client *client = cls; 706 struct GNUNET_SERVICE_Client *client = cls;
711 int ret; 707 int ret;
712 708
713 client->recv_task = NULL; 709 client->recv_task = NULL;
714 ret = GNUNET_MST_read (client->mst, client->sock, GNUNET_NO, GNUNET_YES); 710 ret = GNUNET_MST_read(client->mst, client->sock, GNUNET_NO, GNUNET_YES);
715 if (GNUNET_SYSERR == ret) 711 if (GNUNET_SYSERR == ret)
716 {
717 /* client closed connection (or IO error) */
718 if (NULL == client->drop_task)
719 { 712 {
720 GNUNET_assert (GNUNET_NO == client->needs_continue); 713 /* client closed connection (or IO error) */
721 GNUNET_SERVICE_client_drop (client); 714 if (NULL == client->drop_task)
715 {
716 GNUNET_assert(GNUNET_NO == client->needs_continue);
717 GNUNET_SERVICE_client_drop(client);
718 }
719 return;
722 } 720 }
723 return;
724 }
725 if (GNUNET_NO == ret) 721 if (GNUNET_NO == ret)
726 return; /* more messages in buffer, wait for application 722 return; /* more messages in buffer, wait for application
727 to be done processing */ 723 to be done processing */
728 GNUNET_assert (GNUNET_OK == ret); 724 GNUNET_assert(GNUNET_OK == ret);
729 if (GNUNET_YES == client->needs_continue) 725 if (GNUNET_YES == client->needs_continue)
730 return; 726 return;
731 if (NULL != client->recv_task) 727 if (NULL != client->recv_task)
732 return; 728 return;
733 /* MST needs more data, re-schedule read job */ 729 /* MST needs more data, re-schedule read job */
734 client->recv_task = 730 client->recv_task =
735 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 731 GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
736 client->sock, 732 client->sock,
737 &service_client_recv, 733 &service_client_recv,
738 client); 734 client);
739} 735}
740 736
741 737
@@ -747,31 +743,31 @@ service_client_recv (void *cls)
747 * @param sock socket associated with the client 743 * @param sock socket associated with the client
748 */ 744 */
749static void 745static void
750start_client (struct GNUNET_SERVICE_Handle *sh, 746start_client(struct GNUNET_SERVICE_Handle *sh,
751 struct GNUNET_NETWORK_Handle *csock) 747 struct GNUNET_NETWORK_Handle *csock)
752{ 748{
753 struct GNUNET_SERVICE_Client *client; 749 struct GNUNET_SERVICE_Client *client;
754 750
755 client = GNUNET_new (struct GNUNET_SERVICE_Client); 751 client = GNUNET_new(struct GNUNET_SERVICE_Client);
756 GNUNET_CONTAINER_DLL_insert (sh->clients_head, sh->clients_tail, client); 752 GNUNET_CONTAINER_DLL_insert(sh->clients_head, sh->clients_tail, client);
757 client->sh = sh; 753 client->sh = sh;
758 client->sock = csock; 754 client->sock = csock;
759 client->mq = GNUNET_MQ_queue_for_callbacks (&service_mq_send, 755 client->mq = GNUNET_MQ_queue_for_callbacks(&service_mq_send,
760 NULL, 756 NULL,
761 &service_mq_cancel, 757 &service_mq_cancel,
762 client, 758 client,
763 sh->handlers, 759 sh->handlers,
764 &service_mq_error_handler, 760 &service_mq_error_handler,
765 client); 761 client);
766 client->mst = GNUNET_MST_create (&service_client_mst_cb, client); 762 client->mst = GNUNET_MST_create(&service_client_mst_cb, client);
767 if (NULL != sh->connect_cb) 763 if (NULL != sh->connect_cb)
768 client->user_context = sh->connect_cb (sh->cb_cls, client, client->mq); 764 client->user_context = sh->connect_cb(sh->cb_cls, client, client->mq);
769 GNUNET_MQ_set_handlers_closure (client->mq, client->user_context); 765 GNUNET_MQ_set_handlers_closure(client->mq, client->user_context);
770 client->recv_task = 766 client->recv_task =
771 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 767 GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
772 client->sock, 768 client->sock,
773 &service_client_recv, 769 &service_client_recv,
774 client); 770 client);
775} 771}
776 772
777 773
@@ -782,82 +778,84 @@ start_client (struct GNUNET_SERVICE_Handle *sh,
782 * @param cls the `struct ServiceListenContext` of the ready listen socket 778 * @param cls the `struct ServiceListenContext` of the ready listen socket
783 */ 779 */
784static void 780static void
785accept_client (void *cls) 781accept_client(void *cls)
786{ 782{
787 struct ServiceListenContext *slc = cls; 783 struct ServiceListenContext *slc = cls;
788 struct GNUNET_SERVICE_Handle *sh = slc->sh; 784 struct GNUNET_SERVICE_Handle *sh = slc->sh;
789 785
790 slc->listen_task = NULL; 786 slc->listen_task = NULL;
791 while (1) 787 while (1)
792 {
793 struct GNUNET_NETWORK_Handle *sock;
794 const struct sockaddr_in *v4;
795 const struct sockaddr_in6 *v6;
796 struct sockaddr_storage sa;
797 socklen_t addrlen;
798 int ok;
799
800 addrlen = sizeof (sa);
801 sock = GNUNET_NETWORK_socket_accept (slc->listen_socket,
802 (struct sockaddr *) &sa,
803 &addrlen);
804 if (NULL == sock)
805 {
806 if (EMFILE == errno)
807 do_suspend (sh, SUSPEND_STATE_EMFILE);
808 else if (EAGAIN != errno)
809 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "accept");
810 break;
811 }
812 switch (sa.ss_family)
813 { 788 {
814 case AF_INET: 789 struct GNUNET_NETWORK_Handle *sock;
815 GNUNET_assert (addrlen == sizeof (struct sockaddr_in)); 790 const struct sockaddr_in *v4;
816 v4 = (const struct sockaddr_in *) &sa; 791 const struct sockaddr_in6 *v6;
817 ok = (((NULL == sh->v4_allowed) || 792 struct sockaddr_storage sa;
818 (check_ipv4_listed (sh->v4_allowed, &v4->sin_addr))) && 793 socklen_t addrlen;
819 ((NULL == sh->v4_denied) || 794 int ok;
820 (! check_ipv4_listed (sh->v4_denied, &v4->sin_addr)))); 795
821 break; 796 addrlen = sizeof(sa);
822 case AF_INET6: 797 sock = GNUNET_NETWORK_socket_accept(slc->listen_socket,
823 GNUNET_assert (addrlen == sizeof (struct sockaddr_in6)); 798 (struct sockaddr *)&sa,
824 v6 = (const struct sockaddr_in6 *) &sa; 799 &addrlen);
825 ok = (((NULL == sh->v6_allowed) || 800 if (NULL == sock)
826 (check_ipv6_listed (sh->v6_allowed, &v6->sin6_addr))) && 801 {
827 ((NULL == sh->v6_denied) || 802 if (EMFILE == errno)
828 (! check_ipv6_listed (sh->v6_denied, &v6->sin6_addr)))); 803 do_suspend(sh, SUSPEND_STATE_EMFILE);
829 break; 804 else if (EAGAIN != errno)
805 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "accept");
806 break;
807 }
808 switch (sa.ss_family)
809 {
810 case AF_INET:
811 GNUNET_assert(addrlen == sizeof(struct sockaddr_in));
812 v4 = (const struct sockaddr_in *)&sa;
813 ok = (((NULL == sh->v4_allowed) ||
814 (check_ipv4_listed(sh->v4_allowed, &v4->sin_addr))) &&
815 ((NULL == sh->v4_denied) ||
816 (!check_ipv4_listed(sh->v4_denied, &v4->sin_addr))));
817 break;
818
819 case AF_INET6:
820 GNUNET_assert(addrlen == sizeof(struct sockaddr_in6));
821 v6 = (const struct sockaddr_in6 *)&sa;
822 ok = (((NULL == sh->v6_allowed) ||
823 (check_ipv6_listed(sh->v6_allowed, &v6->sin6_addr))) &&
824 ((NULL == sh->v6_denied) ||
825 (!check_ipv6_listed(sh->v6_denied, &v6->sin6_addr))));
826 break;
827
830#ifndef WINDOWS 828#ifndef WINDOWS
831 case AF_UNIX: 829 case AF_UNIX:
832 ok = GNUNET_OK; /* controlled using file-system ACL now */ 830 ok = GNUNET_OK; /* controlled using file-system ACL now */
833 break; 831 break;
834#endif 832#endif
835 default: 833 default:
836 LOG (GNUNET_ERROR_TYPE_WARNING, 834 LOG(GNUNET_ERROR_TYPE_WARNING,
837 _ ("Unknown address family %d\n"), 835 _("Unknown address family %d\n"),
838 sa.ss_family); 836 sa.ss_family);
839 return; 837 return;
840 } 838 }
841 if (! ok) 839 if (!ok)
842 { 840 {
843 LOG (GNUNET_ERROR_TYPE_DEBUG, 841 LOG(GNUNET_ERROR_TYPE_DEBUG,
844 "Service rejected incoming connection from %s due to policy.\n", 842 "Service rejected incoming connection from %s due to policy.\n",
845 GNUNET_a2s ((const struct sockaddr *) &sa, addrlen)); 843 GNUNET_a2s((const struct sockaddr *)&sa, addrlen));
846 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock)); 844 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(sock));
847 continue; 845 continue;
846 }
847 LOG(GNUNET_ERROR_TYPE_DEBUG,
848 "Service accepted incoming connection from %s.\n",
849 GNUNET_a2s((const struct sockaddr *)&sa, addrlen));
850 start_client(slc->sh, sock);
848 } 851 }
849 LOG (GNUNET_ERROR_TYPE_DEBUG,
850 "Service accepted incoming connection from %s.\n",
851 GNUNET_a2s ((const struct sockaddr *) &sa, addrlen));
852 start_client (slc->sh, sock);
853 }
854 if (0 != sh->suspend_state) 852 if (0 != sh->suspend_state)
855 return; 853 return;
856 slc->listen_task = 854 slc->listen_task =
857 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 855 GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
858 slc->listen_socket, 856 slc->listen_socket,
859 &accept_client, 857 &accept_client,
860 slc); 858 slc);
861} 859}
862 860
863 861
@@ -869,23 +867,23 @@ accept_client (void *cls)
869 * or #SUSPEND_STATE_NONE on first startup 867 * or #SUSPEND_STATE_NONE on first startup
870 */ 868 */
871static void 869static void
872do_resume (struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr) 870do_resume(struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr)
873{ 871{
874 struct ServiceListenContext *slc; 872 struct ServiceListenContext *slc;
875 873
876 GNUNET_assert ((SUSPEND_STATE_NONE == sr) || (0 != (sh->suspend_state & sr))); 874 GNUNET_assert((SUSPEND_STATE_NONE == sr) || (0 != (sh->suspend_state & sr)));
877 sh->suspend_state -= sr; 875 sh->suspend_state -= sr;
878 if (SUSPEND_STATE_NONE != sh->suspend_state) 876 if (SUSPEND_STATE_NONE != sh->suspend_state)
879 return; 877 return;
880 for (slc = sh->slc_head; NULL != slc; slc = slc->next) 878 for (slc = sh->slc_head; NULL != slc; slc = slc->next)
881 { 879 {
882 GNUNET_assert (NULL == slc->listen_task); 880 GNUNET_assert(NULL == slc->listen_task);
883 slc->listen_task = 881 slc->listen_task =
884 GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 882 GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
885 slc->listen_socket, 883 slc->listen_socket,
886 &accept_client, 884 &accept_client,
887 slc); 885 slc);
888 } 886 }
889} 887}
890 888
891 889
@@ -897,23 +895,23 @@ do_resume (struct GNUNET_SERVICE_Handle *sh, enum SuspendReason sr)
897 * @param cls our `struct GNUNET_SERVICE_Handle` 895 * @param cls our `struct GNUNET_SERVICE_Handle`
898 */ 896 */
899static void 897static void
900service_main (void *cls) 898service_main(void *cls)
901{ 899{
902 struct GNUNET_SERVICE_Handle *sh = cls; 900 struct GNUNET_SERVICE_Handle *sh = cls;
903 901
904 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options) 902 if (GNUNET_SERVICE_OPTION_MANUAL_SHUTDOWN != sh->options)
905 GNUNET_SCHEDULER_add_shutdown (&service_shutdown, sh); 903 GNUNET_SCHEDULER_add_shutdown(&service_shutdown, sh);
906 do_resume (sh, SUSPEND_STATE_NONE); 904 do_resume(sh, SUSPEND_STATE_NONE);
907 905
908 if (-1 != sh->ready_confirm_fd) 906 if (-1 != sh->ready_confirm_fd)
909 { 907 {
910 GNUNET_break (1 == write (sh->ready_confirm_fd, ".", 1)); 908 GNUNET_break(1 == write(sh->ready_confirm_fd, ".", 1));
911 GNUNET_break (0 == close (sh->ready_confirm_fd)); 909 GNUNET_break(0 == close(sh->ready_confirm_fd));
912 sh->ready_confirm_fd = -1; 910 sh->ready_confirm_fd = -1;
913 } 911 }
914 912
915 if (NULL != sh->service_init_cb) 913 if (NULL != sh->service_init_cb)
916 sh->service_init_cb (sh->cb_cls, sh->cfg, sh); 914 sh->service_init_cb(sh->cb_cls, sh->cfg, sh);
917} 915}
918 916
919 917
@@ -927,33 +925,33 @@ service_main (void *cls)
927 * no ACL configured) 925 * no ACL configured)
928 */ 926 */
929static int 927static int
930process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret, 928process_acl4(struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
931 struct GNUNET_SERVICE_Handle *sh, 929 struct GNUNET_SERVICE_Handle *sh,
932 const char *option) 930 const char *option)
933{ 931{
934 char *opt; 932 char *opt;
935 933
936 if (! GNUNET_CONFIGURATION_have_value (sh->cfg, sh->service_name, option)) 934 if (!GNUNET_CONFIGURATION_have_value(sh->cfg, sh->service_name, option))
937 { 935 {
938 *ret = NULL; 936 *ret = NULL;
939 return GNUNET_OK; 937 return GNUNET_OK;
940 } 938 }
941 GNUNET_break (GNUNET_OK == 939 GNUNET_break(GNUNET_OK ==
942 GNUNET_CONFIGURATION_get_value_string (sh->cfg, 940 GNUNET_CONFIGURATION_get_value_string(sh->cfg,
943 sh->service_name, 941 sh->service_name,
944 option, 942 option,
945 &opt)); 943 &opt));
946 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy (opt))) 944 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv4_policy(opt)))
947 { 945 {
948 LOG (GNUNET_ERROR_TYPE_WARNING, 946 LOG(GNUNET_ERROR_TYPE_WARNING,
949 _ ("Could not parse IPv4 network specification `%s' for `%s:%s'\n"), 947 _("Could not parse IPv4 network specification `%s' for `%s:%s'\n"),
950 opt, 948 opt,
951 sh->service_name, 949 sh->service_name,
952 option); 950 option);
953 GNUNET_free (opt); 951 GNUNET_free(opt);
954 return GNUNET_SYSERR; 952 return GNUNET_SYSERR;
955 } 953 }
956 GNUNET_free (opt); 954 GNUNET_free(opt);
957 return GNUNET_OK; 955 return GNUNET_OK;
958} 956}
959 957
@@ -968,33 +966,33 @@ process_acl4 (struct GNUNET_STRINGS_IPv4NetworkPolicy **ret,
968 * no ACL configured) 966 * no ACL configured)
969 */ 967 */
970static int 968static int
971process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret, 969process_acl6(struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
972 struct GNUNET_SERVICE_Handle *sh, 970 struct GNUNET_SERVICE_Handle *sh,
973 const char *option) 971 const char *option)
974{ 972{
975 char *opt; 973 char *opt;
976 974
977 if (! GNUNET_CONFIGURATION_have_value (sh->cfg, sh->service_name, option)) 975 if (!GNUNET_CONFIGURATION_have_value(sh->cfg, sh->service_name, option))
978 { 976 {
979 *ret = NULL; 977 *ret = NULL;
980 return GNUNET_OK; 978 return GNUNET_OK;
981 } 979 }
982 GNUNET_break (GNUNET_OK == 980 GNUNET_break(GNUNET_OK ==
983 GNUNET_CONFIGURATION_get_value_string (sh->cfg, 981 GNUNET_CONFIGURATION_get_value_string(sh->cfg,
984 sh->service_name, 982 sh->service_name,
985 option, 983 option,
986 &opt)); 984 &opt));
987 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy (opt))) 985 if (NULL == (*ret = GNUNET_STRINGS_parse_ipv6_policy(opt)))
988 { 986 {
989 LOG (GNUNET_ERROR_TYPE_WARNING, 987 LOG(GNUNET_ERROR_TYPE_WARNING,
990 _ ("Could not parse IPv6 network specification `%s' for `%s:%s'\n"), 988 _("Could not parse IPv6 network specification `%s' for `%s:%s'\n"),
991 opt, 989 opt,
992 sh->service_name, 990 sh->service_name,
993 option); 991 option);
994 GNUNET_free (opt); 992 GNUNET_free(opt);
995 return GNUNET_SYSERR; 993 return GNUNET_SYSERR;
996 } 994 }
997 GNUNET_free (opt); 995 GNUNET_free(opt);
998 return GNUNET_OK; 996 return GNUNET_OK;
999} 997}
1000 998
@@ -1010,30 +1008,30 @@ process_acl6 (struct GNUNET_STRINGS_IPv6NetworkPolicy **ret,
1010 * parameter is ignore on systems other than LINUX 1008 * parameter is ignore on systems other than LINUX
1011 */ 1009 */
1012static void 1010static void
1013add_unixpath (struct sockaddr **saddrs, 1011add_unixpath(struct sockaddr **saddrs,
1014 socklen_t *saddrlens, 1012 socklen_t *saddrlens,
1015 const char *unixpath, 1013 const char *unixpath,
1016 int abstract) 1014 int abstract)
1017{ 1015{
1018#ifdef AF_UNIX 1016#ifdef AF_UNIX
1019 struct sockaddr_un *un; 1017 struct sockaddr_un *un;
1020 1018
1021 un = GNUNET_new (struct sockaddr_un); 1019 un = GNUNET_new(struct sockaddr_un);
1022 un->sun_family = AF_UNIX; 1020 un->sun_family = AF_UNIX;
1023 GNUNET_strlcpy (un->sun_path, unixpath, sizeof (un->sun_path)); 1021 GNUNET_strlcpy(un->sun_path, unixpath, sizeof(un->sun_path));
1024#ifdef LINUX 1022#ifdef LINUX
1025 if (GNUNET_YES == abstract) 1023 if (GNUNET_YES == abstract)
1026 un->sun_path[0] = '\0'; 1024 un->sun_path[0] = '\0';
1027#endif 1025#endif
1028#if HAVE_SOCKADDR_UN_SUN_LEN 1026#if HAVE_SOCKADDR_UN_SUN_LEN
1029 un->sun_len = (u_char) sizeof (struct sockaddr_un); 1027 un->sun_len = (u_char)sizeof(struct sockaddr_un);
1030#endif 1028#endif
1031 *saddrs = (struct sockaddr *) un; 1029 *saddrs = (struct sockaddr *)un;
1032 *saddrlens = sizeof (struct sockaddr_un); 1030 *saddrlens = sizeof(struct sockaddr_un);
1033#else 1031#else
1034 /* this function should never be called 1032 /* this function should never be called
1035 * unless AF_UNIX is defined! */ 1033 * unless AF_UNIX is defined! */
1036 GNUNET_assert (0); 1034 GNUNET_assert(0);
1037#endif 1035#endif
1038} 1036}
1039 1037
@@ -1059,10 +1057,10 @@ add_unixpath (struct sockaddr **saddrs,
1059 * set to NULL). 1057 * set to NULL).
1060 */ 1058 */
1061static int 1059static int
1062get_server_addresses (const char *service_name, 1060get_server_addresses(const char *service_name,
1063 const struct GNUNET_CONFIGURATION_Handle *cfg, 1061 const struct GNUNET_CONFIGURATION_Handle *cfg,
1064 struct sockaddr ***addrs, 1062 struct sockaddr ***addrs,
1065 socklen_t **addr_lens) 1063 socklen_t **addr_lens)
1066{ 1064{
1067 int disablev6; 1065 int disablev6;
1068 struct GNUNET_NETWORK_Handle *desc; 1066 struct GNUNET_NETWORK_Handle *desc;
@@ -1084,40 +1082,40 @@ get_server_addresses (const char *service_name,
1084 *addr_lens = NULL; 1082 *addr_lens = NULL;
1085 desc = NULL; 1083 desc = NULL;
1086 disablev6 = GNUNET_NO; 1084 disablev6 = GNUNET_NO;
1087 if ((GNUNET_NO == GNUNET_NETWORK_test_pf (PF_INET6)) || 1085 if ((GNUNET_NO == GNUNET_NETWORK_test_pf(PF_INET6)) ||
1088 (GNUNET_YES == 1086 (GNUNET_YES ==
1089 GNUNET_CONFIGURATION_get_value_yesno (cfg, service_name, "DISABLEV6"))) 1087 GNUNET_CONFIGURATION_get_value_yesno(cfg, service_name, "DISABLEV6")))
1090 disablev6 = GNUNET_YES; 1088 disablev6 = GNUNET_YES;
1091 1089
1092 port = 0; 1090 port = 0;
1093 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "PORT")) 1091 if (GNUNET_CONFIGURATION_have_value(cfg, service_name, "PORT"))
1094 {
1095 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg,
1096 service_name,
1097 "PORT",
1098 &port))
1099 { 1092 {
1100 LOG (GNUNET_ERROR_TYPE_ERROR, 1093 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg,
1101 _ ("Require valid port number for service `%s' in configuration!\n"), 1094 service_name,
1102 service_name); 1095 "PORT",
1103 } 1096 &port))
1104 if (port > 65535) 1097 {
1105 { 1098 LOG(GNUNET_ERROR_TYPE_ERROR,
1106 LOG (GNUNET_ERROR_TYPE_ERROR, 1099 _("Require valid port number for service `%s' in configuration!\n"),
1107 _ ("Require valid port number for service `%s' in configuration!\n"), 1100 service_name);
1108 service_name); 1101 }
1109 return GNUNET_SYSERR; 1102 if (port > 65535)
1103 {
1104 LOG(GNUNET_ERROR_TYPE_ERROR,
1105 _("Require valid port number for service `%s' in configuration!\n"),
1106 service_name);
1107 return GNUNET_SYSERR;
1108 }
1110 } 1109 }
1111 }
1112 1110
1113 if (GNUNET_CONFIGURATION_have_value (cfg, service_name, "BINDTO")) 1111 if (GNUNET_CONFIGURATION_have_value(cfg, service_name, "BINDTO"))
1114 { 1112 {
1115 GNUNET_break (GNUNET_OK == 1113 GNUNET_break(GNUNET_OK ==
1116 GNUNET_CONFIGURATION_get_value_string (cfg, 1114 GNUNET_CONFIGURATION_get_value_string(cfg,
1117 service_name, 1115 service_name,
1118 "BINDTO", 1116 "BINDTO",
1119 &hostname)); 1117 &hostname));
1120 } 1118 }
1121 else 1119 else
1122 hostname = NULL; 1120 hostname = NULL;
1123 1121
@@ -1125,232 +1123,232 @@ get_server_addresses (const char *service_name,
1125 abstract = GNUNET_NO; 1123 abstract = GNUNET_NO;
1126#ifdef AF_UNIX 1124#ifdef AF_UNIX
1127 if ((GNUNET_YES == 1125 if ((GNUNET_YES ==
1128 GNUNET_CONFIGURATION_have_value (cfg, service_name, "UNIXPATH")) && 1126 GNUNET_CONFIGURATION_have_value(cfg, service_name, "UNIXPATH")) &&
1129 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename (cfg, 1127 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_filename(cfg,
1130 service_name, 1128 service_name,
1131 "UNIXPATH", 1129 "UNIXPATH",
1132 &unixpath)) && 1130 &unixpath)) &&
1133 (0 < strlen (unixpath))) 1131 (0 < strlen(unixpath)))
1134 {
1135 /* probe UNIX support */
1136 struct sockaddr_un s_un;
1137
1138 if (strlen (unixpath) >= sizeof (s_un.sun_path))
1139 { 1132 {
1140 LOG (GNUNET_ERROR_TYPE_WARNING, 1133 /* probe UNIX support */
1141 _ ("UNIXPATH `%s' too long, maximum length is %llu\n"), 1134 struct sockaddr_un s_un;
1142 unixpath, 1135
1143 (unsigned long long) sizeof (s_un.sun_path)); 1136 if (strlen(unixpath) >= sizeof(s_un.sun_path))
1144 unixpath = GNUNET_NETWORK_shorten_unixpath (unixpath); 1137 {
1145 LOG (GNUNET_ERROR_TYPE_INFO, _ ("Using `%s' instead\n"), unixpath); 1138 LOG(GNUNET_ERROR_TYPE_WARNING,
1146 } 1139 _("UNIXPATH `%s' too long, maximum length is %llu\n"),
1140 unixpath,
1141 (unsigned long long)sizeof(s_un.sun_path));
1142 unixpath = GNUNET_NETWORK_shorten_unixpath(unixpath);
1143 LOG(GNUNET_ERROR_TYPE_INFO, _("Using `%s' instead\n"), unixpath);
1144 }
1147#ifdef LINUX 1145#ifdef LINUX
1148 abstract = GNUNET_CONFIGURATION_get_value_yesno (cfg, 1146 abstract = GNUNET_CONFIGURATION_get_value_yesno(cfg,
1149 "TESTING", 1147 "TESTING",
1150 "USE_ABSTRACT_SOCKETS"); 1148 "USE_ABSTRACT_SOCKETS");
1151 if (GNUNET_SYSERR == abstract) 1149 if (GNUNET_SYSERR == abstract)
1152 abstract = GNUNET_NO; 1150 abstract = GNUNET_NO;
1153#endif 1151#endif
1154 if ((GNUNET_YES != abstract) && 1152 if ((GNUNET_YES != abstract) &&
1155 (GNUNET_OK != GNUNET_DISK_directory_create_for_file (unixpath))) 1153 (GNUNET_OK != GNUNET_DISK_directory_create_for_file(unixpath)))
1156 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "mkdir", unixpath); 1154 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "mkdir", unixpath);
1157 }
1158 if (NULL != unixpath)
1159 {
1160 desc = GNUNET_NETWORK_socket_create (AF_UNIX, SOCK_STREAM, 0);
1161 if (NULL == desc)
1162 {
1163 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
1164 (EACCES == errno))
1165 {
1166 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket");
1167 GNUNET_free_non_null (hostname);
1168 GNUNET_free (unixpath);
1169 return GNUNET_SYSERR;
1170 }
1171 LOG (GNUNET_ERROR_TYPE_INFO,
1172 _ (
1173 "Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
1174 service_name,
1175 strerror (errno));
1176 GNUNET_free (unixpath);
1177 unixpath = NULL;
1178 } 1155 }
1179 else 1156 if (NULL != unixpath)
1180 { 1157 {
1181 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (desc)); 1158 desc = GNUNET_NETWORK_socket_create(AF_UNIX, SOCK_STREAM, 0);
1182 desc = NULL; 1159 if (NULL == desc)
1160 {
1161 if ((ENOBUFS == errno) || (ENOMEM == errno) || (ENFILE == errno) ||
1162 (EACCES == errno))
1163 {
1164 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "socket");
1165 GNUNET_free_non_null(hostname);
1166 GNUNET_free(unixpath);
1167 return GNUNET_SYSERR;
1168 }
1169 LOG(GNUNET_ERROR_TYPE_INFO,
1170 _(
1171 "Disabling UNIX domain socket support for service `%s', failed to create UNIX domain socket: %s\n"),
1172 service_name,
1173 strerror(errno));
1174 GNUNET_free(unixpath);
1175 unixpath = NULL;
1176 }
1177 else
1178 {
1179 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(desc));
1180 desc = NULL;
1181 }
1183 } 1182 }
1184 }
1185#endif 1183#endif
1186 1184
1187 if ((0 == port) && (NULL == unixpath)) 1185 if ((0 == port) && (NULL == unixpath))
1188 {
1189 LOG (GNUNET_ERROR_TYPE_ERROR,
1190 _ (
1191 "Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1192 service_name);
1193 GNUNET_free_non_null (hostname);
1194 return GNUNET_SYSERR;
1195 }
1196 if (0 == port)
1197 {
1198 saddrs = GNUNET_new_array (2, struct sockaddr *);
1199 saddrlens = GNUNET_new_array (2, socklen_t);
1200 add_unixpath (saddrs, saddrlens, unixpath, abstract);
1201 GNUNET_free_non_null (unixpath);
1202 GNUNET_free_non_null (hostname);
1203 *addrs = saddrs;
1204 *addr_lens = saddrlens;
1205 return 1;
1206 }
1207
1208 if (NULL != hostname)
1209 {
1210 LOG (GNUNET_ERROR_TYPE_DEBUG,
1211 "Resolving `%s' since that is where `%s' will bind to.\n",
1212 hostname,
1213 service_name);
1214 memset (&hints, 0, sizeof (struct addrinfo));
1215 if (disablev6)
1216 hints.ai_family = AF_INET;
1217 hints.ai_protocol = IPPROTO_TCP;
1218 if ((0 != (ret = getaddrinfo (hostname, NULL, &hints, &res))) ||
1219 (NULL == res))
1220 { 1186 {
1221 LOG (GNUNET_ERROR_TYPE_ERROR, 1187 LOG(GNUNET_ERROR_TYPE_ERROR,
1222 _ ("Failed to resolve `%s': %s\n"), 1188 _(
1223 hostname, 1189 "Have neither PORT nor UNIXPATH for service `%s', but one is required\n"),
1224 gai_strerror (ret)); 1190 service_name);
1225 GNUNET_free (hostname); 1191 GNUNET_free_non_null(hostname);
1226 GNUNET_free_non_null (unixpath);
1227 return GNUNET_SYSERR; 1192 return GNUNET_SYSERR;
1228 } 1193 }
1229 next = res; 1194 if (0 == port)
1230 i = 0;
1231 while (NULL != (pos = next))
1232 {
1233 next = pos->ai_next;
1234 if ((disablev6) && (pos->ai_family == AF_INET6))
1235 continue;
1236 i++;
1237 }
1238 if (0 == i)
1239 {
1240 LOG (GNUNET_ERROR_TYPE_ERROR,
1241 _ ("Failed to find %saddress for `%s'.\n"),
1242 disablev6 ? "IPv4 " : "",
1243 hostname);
1244 freeaddrinfo (res);
1245 GNUNET_free (hostname);
1246 GNUNET_free_non_null (unixpath);
1247 return GNUNET_SYSERR;
1248 }
1249 resi = i;
1250 if (NULL != unixpath)
1251 resi++;
1252 saddrs = GNUNET_new_array (resi + 1, struct sockaddr *);
1253 saddrlens = GNUNET_new_array (resi + 1, socklen_t);
1254 i = 0;
1255 if (NULL != unixpath)
1256 { 1195 {
1257 add_unixpath (saddrs, saddrlens, unixpath, abstract); 1196 saddrs = GNUNET_new_array(2, struct sockaddr *);
1258 i++; 1197 saddrlens = GNUNET_new_array(2, socklen_t);
1198 add_unixpath(saddrs, saddrlens, unixpath, abstract);
1199 GNUNET_free_non_null(unixpath);
1200 GNUNET_free_non_null(hostname);
1201 *addrs = saddrs;
1202 *addr_lens = saddrlens;
1203 return 1;
1259 } 1204 }
1260 next = res; 1205
1261 while (NULL != (pos = next)) 1206 if (NULL != hostname)
1262 {
1263 next = pos->ai_next;
1264 if ((disablev6) && (AF_INET6 == pos->ai_family))
1265 continue;
1266 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
1267 continue; /* not TCP */
1268 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
1269 continue; /* huh? */
1270 LOG (GNUNET_ERROR_TYPE_DEBUG,
1271 "Service `%s' will bind to `%s'\n",
1272 service_name,
1273 GNUNET_a2s (pos->ai_addr, pos->ai_addrlen));
1274 if (AF_INET == pos->ai_family)
1275 {
1276 GNUNET_assert (sizeof (struct sockaddr_in) == pos->ai_addrlen);
1277 saddrlens[i] = pos->ai_addrlen;
1278 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1279 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1280 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port);
1281 }
1282 else
1283 {
1284 GNUNET_assert (AF_INET6 == pos->ai_family);
1285 GNUNET_assert (sizeof (struct sockaddr_in6) == pos->ai_addrlen);
1286 saddrlens[i] = pos->ai_addrlen;
1287 saddrs[i] = GNUNET_malloc (saddrlens[i]);
1288 GNUNET_memcpy (saddrs[i], pos->ai_addr, saddrlens[i]);
1289 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port);
1290 }
1291 i++;
1292 }
1293 GNUNET_free (hostname);
1294 freeaddrinfo (res);
1295 resi = i;
1296 }
1297 else
1298 {
1299 /* will bind against everything, just set port */
1300 if (disablev6)
1301 { 1207 {
1302 /* V4-only */ 1208 LOG(GNUNET_ERROR_TYPE_DEBUG,
1303 resi = 1; 1209 "Resolving `%s' since that is where `%s' will bind to.\n",
1210 hostname,
1211 service_name);
1212 memset(&hints, 0, sizeof(struct addrinfo));
1213 if (disablev6)
1214 hints.ai_family = AF_INET;
1215 hints.ai_protocol = IPPROTO_TCP;
1216 if ((0 != (ret = getaddrinfo(hostname, NULL, &hints, &res))) ||
1217 (NULL == res))
1218 {
1219 LOG(GNUNET_ERROR_TYPE_ERROR,
1220 _("Failed to resolve `%s': %s\n"),
1221 hostname,
1222 gai_strerror(ret));
1223 GNUNET_free(hostname);
1224 GNUNET_free_non_null(unixpath);
1225 return GNUNET_SYSERR;
1226 }
1227 next = res;
1228 i = 0;
1229 while (NULL != (pos = next))
1230 {
1231 next = pos->ai_next;
1232 if ((disablev6) && (pos->ai_family == AF_INET6))
1233 continue;
1234 i++;
1235 }
1236 if (0 == i)
1237 {
1238 LOG(GNUNET_ERROR_TYPE_ERROR,
1239 _("Failed to find %saddress for `%s'.\n"),
1240 disablev6 ? "IPv4 " : "",
1241 hostname);
1242 freeaddrinfo(res);
1243 GNUNET_free(hostname);
1244 GNUNET_free_non_null(unixpath);
1245 return GNUNET_SYSERR;
1246 }
1247 resi = i;
1304 if (NULL != unixpath) 1248 if (NULL != unixpath)
1305 resi++; 1249 resi++;
1250 saddrs = GNUNET_new_array(resi + 1, struct sockaddr *);
1251 saddrlens = GNUNET_new_array(resi + 1, socklen_t);
1306 i = 0; 1252 i = 0;
1307 saddrs = GNUNET_new_array (resi + 1, struct sockaddr *);
1308 saddrlens = GNUNET_new_array (resi + 1, socklen_t);
1309 if (NULL != unixpath) 1253 if (NULL != unixpath)
1310 { 1254 {
1311 add_unixpath (saddrs, saddrlens, unixpath, abstract); 1255 add_unixpath(saddrs, saddrlens, unixpath, abstract);
1312 i++; 1256 i++;
1313 } 1257 }
1314 saddrlens[i] = sizeof (struct sockaddr_in); 1258 next = res;
1315 saddrs[i] = GNUNET_malloc (saddrlens[i]); 1259 while (NULL != (pos = next))
1316#if HAVE_SOCKADDR_IN_SIN_LEN 1260 {
1317 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[i]; 1261 next = pos->ai_next;
1318#endif 1262 if ((disablev6) && (AF_INET6 == pos->ai_family))
1319 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET; 1263 continue;
1320 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port); 1264 if ((IPPROTO_TCP != pos->ai_protocol) && (0 != pos->ai_protocol))
1265 continue; /* not TCP */
1266 if ((SOCK_STREAM != pos->ai_socktype) && (0 != pos->ai_socktype))
1267 continue; /* huh? */
1268 LOG(GNUNET_ERROR_TYPE_DEBUG,
1269 "Service `%s' will bind to `%s'\n",
1270 service_name,
1271 GNUNET_a2s(pos->ai_addr, pos->ai_addrlen));
1272 if (AF_INET == pos->ai_family)
1273 {
1274 GNUNET_assert(sizeof(struct sockaddr_in) == pos->ai_addrlen);
1275 saddrlens[i] = pos->ai_addrlen;
1276 saddrs[i] = GNUNET_malloc(saddrlens[i]);
1277 GNUNET_memcpy(saddrs[i], pos->ai_addr, saddrlens[i]);
1278 ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port);
1279 }
1280 else
1281 {
1282 GNUNET_assert(AF_INET6 == pos->ai_family);
1283 GNUNET_assert(sizeof(struct sockaddr_in6) == pos->ai_addrlen);
1284 saddrlens[i] = pos->ai_addrlen;
1285 saddrs[i] = GNUNET_malloc(saddrlens[i]);
1286 GNUNET_memcpy(saddrs[i], pos->ai_addr, saddrlens[i]);
1287 ((struct sockaddr_in6 *)saddrs[i])->sin6_port = htons(port);
1288 }
1289 i++;
1290 }
1291 GNUNET_free(hostname);
1292 freeaddrinfo(res);
1293 resi = i;
1321 } 1294 }
1322 else 1295 else
1323 { 1296 {
1324 /* dual stack */ 1297 /* will bind against everything, just set port */
1325 resi = 2; 1298 if (disablev6)
1326 if (NULL != unixpath) 1299 {
1327 resi++; 1300 /* V4-only */
1328 saddrs = GNUNET_new_array (resi + 1, struct sockaddr *); 1301 resi = 1;
1329 saddrlens = GNUNET_new_array (resi + 1, socklen_t); 1302 if (NULL != unixpath)
1330 i = 0; 1303 resi++;
1331 if (NULL != unixpath) 1304 i = 0;
1332 { 1305 saddrs = GNUNET_new_array(resi + 1, struct sockaddr *);
1333 add_unixpath (saddrs, saddrlens, unixpath, abstract); 1306 saddrlens = GNUNET_new_array(resi + 1, socklen_t);
1334 i++; 1307 if (NULL != unixpath)
1335 } 1308 {
1336 saddrlens[i] = sizeof (struct sockaddr_in6); 1309 add_unixpath(saddrs, saddrlens, unixpath, abstract);
1337 saddrs[i] = GNUNET_malloc (saddrlens[i]); 1310 i++;
1311 }
1312 saddrlens[i] = sizeof(struct sockaddr_in);
1313 saddrs[i] = GNUNET_malloc(saddrlens[i]);
1338#if HAVE_SOCKADDR_IN_SIN_LEN 1314#if HAVE_SOCKADDR_IN_SIN_LEN
1339 ((struct sockaddr_in6 *) saddrs[i])->sin6_len = saddrlens[0]; 1315 ((struct sockaddr_in *)saddrs[i])->sin_len = saddrlens[i];
1340#endif 1316#endif
1341 ((struct sockaddr_in6 *) saddrs[i])->sin6_family = AF_INET6; 1317 ((struct sockaddr_in *)saddrs[i])->sin_family = AF_INET;
1342 ((struct sockaddr_in6 *) saddrs[i])->sin6_port = htons (port); 1318 ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port);
1343 i++; 1319 }
1344 saddrlens[i] = sizeof (struct sockaddr_in); 1320 else
1345 saddrs[i] = GNUNET_malloc (saddrlens[i]); 1321 {
1322 /* dual stack */
1323 resi = 2;
1324 if (NULL != unixpath)
1325 resi++;
1326 saddrs = GNUNET_new_array(resi + 1, struct sockaddr *);
1327 saddrlens = GNUNET_new_array(resi + 1, socklen_t);
1328 i = 0;
1329 if (NULL != unixpath)
1330 {
1331 add_unixpath(saddrs, saddrlens, unixpath, abstract);
1332 i++;
1333 }
1334 saddrlens[i] = sizeof(struct sockaddr_in6);
1335 saddrs[i] = GNUNET_malloc(saddrlens[i]);
1336#if HAVE_SOCKADDR_IN_SIN_LEN
1337 ((struct sockaddr_in6 *)saddrs[i])->sin6_len = saddrlens[0];
1338#endif
1339 ((struct sockaddr_in6 *)saddrs[i])->sin6_family = AF_INET6;
1340 ((struct sockaddr_in6 *)saddrs[i])->sin6_port = htons(port);
1341 i++;
1342 saddrlens[i] = sizeof(struct sockaddr_in);
1343 saddrs[i] = GNUNET_malloc(saddrlens[i]);
1346#if HAVE_SOCKADDR_IN_SIN_LEN 1344#if HAVE_SOCKADDR_IN_SIN_LEN
1347 ((struct sockaddr_in *) saddrs[i])->sin_len = saddrlens[1]; 1345 ((struct sockaddr_in *)saddrs[i])->sin_len = saddrlens[1];
1348#endif 1346#endif
1349 ((struct sockaddr_in *) saddrs[i])->sin_family = AF_INET; 1347 ((struct sockaddr_in *)saddrs[i])->sin_family = AF_INET;
1350 ((struct sockaddr_in *) saddrs[i])->sin_port = htons (port); 1348 ((struct sockaddr_in *)saddrs[i])->sin_port = htons(port);
1349 }
1351 } 1350 }
1352 } 1351 GNUNET_free_non_null(unixpath);
1353 GNUNET_free_non_null (unixpath);
1354 *addrs = saddrs; 1352 *addrs = saddrs;
1355 *addr_lens = saddrlens; 1353 *addr_lens = saddrlens;
1356 return resi; 1354 return resi;
@@ -1366,7 +1364,7 @@ get_server_addresses (const char *service_name,
1366 * NULL if not ok (must bind yourself) 1364 * NULL if not ok (must bind yourself)
1367 */ 1365 */
1368static struct GNUNET_NETWORK_Handle ** 1366static struct GNUNET_NETWORK_Handle **
1369receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh) 1367receive_sockets_from_parent(struct GNUNET_SERVICE_Handle *sh)
1370{ 1368{
1371 static struct GNUNET_NETWORK_Handle **lsocks; 1369 static struct GNUNET_NETWORK_Handle **lsocks;
1372 const char *env_buf; 1370 const char *env_buf;
@@ -1375,69 +1373,70 @@ receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
1375 uint64_t i; 1373 uint64_t i;
1376 HANDLE lsocks_pipe; 1374 HANDLE lsocks_pipe;
1377 1375
1378 env_buf = getenv ("GNUNET_OS_READ_LSOCKS"); 1376 env_buf = getenv("GNUNET_OS_READ_LSOCKS");
1379 if ((NULL == env_buf) || (strlen (env_buf) <= 0)) 1377 if ((NULL == env_buf) || (strlen(env_buf) <= 0))
1380 return NULL; 1378 return NULL;
1381 /* Using W32 API directly here, because this pipe will 1379 /* Using W32 API directly here, because this pipe will
1382 * never be used outside of this function, and it's just too much of a bother 1380 * never be used outside of this function, and it's just too much of a bother
1383 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks) 1381 * to create a GNUnet API that boxes a HANDLE (the way it is done with socks)
1384 */ 1382 */
1385 lsocks_pipe = (HANDLE) strtoul (env_buf, NULL, 10); 1383 lsocks_pipe = (HANDLE)strtoul(env_buf, NULL, 10);
1386 if ((0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe)) 1384 if ((0 == lsocks_pipe) || (INVALID_HANDLE_VALUE == lsocks_pipe))
1387 return NULL; 1385 return NULL;
1388 fail = 1; 1386 fail = 1;
1389 do 1387 do
1390 {
1391 int ret;
1392 int fail2;
1393 DWORD rd;
1394
1395 ret = ReadFile (lsocks_pipe, &count, sizeof (count), &rd, NULL);
1396 if ((0 == ret) || (sizeof (count) != rd) || (0 == count))
1397 break;
1398 lsocks = GNUNET_new_array (count + 1, struct GNUNET_NETWORK_Handle *);
1399
1400 fail2 = 1;
1401 for (i = 0; i < count; i++)
1402 { 1388 {
1403 WSAPROTOCOL_INFOA pi; 1389 int ret;
1404 uint64_t size; 1390 int fail2;
1405 SOCKET s; 1391 DWORD rd;
1406 1392
1407 ret = ReadFile (lsocks_pipe, &size, sizeof (size), &rd, NULL); 1393 ret = ReadFile(lsocks_pipe, &count, sizeof(count), &rd, NULL);
1408 if ((0 == ret) || (sizeof (size) != rd) || (sizeof (pi) != size)) 1394 if ((0 == ret) || (sizeof(count) != rd) || (0 == count))
1409 break; 1395 break;
1410 ret = ReadFile (lsocks_pipe, &pi, sizeof (pi), &rd, NULL); 1396 lsocks = GNUNET_new_array(count + 1, struct GNUNET_NETWORK_Handle *);
1411 if ((0 == ret) || (sizeof (pi) != rd)) 1397
1398 fail2 = 1;
1399 for (i = 0; i < count; i++)
1400 {
1401 WSAPROTOCOL_INFOA pi;
1402 uint64_t size;
1403 SOCKET s;
1404
1405 ret = ReadFile(lsocks_pipe, &size, sizeof(size), &rd, NULL);
1406 if ((0 == ret) || (sizeof(size) != rd) || (sizeof(pi) != size))
1407 break;
1408 ret = ReadFile(lsocks_pipe, &pi, sizeof(pi), &rd, NULL);
1409 if ((0 == ret) || (sizeof(pi) != rd))
1410 break;
1411 s = WSASocketA(pi.iAddressFamily,
1412 pi.iSocketType,
1413 pi.iProtocol,
1414 &pi,
1415 0,
1416 WSA_FLAG_OVERLAPPED);
1417 lsocks[i] = GNUNET_NETWORK_socket_box_native(s);
1418 if (NULL == lsocks[i])
1419 break;
1420 else if (i == count - 1)
1421 fail2 = 0;
1422 }
1423 if (fail2)
1412 break; 1424 break;
1413 s = WSASocketA (pi.iAddressFamily, 1425 lsocks[count] = NULL;
1414 pi.iSocketType, 1426 fail = 0;
1415 pi.iProtocol,
1416 &pi,
1417 0,
1418 WSA_FLAG_OVERLAPPED);
1419 lsocks[i] = GNUNET_NETWORK_socket_box_native (s);
1420 if (NULL == lsocks[i])
1421 break;
1422 else if (i == count - 1)
1423 fail2 = 0;
1424 } 1427 }
1425 if (fail2) 1428 while (fail);
1426 break; 1429 CloseHandle(lsocks_pipe);
1427 lsocks[count] = NULL;
1428 fail = 0;
1429 } while (fail);
1430 CloseHandle (lsocks_pipe);
1431 1430
1432 if (fail) 1431 if (fail)
1433 { 1432 {
1434 LOG (GNUNET_ERROR_TYPE_ERROR, 1433 LOG(GNUNET_ERROR_TYPE_ERROR,
1435 _ ("Could not access a pre-bound socket, will try to bind myself\n")); 1434 _("Could not access a pre-bound socket, will try to bind myself\n"));
1436 for (i = 0; (i < count) && (NULL != lsocks[i]); i++) 1435 for (i = 0; (i < count) && (NULL != lsocks[i]); i++)
1437 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (lsocks[i])); 1436 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(lsocks[i]));
1438 GNUNET_free (lsocks); 1437 GNUNET_free(lsocks);
1439 return NULL; 1438 return NULL;
1440 } 1439 }
1441 return lsocks; 1440 return lsocks;
1442} 1441}
1443#endif 1442#endif
@@ -1451,86 +1450,89 @@ receive_sockets_from_parent (struct GNUNET_SERVICE_Handle *sh)
1451 * @return NULL on error, otherwise the listen socket 1450 * @return NULL on error, otherwise the listen socket
1452 */ 1451 */
1453static struct GNUNET_NETWORK_Handle * 1452static struct GNUNET_NETWORK_Handle *
1454open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen) 1453open_listen_socket(const struct sockaddr *server_addr, socklen_t socklen)
1455{ 1454{
1456 struct GNUNET_NETWORK_Handle *sock; 1455 struct GNUNET_NETWORK_Handle *sock;
1457 uint16_t port; 1456 uint16_t port;
1458 int eno; 1457 int eno;
1459 1458
1460 switch (server_addr->sa_family) 1459 switch (server_addr->sa_family)
1461 { 1460 {
1462 case AF_INET: 1461 case AF_INET:
1463 port = ntohs (((const struct sockaddr_in *) server_addr)->sin_port); 1462 port = ntohs(((const struct sockaddr_in *)server_addr)->sin_port);
1464 break; 1463 break;
1465 case AF_INET6: 1464
1466 port = ntohs (((const struct sockaddr_in6 *) server_addr)->sin6_port); 1465 case AF_INET6:
1467 break; 1466 port = ntohs(((const struct sockaddr_in6 *)server_addr)->sin6_port);
1468 case AF_UNIX: 1467 break;
1469 port = 0; 1468
1470 break; 1469 case AF_UNIX:
1471 default: 1470 port = 0;
1472 GNUNET_break (0); 1471 break;
1473 port = 0; 1472
1474 break; 1473 default:
1475 } 1474 GNUNET_break(0);
1476 sock = GNUNET_NETWORK_socket_create (server_addr->sa_family, SOCK_STREAM, 0); 1475 port = 0;
1476 break;
1477 }
1478 sock = GNUNET_NETWORK_socket_create(server_addr->sa_family, SOCK_STREAM, 0);
1477 if (NULL == sock) 1479 if (NULL == sock)
1478 { 1480 {
1479 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "socket"); 1481 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "socket");
1480 errno = 0; 1482 errno = 0;
1481 return NULL; 1483 return NULL;
1482 } 1484 }
1483 /* bind the socket */ 1485 /* bind the socket */
1484 if (GNUNET_OK != GNUNET_NETWORK_socket_bind (sock, server_addr, socklen)) 1486 if (GNUNET_OK != GNUNET_NETWORK_socket_bind(sock, server_addr, socklen))
1485 {
1486 eno = errno;
1487 if (EADDRINUSE != errno)
1488 { 1487 {
1489 /* we don't log 'EADDRINUSE' here since an IPv4 bind may 1488 eno = errno;
1490 * fail if we already took the port on IPv6; if both IPv4 and 1489 if (EADDRINUSE != errno)
1491 * IPv6 binds fail, then our caller will log using the 1490 {
1492 * errno preserved in 'eno' */ 1491 /* we don't log 'EADDRINUSE' here since an IPv4 bind may
1493 if (0 != port) 1492 * fail if we already took the port on IPv6; if both IPv4 and
1494 LOG (GNUNET_ERROR_TYPE_ERROR, 1493 * IPv6 binds fail, then our caller will log using the
1495 _ ("`%s' failed for port %d (%s).\n"), 1494 * errno preserved in 'eno' */
1496 "bind", 1495 if (0 != port)
1497 port, 1496 LOG(GNUNET_ERROR_TYPE_ERROR,
1498 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6"); 1497 _("`%s' failed for port %d (%s).\n"),
1498 "bind",
1499 port,
1500 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1501 else
1502 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "bind");
1503 eno = 0;
1504 }
1499 else 1505 else
1500 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "bind"); 1506 {
1501 eno = 0; 1507 if (0 != port)
1508 LOG(GNUNET_ERROR_TYPE_WARNING,
1509 _("`%s' failed for port %d (%s): address already in use\n"),
1510 "bind",
1511 port,
1512 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1513 else if (AF_UNIX == server_addr->sa_family)
1514 {
1515 LOG(GNUNET_ERROR_TYPE_WARNING,
1516 _("`%s' failed for `%s': address already in use\n"),
1517 "bind",
1518 GNUNET_a2s(server_addr, socklen));
1519 }
1520 }
1521 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(sock));
1522 errno = eno;
1523 return NULL;
1502 } 1524 }
1503 else 1525 if (GNUNET_OK != GNUNET_NETWORK_socket_listen(sock, 5))
1504 { 1526 {
1505 if (0 != port) 1527 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "listen");
1506 LOG (GNUNET_ERROR_TYPE_WARNING, 1528 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(sock));
1507 _ ("`%s' failed for port %d (%s): address already in use\n"), 1529 errno = 0;
1508 "bind", 1530 return NULL;
1509 port,
1510 (AF_INET == server_addr->sa_family) ? "IPv4" : "IPv6");
1511 else if (AF_UNIX == server_addr->sa_family)
1512 {
1513 LOG (GNUNET_ERROR_TYPE_WARNING,
1514 _ ("`%s' failed for `%s': address already in use\n"),
1515 "bind",
1516 GNUNET_a2s (server_addr, socklen));
1517 }
1518 } 1531 }
1519 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
1520 errno = eno;
1521 return NULL;
1522 }
1523 if (GNUNET_OK != GNUNET_NETWORK_socket_listen (sock, 5))
1524 {
1525 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "listen");
1526 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (sock));
1527 errno = 0;
1528 return NULL;
1529 }
1530 if (0 != port) 1532 if (0 != port)
1531 LOG (GNUNET_ERROR_TYPE_DEBUG, 1533 LOG(GNUNET_ERROR_TYPE_DEBUG,
1532 "Server starts to listen on port %u.\n", 1534 "Server starts to listen on port %u.\n",
1533 port); 1535 port);
1534 return sock; 1536 return sock;
1535} 1537}
1536 1538
@@ -1552,10 +1554,11 @@ open_listen_socket (const struct sockaddr *server_addr, socklen_t socklen)
1552 * @return #GNUNET_OK if configuration succeeded 1554 * @return #GNUNET_OK if configuration succeeded
1553 */ 1555 */
1554static int 1556static int
1555setup_service (struct GNUNET_SERVICE_Handle *sh) 1557setup_service(struct GNUNET_SERVICE_Handle *sh)
1556{ 1558{
1557 int tolerant; 1559 int tolerant;
1558 struct GNUNET_NETWORK_Handle **lsocks; 1560 struct GNUNET_NETWORK_Handle **lsocks;
1561
1559#ifndef MINGW 1562#ifndef MINGW
1560 const char *nfds; 1563 const char *nfds;
1561 unsigned int cnt; 1564 unsigned int cnt;
@@ -1563,126 +1566,126 @@ setup_service (struct GNUNET_SERVICE_Handle *sh)
1563 char dummy[2]; 1566 char dummy[2];
1564#endif 1567#endif
1565 1568
1566 if (GNUNET_CONFIGURATION_have_value (sh->cfg, sh->service_name, "TOLERANT")) 1569 if (GNUNET_CONFIGURATION_have_value(sh->cfg, sh->service_name, "TOLERANT"))
1567 {
1568 if (GNUNET_SYSERR ==
1569 (tolerant = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg,
1570 sh->service_name,
1571 "TOLERANT")))
1572 { 1570 {
1573 LOG (GNUNET_ERROR_TYPE_ERROR, 1571 if (GNUNET_SYSERR ==
1574 _ ("Specified value for `%s' of service `%s' is invalid\n"), 1572 (tolerant = GNUNET_CONFIGURATION_get_value_yesno(sh->cfg,
1575 "TOLERANT", 1573 sh->service_name,
1576 sh->service_name); 1574 "TOLERANT")))
1577 return GNUNET_SYSERR; 1575 {
1576 LOG(GNUNET_ERROR_TYPE_ERROR,
1577 _("Specified value for `%s' of service `%s' is invalid\n"),
1578 "TOLERANT",
1579 sh->service_name);
1580 return GNUNET_SYSERR;
1581 }
1578 } 1582 }
1579 }
1580 else 1583 else
1581 tolerant = GNUNET_NO; 1584 tolerant = GNUNET_NO;
1582 1585
1583 lsocks = NULL; 1586 lsocks = NULL;
1584#ifndef MINGW 1587#ifndef MINGW
1585 errno = 0; 1588 errno = 0;
1586 if ((NULL != (nfds = getenv ("LISTEN_FDS"))) && 1589 if ((NULL != (nfds = getenv("LISTEN_FDS"))) &&
1587 (1 == sscanf (nfds, "%u%1s", &cnt, dummy)) && (cnt > 0) && 1590 (1 == sscanf(nfds, "%u%1s", &cnt, dummy)) && (cnt > 0) &&
1588 (cnt < FD_SETSIZE) && (cnt + 4 < FD_SETSIZE)) 1591 (cnt < FD_SETSIZE) && (cnt + 4 < FD_SETSIZE))
1589 {
1590 lsocks = GNUNET_new_array (cnt + 1, struct GNUNET_NETWORK_Handle *);
1591 while (0 < cnt--)
1592 { 1592 {
1593 flags = fcntl (3 + cnt, F_GETFD); 1593 lsocks = GNUNET_new_array(cnt + 1, struct GNUNET_NETWORK_Handle *);
1594 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) || 1594 while (0 < cnt--)
1595 (NULL == (lsocks[cnt] = GNUNET_NETWORK_socket_box_native (3 + cnt)))) 1595 {
1596 { 1596 flags = fcntl(3 + cnt, F_GETFD);
1597 LOG (GNUNET_ERROR_TYPE_ERROR, 1597 if ((flags < 0) || (0 != (flags & FD_CLOEXEC)) ||
1598 _ ( 1598 (NULL == (lsocks[cnt] = GNUNET_NETWORK_socket_box_native(3 + cnt))))
1599 "Could not access pre-bound socket %u, will try to bind myself\n"), 1599 {
1600 (unsigned int) 3 + cnt); 1600 LOG(GNUNET_ERROR_TYPE_ERROR,
1601 cnt++; 1601 _(
1602 while (NULL != lsocks[cnt]) 1602 "Could not access pre-bound socket %u, will try to bind myself\n"),
1603 GNUNET_break (GNUNET_OK == 1603 (unsigned int)3 + cnt);
1604 GNUNET_NETWORK_socket_close (lsocks[cnt++])); 1604 cnt++;
1605 GNUNET_free (lsocks); 1605 while (NULL != lsocks[cnt])
1606 lsocks = NULL; 1606 GNUNET_break(GNUNET_OK ==
1607 break; 1607 GNUNET_NETWORK_socket_close(lsocks[cnt++]));
1608 } 1608 GNUNET_free(lsocks);
1609 lsocks = NULL;
1610 break;
1611 }
1612 }
1613 unsetenv("LISTEN_FDS");
1609 } 1614 }
1610 unsetenv ("LISTEN_FDS");
1611 }
1612#else 1615#else
1613 if (NULL != getenv ("GNUNET_OS_READ_LSOCKS")) 1616 if (NULL != getenv("GNUNET_OS_READ_LSOCKS"))
1614 { 1617 {
1615 lsocks = receive_sockets_from_parent (sh); 1618 lsocks = receive_sockets_from_parent(sh);
1616 putenv ("GNUNET_OS_READ_LSOCKS="); 1619 putenv("GNUNET_OS_READ_LSOCKS=");
1617 } 1620 }
1618#endif 1621#endif
1619 1622
1620 if (NULL != lsocks) 1623 if (NULL != lsocks)
1621 {
1622 /* listen only on inherited sockets if we have any */
1623 struct GNUNET_NETWORK_Handle **ls;
1624
1625 for (ls = lsocks; NULL != *ls; ls++)
1626 { 1624 {
1627 struct ServiceListenContext *slc; 1625 /* listen only on inherited sockets if we have any */
1628 1626 struct GNUNET_NETWORK_Handle **ls;
1629 slc = GNUNET_new (struct ServiceListenContext); 1627
1630 slc->sh = sh; 1628 for (ls = lsocks; NULL != *ls; ls++)
1631 slc->listen_socket = *ls; 1629 {
1632 GNUNET_CONTAINER_DLL_insert (sh->slc_head, sh->slc_tail, slc); 1630 struct ServiceListenContext *slc;
1631
1632 slc = GNUNET_new(struct ServiceListenContext);
1633 slc->sh = sh;
1634 slc->listen_socket = *ls;
1635 GNUNET_CONTAINER_DLL_insert(sh->slc_head, sh->slc_tail, slc);
1636 }
1637 GNUNET_free(lsocks);
1633 } 1638 }
1634 GNUNET_free (lsocks);
1635 }
1636 else 1639 else
1637 {
1638 struct sockaddr **addrs;
1639 socklen_t *addrlens;
1640 int num;
1641
1642 num = get_server_addresses (sh->service_name, sh->cfg, &addrs, &addrlens);
1643 if (GNUNET_SYSERR == num)
1644 return GNUNET_SYSERR;
1645
1646 for (int i = 0; i < num; i++)
1647 { 1640 {
1648 struct ServiceListenContext *slc; 1641 struct sockaddr **addrs;
1642 socklen_t *addrlens;
1643 int num;
1649 1644
1650 slc = GNUNET_new (struct ServiceListenContext); 1645 num = get_server_addresses(sh->service_name, sh->cfg, &addrs, &addrlens);
1651 slc->sh = sh; 1646 if (GNUNET_SYSERR == num)
1652 slc->listen_socket = open_listen_socket (addrs[i], addrlens[i]); 1647 return GNUNET_SYSERR;
1653 GNUNET_free (addrs[i]); 1648
1654 if (NULL == slc->listen_socket) 1649 for (int i = 0; i < num; i++)
1655 { 1650 {
1656 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, "bind"); 1651 struct ServiceListenContext *slc;
1657 GNUNET_free (slc); 1652
1658 continue; 1653 slc = GNUNET_new(struct ServiceListenContext);
1659 } 1654 slc->sh = sh;
1660 GNUNET_CONTAINER_DLL_insert (sh->slc_head, sh->slc_tail, slc); 1655 slc->listen_socket = open_listen_socket(addrs[i], addrlens[i]);
1661 } 1656 GNUNET_free(addrs[i]);
1662 GNUNET_free_non_null (addrlens); 1657 if (NULL == slc->listen_socket)
1663 GNUNET_free_non_null (addrs); 1658 {
1664 if ((0 != num) && (NULL == sh->slc_head)) 1659 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR, "bind");
1665 { 1660 GNUNET_free(slc);
1666 /* All attempts to bind failed, hard failure */ 1661 continue;
1667 GNUNET_log ( 1662 }
1668 GNUNET_ERROR_TYPE_ERROR, 1663 GNUNET_CONTAINER_DLL_insert(sh->slc_head, sh->slc_tail, slc);
1669 _ ( 1664 }
1670 "Could not bind to any of the ports I was supposed to, refusing to run!\n")); 1665 GNUNET_free_non_null(addrlens);
1671 return GNUNET_SYSERR; 1666 GNUNET_free_non_null(addrs);
1667 if ((0 != num) && (NULL == sh->slc_head))
1668 {
1669 /* All attempts to bind failed, hard failure */
1670 GNUNET_log(
1671 GNUNET_ERROR_TYPE_ERROR,
1672 _(
1673 "Could not bind to any of the ports I was supposed to, refusing to run!\n"));
1674 return GNUNET_SYSERR;
1675 }
1672 } 1676 }
1673 }
1674 1677
1675 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES; 1678 sh->require_found = tolerant ? GNUNET_NO : GNUNET_YES;
1676 sh->match_uid = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg, 1679 sh->match_uid = GNUNET_CONFIGURATION_get_value_yesno(sh->cfg,
1677 sh->service_name, 1680 sh->service_name,
1678 "UNIX_MATCH_UID"); 1681 "UNIX_MATCH_UID");
1679 sh->match_gid = GNUNET_CONFIGURATION_get_value_yesno (sh->cfg, 1682 sh->match_gid = GNUNET_CONFIGURATION_get_value_yesno(sh->cfg,
1680 sh->service_name, 1683 sh->service_name,
1681 "UNIX_MATCH_GID"); 1684 "UNIX_MATCH_GID");
1682 process_acl4 (&sh->v4_denied, sh, "REJECT_FROM"); 1685 process_acl4(&sh->v4_denied, sh, "REJECT_FROM");
1683 process_acl4 (&sh->v4_allowed, sh, "ACCEPT_FROM"); 1686 process_acl4(&sh->v4_allowed, sh, "ACCEPT_FROM");
1684 process_acl6 (&sh->v6_denied, sh, "REJECT_FROM6"); 1687 process_acl6(&sh->v6_denied, sh, "REJECT_FROM6");
1685 process_acl6 (&sh->v6_allowed, sh, "ACCEPT_FROM6"); 1688 process_acl6(&sh->v6_allowed, sh, "ACCEPT_FROM6");
1686 return GNUNET_OK; 1689 return GNUNET_OK;
1687} 1690}
1688 1691
@@ -1695,14 +1698,14 @@ setup_service (struct GNUNET_SERVICE_Handle *sh)
1695 * @return value of the 'USERNAME' option 1698 * @return value of the 'USERNAME' option
1696 */ 1699 */
1697static char * 1700static char *
1698get_user_name (struct GNUNET_SERVICE_Handle *sh) 1701get_user_name(struct GNUNET_SERVICE_Handle *sh)
1699{ 1702{
1700 char *un; 1703 char *un;
1701 1704
1702 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (sh->cfg, 1705 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(sh->cfg,
1703 sh->service_name, 1706 sh->service_name,
1704 "USERNAME", 1707 "USERNAME",
1705 &un)) 1708 &un))
1706 return NULL; 1709 return NULL;
1707 return un; 1710 return un;
1708} 1711}
@@ -1715,45 +1718,45 @@ get_user_name (struct GNUNET_SERVICE_Handle *sh)
1715 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1718 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1716 */ 1719 */
1717static int 1720static int
1718set_user_id (struct GNUNET_SERVICE_Handle *sh) 1721set_user_id(struct GNUNET_SERVICE_Handle *sh)
1719{ 1722{
1720 char *user; 1723 char *user;
1721 1724
1722 if (NULL == (user = get_user_name (sh))) 1725 if (NULL == (user = get_user_name(sh)))
1723 return GNUNET_OK; /* keep */ 1726 return GNUNET_OK; /* keep */
1724#ifndef MINGW 1727#ifndef MINGW
1725 struct passwd *pws; 1728 struct passwd *pws;
1726 1729
1727 errno = 0; 1730 errno = 0;
1728 pws = getpwnam (user); 1731 pws = getpwnam(user);
1729 if (NULL == pws) 1732 if (NULL == pws)
1730 { 1733 {
1731 LOG (GNUNET_ERROR_TYPE_ERROR, 1734 LOG(GNUNET_ERROR_TYPE_ERROR,
1732 _ ("Cannot obtain information about user `%s': %s\n"), 1735 _("Cannot obtain information about user `%s': %s\n"),
1733 user, 1736 user,
1734 errno == 0 ? _ ("No such user") : strerror (errno)); 1737 errno == 0 ? _("No such user") : strerror(errno));
1735 GNUNET_free (user); 1738 GNUNET_free(user);
1736 return GNUNET_SYSERR; 1739 return GNUNET_SYSERR;
1737 } 1740 }
1738 if ((0 != setgid (pws->pw_gid)) || (0 != setegid (pws->pw_gid)) || 1741 if ((0 != setgid(pws->pw_gid)) || (0 != setegid(pws->pw_gid)) ||
1739#if HAVE_INITGROUPS 1742#if HAVE_INITGROUPS
1740 (0 != initgroups (user, pws->pw_gid)) || 1743 (0 != initgroups(user, pws->pw_gid)) ||
1741#endif 1744#endif
1742 (0 != setuid (pws->pw_uid)) || (0 != seteuid (pws->pw_uid))) 1745 (0 != setuid(pws->pw_uid)) || (0 != seteuid(pws->pw_uid)))
1743 {
1744 if ((0 != setregid (pws->pw_gid, pws->pw_gid)) ||
1745 (0 != setreuid (pws->pw_uid, pws->pw_uid)))
1746 { 1746 {
1747 LOG (GNUNET_ERROR_TYPE_ERROR, 1747 if ((0 != setregid(pws->pw_gid, pws->pw_gid)) ||
1748 _ ("Cannot change user/group to `%s': %s\n"), 1748 (0 != setreuid(pws->pw_uid, pws->pw_uid)))
1749 user, 1749 {
1750 strerror (errno)); 1750 LOG(GNUNET_ERROR_TYPE_ERROR,
1751 GNUNET_free (user); 1751 _("Cannot change user/group to `%s': %s\n"),
1752 return GNUNET_SYSERR; 1752 user,
1753 strerror(errno));
1754 GNUNET_free(user);
1755 return GNUNET_SYSERR;
1756 }
1753 } 1757 }
1754 }
1755#endif 1758#endif
1756 GNUNET_free (user); 1759 GNUNET_free(user);
1757 return GNUNET_OK; 1760 return GNUNET_OK;
1758} 1761}
1759 1762
@@ -1766,14 +1769,14 @@ set_user_id (struct GNUNET_SERVICE_Handle *sh)
1766 * @return name of the file for the process ID 1769 * @return name of the file for the process ID
1767 */ 1770 */
1768static char * 1771static char *
1769get_pid_file_name (struct GNUNET_SERVICE_Handle *sh) 1772get_pid_file_name(struct GNUNET_SERVICE_Handle *sh)
1770{ 1773{
1771 char *pif; 1774 char *pif;
1772 1775
1773 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename (sh->cfg, 1776 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_filename(sh->cfg,
1774 sh->service_name, 1777 sh->service_name,
1775 "PIDFILE", 1778 "PIDFILE",
1776 &pif)) 1779 &pif))
1777 return NULL; 1780 return NULL;
1778 return pif; 1781 return pif;
1779} 1782}
@@ -1785,15 +1788,15 @@ get_pid_file_name (struct GNUNET_SERVICE_Handle *sh)
1785 * @param sh service context 1788 * @param sh service context
1786 */ 1789 */
1787static void 1790static void
1788pid_file_delete (struct GNUNET_SERVICE_Handle *sh) 1791pid_file_delete(struct GNUNET_SERVICE_Handle *sh)
1789{ 1792{
1790 char *pif = get_pid_file_name (sh); 1793 char *pif = get_pid_file_name(sh);
1791 1794
1792 if (NULL == pif) 1795 if (NULL == pif)
1793 return; /* no PID file */ 1796 return; /* no PID file */
1794 if (0 != unlink (pif)) 1797 if (0 != unlink(pif))
1795 LOG_STRERROR_FILE (GNUNET_ERROR_TYPE_WARNING, "unlink", pif); 1798 LOG_STRERROR_FILE(GNUNET_ERROR_TYPE_WARNING, "unlink", pif);
1796 GNUNET_free (pif); 1799 GNUNET_free(pif);
1797} 1800}
1798 1801
1799 1802
@@ -1804,76 +1807,79 @@ pid_file_delete (struct GNUNET_SERVICE_Handle *sh)
1804 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 1807 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
1805 */ 1808 */
1806static int 1809static int
1807detach_terminal (struct GNUNET_SERVICE_Handle *sh) 1810detach_terminal(struct GNUNET_SERVICE_Handle *sh)
1808{ 1811{
1809#ifndef MINGW 1812#ifndef MINGW
1810 pid_t pid; 1813 pid_t pid;
1811 int nullfd; 1814 int nullfd;
1812 int filedes[2]; 1815 int filedes[2];
1813 1816
1814 if (0 != pipe (filedes)) 1817 if (0 != pipe(filedes))
1815 { 1818 {
1816 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "pipe"); 1819 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "pipe");
1817 return GNUNET_SYSERR; 1820 return GNUNET_SYSERR;
1818 } 1821 }
1819 pid = fork (); 1822 pid = fork();
1820 if (pid < 0) 1823 if (pid < 0)
1821 { 1824 {
1822 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "fork"); 1825 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "fork");
1823 return GNUNET_SYSERR; 1826 return GNUNET_SYSERR;
1824 } 1827 }
1825 if (0 != pid) 1828 if (0 != pid)
1826 {
1827 /* Parent */
1828 char c;
1829
1830 GNUNET_break (0 == close (filedes[1]));
1831 c = 'X';
1832 if (1 != read (filedes[0], &c, sizeof (char)))
1833 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "read");
1834 fflush (stdout);
1835 switch (c)
1836 { 1829 {
1837 case '.': 1830 /* Parent */
1838 exit (0); 1831 char c;
1839 case 'I': 1832
1840 LOG (GNUNET_ERROR_TYPE_INFO, 1833 GNUNET_break(0 == close(filedes[1]));
1841 _ ("Service process failed to initialize\n")); 1834 c = 'X';
1842 break; 1835 if (1 != read(filedes[0], &c, sizeof(char)))
1843 case 'S': 1836 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "read");
1844 LOG (GNUNET_ERROR_TYPE_INFO, 1837 fflush(stdout);
1845 _ ("Service process could not initialize server function\n")); 1838 switch (c)
1846 break; 1839 {
1847 case 'X': 1840 case '.':
1848 LOG (GNUNET_ERROR_TYPE_INFO, 1841 exit(0);
1849 _ ("Service process failed to report status\n")); 1842
1850 break; 1843 case 'I':
1844 LOG(GNUNET_ERROR_TYPE_INFO,
1845 _("Service process failed to initialize\n"));
1846 break;
1847
1848 case 'S':
1849 LOG(GNUNET_ERROR_TYPE_INFO,
1850 _("Service process could not initialize server function\n"));
1851 break;
1852
1853 case 'X':
1854 LOG(GNUNET_ERROR_TYPE_INFO,
1855 _("Service process failed to report status\n"));
1856 break;
1857 }
1858 exit(1); /* child reported error */
1851 } 1859 }
1852 exit (1); /* child reported error */ 1860 GNUNET_break(0 == close(0));
1853 } 1861 GNUNET_break(0 == close(1));
1854 GNUNET_break (0 == close (0)); 1862 GNUNET_break(0 == close(filedes[0]));
1855 GNUNET_break (0 == close (1)); 1863 nullfd = open("/dev/null", O_RDWR | O_APPEND);
1856 GNUNET_break (0 == close (filedes[0]));
1857 nullfd = open ("/dev/null", O_RDWR | O_APPEND);
1858 if (nullfd < 0) 1864 if (nullfd < 0)
1859 return GNUNET_SYSERR; 1865 return GNUNET_SYSERR;
1860 /* set stdin/stdout to /dev/null */ 1866 /* set stdin/stdout to /dev/null */
1861 if ((dup2 (nullfd, 0) < 0) || (dup2 (nullfd, 1) < 0)) 1867 if ((dup2(nullfd, 0) < 0) || (dup2(nullfd, 1) < 0))
1862 { 1868 {
1863 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "dup2"); 1869 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "dup2");
1864 (void) close (nullfd); 1870 (void)close(nullfd);
1865 return GNUNET_SYSERR; 1871 return GNUNET_SYSERR;
1866 } 1872 }
1867 (void) close (nullfd); 1873 (void)close(nullfd);
1868 /* Detach from controlling terminal */ 1874 /* Detach from controlling terminal */
1869 pid = setsid (); 1875 pid = setsid();
1870 if (-1 == pid) 1876 if (-1 == pid)
1871 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "setsid"); 1877 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "setsid");
1872 sh->ready_confirm_fd = filedes[1]; 1878 sh->ready_confirm_fd = filedes[1];
1873#else 1879#else
1874 /* FIXME: we probably need to do something else 1880 /* FIXME: we probably need to do something else
1875 * elsewhere in order to fork the process itself... */ 1881 * elsewhere in order to fork the process itself... */
1876 FreeConsole (); 1882 FreeConsole();
1877#endif 1883#endif
1878 return GNUNET_OK; 1884 return GNUNET_OK;
1879} 1885}
@@ -1886,23 +1892,23 @@ detach_terminal (struct GNUNET_SERVICE_Handle *sh)
1886 * @param sh handle to the service to tear down. 1892 * @param sh handle to the service to tear down.
1887 */ 1893 */
1888static void 1894static void
1889teardown_service (struct GNUNET_SERVICE_Handle *sh) 1895teardown_service(struct GNUNET_SERVICE_Handle *sh)
1890{ 1896{
1891 struct ServiceListenContext *slc; 1897 struct ServiceListenContext *slc;
1892 1898
1893 GNUNET_free_non_null (sh->v4_denied); 1899 GNUNET_free_non_null(sh->v4_denied);
1894 GNUNET_free_non_null (sh->v6_denied); 1900 GNUNET_free_non_null(sh->v6_denied);
1895 GNUNET_free_non_null (sh->v4_allowed); 1901 GNUNET_free_non_null(sh->v4_allowed);
1896 GNUNET_free_non_null (sh->v6_allowed); 1902 GNUNET_free_non_null(sh->v6_allowed);
1897 while (NULL != (slc = sh->slc_head)) 1903 while (NULL != (slc = sh->slc_head))
1898 { 1904 {
1899 GNUNET_CONTAINER_DLL_remove (sh->slc_head, sh->slc_tail, slc); 1905 GNUNET_CONTAINER_DLL_remove(sh->slc_head, sh->slc_tail, slc);
1900 if (NULL != slc->listen_task) 1906 if (NULL != slc->listen_task)
1901 GNUNET_SCHEDULER_cancel (slc->listen_task); 1907 GNUNET_SCHEDULER_cancel(slc->listen_task);
1902 GNUNET_break (GNUNET_OK == 1908 GNUNET_break(GNUNET_OK ==
1903 GNUNET_NETWORK_socket_close (slc->listen_socket)); 1909 GNUNET_NETWORK_socket_close(slc->listen_socket));
1904 GNUNET_free (slc); 1910 GNUNET_free(slc);
1905 } 1911 }
1906} 1912}
1907 1913
1908 1914
@@ -1913,7 +1919,7 @@ teardown_service (struct GNUNET_SERVICE_Handle *sh)
1913 * @param msg AGPL request 1919 * @param msg AGPL request
1914 */ 1920 */
1915static void 1921static void
1916return_agpl (void *cls, const struct GNUNET_MessageHeader *msg) 1922return_agpl(void *cls, const struct GNUNET_MessageHeader *msg)
1917{ 1923{
1918 struct GNUNET_SERVICE_Client *client = cls; 1924 struct GNUNET_SERVICE_Client *client = cls;
1919 struct GNUNET_MQ_Handle *mq; 1925 struct GNUNET_MQ_Handle *mq;
@@ -1921,13 +1927,13 @@ return_agpl (void *cls, const struct GNUNET_MessageHeader *msg)
1921 struct GNUNET_MessageHeader *res; 1927 struct GNUNET_MessageHeader *res;
1922 size_t slen; 1928 size_t slen;
1923 1929
1924 (void) msg; 1930 (void)msg;
1925 slen = strlen (GNUNET_AGPL_URL) + 1; 1931 slen = strlen(GNUNET_AGPL_URL) + 1;
1926 env = GNUNET_MQ_msg_extra (res, GNUNET_MESSAGE_TYPE_RESPONSE_AGPL, slen); 1932 env = GNUNET_MQ_msg_extra(res, GNUNET_MESSAGE_TYPE_RESPONSE_AGPL, slen);
1927 memcpy (&res[1], GNUNET_AGPL_URL, slen); 1933 memcpy(&res[1], GNUNET_AGPL_URL, slen);
1928 mq = GNUNET_SERVICE_client_get_mq (client); 1934 mq = GNUNET_SERVICE_client_get_mq(client);
1929 GNUNET_MQ_send (mq, env); 1935 GNUNET_MQ_send(mq, env);
1930 GNUNET_SERVICE_client_continue (client); 1936 GNUNET_SERVICE_client_continue(client);
1931} 1937}
1932 1938
1933 1939
@@ -1968,29 +1974,29 @@ return_agpl (void *cls, const struct GNUNET_MessageHeader *msg)
1968 * @return NULL on error 1974 * @return NULL on error
1969 */ 1975 */
1970struct GNUNET_SERVICE_Handle * 1976struct GNUNET_SERVICE_Handle *
1971GNUNET_SERVICE_start (const char *service_name, 1977GNUNET_SERVICE_start(const char *service_name,
1972 const struct GNUNET_CONFIGURATION_Handle *cfg, 1978 const struct GNUNET_CONFIGURATION_Handle *cfg,
1973 GNUNET_SERVICE_ConnectHandler connect_cb, 1979 GNUNET_SERVICE_ConnectHandler connect_cb,
1974 GNUNET_SERVICE_DisconnectHandler disconnect_cb, 1980 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
1975 void *cls, 1981 void *cls,
1976 const struct GNUNET_MQ_MessageHandler *handlers) 1982 const struct GNUNET_MQ_MessageHandler *handlers)
1977{ 1983{
1978 struct GNUNET_SERVICE_Handle *sh; 1984 struct GNUNET_SERVICE_Handle *sh;
1979 1985
1980 sh = GNUNET_new (struct GNUNET_SERVICE_Handle); 1986 sh = GNUNET_new(struct GNUNET_SERVICE_Handle);
1981 sh->service_name = service_name; 1987 sh->service_name = service_name;
1982 sh->cfg = cfg; 1988 sh->cfg = cfg;
1983 sh->connect_cb = connect_cb; 1989 sh->connect_cb = connect_cb;
1984 sh->disconnect_cb = disconnect_cb; 1990 sh->disconnect_cb = disconnect_cb;
1985 sh->cb_cls = cls; 1991 sh->cb_cls = cls;
1986 sh->handlers = GNUNET_MQ_copy_handlers2 (handlers, &return_agpl, NULL); 1992 sh->handlers = GNUNET_MQ_copy_handlers2(handlers, &return_agpl, NULL);
1987 if (GNUNET_OK != setup_service (sh)) 1993 if (GNUNET_OK != setup_service(sh))
1988 { 1994 {
1989 GNUNET_free_non_null (sh->handlers); 1995 GNUNET_free_non_null(sh->handlers);
1990 GNUNET_free (sh); 1996 GNUNET_free(sh);
1991 return NULL; 1997 return NULL;
1992 } 1998 }
1993 do_resume (sh, SUSPEND_STATE_NONE); 1999 do_resume(sh, SUSPEND_STATE_NONE);
1994 return sh; 2000 return sh;
1995} 2001}
1996 2002
@@ -2001,16 +2007,16 @@ GNUNET_SERVICE_start (const char *service_name,
2001 * @param srv service to stop 2007 * @param srv service to stop
2002 */ 2008 */
2003void 2009void
2004GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv) 2010GNUNET_SERVICE_stop(struct GNUNET_SERVICE_Handle *srv)
2005{ 2011{
2006 struct GNUNET_SERVICE_Client *client; 2012 struct GNUNET_SERVICE_Client *client;
2007 2013
2008 GNUNET_SERVICE_suspend (srv); 2014 GNUNET_SERVICE_suspend(srv);
2009 while (NULL != (client = srv->clients_head)) 2015 while (NULL != (client = srv->clients_head))
2010 GNUNET_SERVICE_client_drop (client); 2016 GNUNET_SERVICE_client_drop(client);
2011 teardown_service (srv); 2017 teardown_service(srv);
2012 GNUNET_free_non_null (srv->handlers); 2018 GNUNET_free_non_null(srv->handlers);
2013 GNUNET_free (srv); 2019 GNUNET_free(srv);
2014} 2020}
2015 2021
2016 2022
@@ -2056,17 +2062,18 @@ GNUNET_SERVICE_stop (struct GNUNET_SERVICE_Handle *srv)
2056 * @return 0 on success, non-zero on error 2062 * @return 0 on success, non-zero on error
2057 */ 2063 */
2058int 2064int
2059GNUNET_SERVICE_run_ (int argc, 2065GNUNET_SERVICE_run_(int argc,
2060 char *const *argv, 2066 char *const *argv,
2061 const char *service_name, 2067 const char *service_name,
2062 enum GNUNET_SERVICE_Options options, 2068 enum GNUNET_SERVICE_Options options,
2063 GNUNET_SERVICE_InitCallback service_init_cb, 2069 GNUNET_SERVICE_InitCallback service_init_cb,
2064 GNUNET_SERVICE_ConnectHandler connect_cb, 2070 GNUNET_SERVICE_ConnectHandler connect_cb,
2065 GNUNET_SERVICE_DisconnectHandler disconnect_cb, 2071 GNUNET_SERVICE_DisconnectHandler disconnect_cb,
2066 void *cls, 2072 void *cls,
2067 const struct GNUNET_MQ_MessageHandler *handlers) 2073 const struct GNUNET_MQ_MessageHandler *handlers)
2068{ 2074{
2069 struct GNUNET_SERVICE_Handle sh; 2075 struct GNUNET_SERVICE_Handle sh;
2076
2070#if ENABLE_NLS 2077#if ENABLE_NLS
2071 char *path; 2078 char *path;
2072#endif 2079#endif
@@ -2082,40 +2089,40 @@ GNUNET_SERVICE_run_ (int argc,
2082 struct GNUNET_CONFIGURATION_Handle *cfg; 2089 struct GNUNET_CONFIGURATION_Handle *cfg;
2083 int ret; 2090 int ret;
2084 int err; 2091 int err;
2085 const struct GNUNET_OS_ProjectData *pd = GNUNET_OS_project_data_get (); 2092 const struct GNUNET_OS_ProjectData *pd = GNUNET_OS_project_data_get();
2086 2093
2087 struct GNUNET_GETOPT_CommandLineOption service_options[] = 2094 struct GNUNET_GETOPT_CommandLineOption service_options[] =
2088 {GNUNET_GETOPT_option_cfgfile (&opt_cfg_filename), 2095 { GNUNET_GETOPT_option_cfgfile(&opt_cfg_filename),
2089 GNUNET_GETOPT_option_flag ('d', 2096 GNUNET_GETOPT_option_flag('d',
2090 "daemonize", 2097 "daemonize",
2091 gettext_noop ( 2098 gettext_noop(
2092 "do daemonize (detach from terminal)"), 2099 "do daemonize (detach from terminal)"),
2093 &do_daemonize), 2100 &do_daemonize),
2094 GNUNET_GETOPT_option_help (NULL), 2101 GNUNET_GETOPT_option_help(NULL),
2095 GNUNET_GETOPT_option_loglevel (&loglev), 2102 GNUNET_GETOPT_option_loglevel(&loglev),
2096 GNUNET_GETOPT_option_logfile (&logfile), 2103 GNUNET_GETOPT_option_logfile(&logfile),
2097 GNUNET_GETOPT_option_version (pd->version), 2104 GNUNET_GETOPT_option_version(pd->version),
2098 GNUNET_GETOPT_OPTION_END}; 2105 GNUNET_GETOPT_OPTION_END };
2099 2106
2100 err = 1; 2107 err = 1;
2101 memset (&sh, 0, sizeof (sh)); 2108 memset(&sh, 0, sizeof(sh));
2102 xdg = getenv ("XDG_CONFIG_HOME"); 2109 xdg = getenv("XDG_CONFIG_HOME");
2103 if (NULL != xdg) 2110 if (NULL != xdg)
2104 GNUNET_asprintf (&cfg_filename, 2111 GNUNET_asprintf(&cfg_filename,
2105 "%s%s%s", 2112 "%s%s%s",
2106 xdg, 2113 xdg,
2107 DIR_SEPARATOR_STR, 2114 DIR_SEPARATOR_STR,
2108 pd->config_file); 2115 pd->config_file);
2109 else 2116 else
2110 cfg_filename = GNUNET_strdup (pd->user_config_file); 2117 cfg_filename = GNUNET_strdup(pd->user_config_file);
2111 sh.ready_confirm_fd = -1; 2118 sh.ready_confirm_fd = -1;
2112 sh.options = options; 2119 sh.options = options;
2113 sh.cfg = cfg = GNUNET_CONFIGURATION_create (); 2120 sh.cfg = cfg = GNUNET_CONFIGURATION_create();
2114 sh.service_init_cb = service_init_cb; 2121 sh.service_init_cb = service_init_cb;
2115 sh.connect_cb = connect_cb; 2122 sh.connect_cb = connect_cb;
2116 sh.disconnect_cb = disconnect_cb; 2123 sh.disconnect_cb = disconnect_cb;
2117 sh.cb_cls = cls; 2124 sh.cb_cls = cls;
2118 sh.handlers = GNUNET_MQ_copy_handlers (handlers); 2125 sh.handlers = GNUNET_MQ_copy_handlers(handlers);
2119 sh.service_name = service_name; 2126 sh.service_name = service_name;
2120 sh.ret = 0; 2127 sh.ret = 0;
2121 /* setup subsystems */ 2128 /* setup subsystems */
@@ -2125,135 +2132,135 @@ GNUNET_SERVICE_run_ (int argc,
2125 do_daemonize = 0; 2132 do_daemonize = 0;
2126#if ENABLE_NLS 2133#if ENABLE_NLS
2127 if (NULL != pd->gettext_domain) 2134 if (NULL != pd->gettext_domain)
2128 {
2129 setlocale (LC_ALL, "");
2130 path = (NULL == pd->gettext_path) ?
2131 GNUNET_OS_installation_get_path (GNUNET_OS_IPK_LOCALEDIR) :
2132 GNUNET_strdup (pd->gettext_path);
2133 if (NULL != path)
2134 { 2135 {
2135 bindtextdomain (pd->gettext_domain, path); 2136 setlocale(LC_ALL, "");
2136 GNUNET_free (path); 2137 path = (NULL == pd->gettext_path) ?
2138 GNUNET_OS_installation_get_path(GNUNET_OS_IPK_LOCALEDIR) :
2139 GNUNET_strdup(pd->gettext_path);
2140 if (NULL != path)
2141 {
2142 bindtextdomain(pd->gettext_domain, path);
2143 GNUNET_free(path);
2144 }
2145 textdomain(pd->gettext_domain);
2137 } 2146 }
2138 textdomain (pd->gettext_domain);
2139 }
2140#endif 2147#endif
2141 ret = GNUNET_GETOPT_run (service_name, service_options, argc, argv); 2148 ret = GNUNET_GETOPT_run(service_name, service_options, argc, argv);
2142 if (GNUNET_SYSERR == ret) 2149 if (GNUNET_SYSERR == ret)
2143 goto shutdown; 2150 goto shutdown;
2144 if (GNUNET_NO == ret) 2151 if (GNUNET_NO == ret)
2145 {
2146 err = 0;
2147 goto shutdown;
2148 }
2149 if (GNUNET_OK != GNUNET_log_setup (service_name, loglev, logfile))
2150 {
2151 GNUNET_break (0);
2152 goto shutdown;
2153 }
2154 if (NULL != opt_cfg_filename)
2155 {
2156 if ((GNUNET_YES != GNUNET_DISK_file_test (opt_cfg_filename)) ||
2157 (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, opt_cfg_filename)))
2158 { 2152 {
2159 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 2153 err = 0;
2160 _ ("Malformed configuration file `%s', exit ...\n"),
2161 opt_cfg_filename);
2162 goto shutdown; 2154 goto shutdown;
2163 } 2155 }
2164 } 2156 if (GNUNET_OK != GNUNET_log_setup(service_name, loglev, logfile))
2165 else
2166 {
2167 if (GNUNET_YES == GNUNET_DISK_file_test (cfg_filename))
2168 { 2157 {
2169 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, cfg_filename)) 2158 GNUNET_break(0);
2170 { 2159 goto shutdown;
2171 GNUNET_log (GNUNET_ERROR_TYPE_ERROR,
2172 _ ("Malformed configuration file `%s', exit ...\n"),
2173 cfg_filename);
2174 goto shutdown;
2175 }
2176 } 2160 }
2177 else 2161 if (NULL != opt_cfg_filename)
2178 { 2162 {
2179 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load (cfg, NULL)) 2163 if ((GNUNET_YES != GNUNET_DISK_file_test(opt_cfg_filename)) ||
2180 { 2164 (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, opt_cfg_filename)))
2181 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 2165 {
2182 _ ("Malformed configuration, exit ...\n")); 2166 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2183 goto shutdown; 2167 _("Malformed configuration file `%s', exit ...\n"),
2184 } 2168 opt_cfg_filename);
2169 goto shutdown;
2170 }
2185 } 2171 }
2186 } 2172 else
2187 if (GNUNET_OK != setup_service (&sh)) 2173 {
2188 goto shutdown; 2174 if (GNUNET_YES == GNUNET_DISK_file_test(cfg_filename))
2189 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal (&sh))) 2175 {
2190 { 2176 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, cfg_filename))
2191 GNUNET_break (0); 2177 {
2178 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2179 _("Malformed configuration file `%s', exit ...\n"),
2180 cfg_filename);
2181 goto shutdown;
2182 }
2183 }
2184 else
2185 {
2186 if (GNUNET_SYSERR == GNUNET_CONFIGURATION_load(cfg, NULL))
2187 {
2188 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
2189 _("Malformed configuration, exit ...\n"));
2190 goto shutdown;
2191 }
2192 }
2193 }
2194 if (GNUNET_OK != setup_service(&sh))
2192 goto shutdown; 2195 goto shutdown;
2193 } 2196 if ((1 == do_daemonize) && (GNUNET_OK != detach_terminal(&sh)))
2194 if (GNUNET_OK != set_user_id (&sh)) 2197 {
2198 GNUNET_break(0);
2199 goto shutdown;
2200 }
2201 if (GNUNET_OK != set_user_id(&sh))
2195 goto shutdown; 2202 goto shutdown;
2196 LOG (GNUNET_ERROR_TYPE_DEBUG, 2203 LOG(GNUNET_ERROR_TYPE_DEBUG,
2197 "Service `%s' runs with configuration from `%s'\n", 2204 "Service `%s' runs with configuration from `%s'\n",
2198 service_name, 2205 service_name,
2199 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename); 2206 (NULL != opt_cfg_filename) ? opt_cfg_filename : cfg_filename);
2200 if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (sh.cfg, 2207 if ((GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(sh.cfg,
2201 "TESTING", 2208 "TESTING",
2202 "SKEW_OFFSET", 2209 "SKEW_OFFSET",
2203 &skew_offset)) && 2210 &skew_offset)) &&
2204 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number (sh.cfg, 2211 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_number(sh.cfg,
2205 "TESTING", 2212 "TESTING",
2206 "SKEW_VARIANCE", 2213 "SKEW_VARIANCE",
2207 &skew_variance))) 2214 &skew_variance)))
2208 { 2215 {
2209 clock_offset = skew_offset - skew_variance; 2216 clock_offset = skew_offset - skew_variance;
2210 GNUNET_TIME_set_offset (clock_offset); 2217 GNUNET_TIME_set_offset(clock_offset);
2211 LOG (GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset); 2218 LOG(GNUNET_ERROR_TYPE_DEBUG, "Skewing clock by %dll ms\n", clock_offset);
2212 } 2219 }
2213 GNUNET_RESOLVER_connect (sh.cfg); 2220 GNUNET_RESOLVER_connect(sh.cfg);
2214 2221
2215 /* actually run service */ 2222 /* actually run service */
2216 err = 0; 2223 err = 0;
2217 GNUNET_SCHEDULER_run (&service_main, &sh); 2224 GNUNET_SCHEDULER_run(&service_main, &sh);
2218 /* shutdown */ 2225 /* shutdown */
2219 if (1 == do_daemonize) 2226 if (1 == do_daemonize)
2220 pid_file_delete (&sh); 2227 pid_file_delete(&sh);
2221 2228
2222shutdown: 2229shutdown:
2223 if (-1 != sh.ready_confirm_fd) 2230 if (-1 != sh.ready_confirm_fd)
2224 { 2231 {
2225 if (1 != write (sh.ready_confirm_fd, err ? "I" : "S", 1)) 2232 if (1 != write(sh.ready_confirm_fd, err ? "I" : "S", 1))
2226 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "write"); 2233 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "write");
2227 GNUNET_break (0 == close (sh.ready_confirm_fd)); 2234 GNUNET_break(0 == close(sh.ready_confirm_fd));
2228 } 2235 }
2229#if HAVE_MALLINFO 2236#if HAVE_MALLINFO
2230 { 2237 {
2231 char *counter; 2238 char *counter;
2232 2239
2233 if ((GNUNET_YES == GNUNET_CONFIGURATION_have_value (sh.cfg, 2240 if ((GNUNET_YES == GNUNET_CONFIGURATION_have_value(sh.cfg,
2234 service_name, 2241 service_name,
2235 "GAUGER_HEAP")) && 2242 "GAUGER_HEAP")) &&
2236 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (sh.cfg, 2243 (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string(sh.cfg,
2237 service_name, 2244 service_name,
2238 "GAUGER_HEAP", 2245 "GAUGER_HEAP",
2239 &counter))) 2246 &counter)))
2240 { 2247 {
2241 struct mallinfo mi; 2248 struct mallinfo mi;
2242 2249
2243 mi = mallinfo (); 2250 mi = mallinfo();
2244 GAUGER (service_name, counter, mi.usmblks, "blocks"); 2251 GAUGER(service_name, counter, mi.usmblks, "blocks");
2245 GNUNET_free (counter); 2252 GNUNET_free(counter);
2246 } 2253 }
2247 } 2254 }
2248#endif 2255#endif
2249 teardown_service (&sh); 2256 teardown_service(&sh);
2250 GNUNET_free_non_null (sh.handlers); 2257 GNUNET_free_non_null(sh.handlers);
2251 GNUNET_SPEEDUP_stop_ (); 2258 GNUNET_SPEEDUP_stop_();
2252 GNUNET_CONFIGURATION_destroy (cfg); 2259 GNUNET_CONFIGURATION_destroy(cfg);
2253 GNUNET_free_non_null (logfile); 2260 GNUNET_free_non_null(logfile);
2254 GNUNET_free_non_null (loglev); 2261 GNUNET_free_non_null(loglev);
2255 GNUNET_free (cfg_filename); 2262 GNUNET_free(cfg_filename);
2256 GNUNET_free_non_null (opt_cfg_filename); 2263 GNUNET_free_non_null(opt_cfg_filename);
2257 2264
2258 return err ? GNUNET_SYSERR : sh.ret; 2265 return err ? GNUNET_SYSERR : sh.ret;
2259} 2266}
@@ -2266,9 +2273,9 @@ shutdown:
2266 * @param sh service to stop accepting connections. 2273 * @param sh service to stop accepting connections.
2267 */ 2274 */
2268void 2275void
2269GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh) 2276GNUNET_SERVICE_suspend(struct GNUNET_SERVICE_Handle *sh)
2270{ 2277{
2271 do_suspend (sh, SUSPEND_STATE_APP); 2278 do_suspend(sh, SUSPEND_STATE_APP);
2272} 2279}
2273 2280
2274 2281
@@ -2278,9 +2285,9 @@ GNUNET_SERVICE_suspend (struct GNUNET_SERVICE_Handle *sh)
2278 * @param sh service to resume accepting connections. 2285 * @param sh service to resume accepting connections.
2279 */ 2286 */
2280void 2287void
2281GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh) 2288GNUNET_SERVICE_resume(struct GNUNET_SERVICE_Handle *sh)
2282{ 2289{
2283 do_resume (sh, SUSPEND_STATE_APP); 2290 do_resume(sh, SUSPEND_STATE_APP);
2284} 2291}
2285 2292
2286 2293
@@ -2291,32 +2298,32 @@ GNUNET_SERVICE_resume (struct GNUNET_SERVICE_Handle *sh)
2291 * @param cls our `struct GNUNET_SERVICE_Client` 2298 * @param cls our `struct GNUNET_SERVICE_Client`
2292 */ 2299 */
2293static void 2300static void
2294resume_client_receive (void *cls) 2301resume_client_receive(void *cls)
2295{ 2302{
2296 struct GNUNET_SERVICE_Client *c = cls; 2303 struct GNUNET_SERVICE_Client *c = cls;
2297 int ret; 2304 int ret;
2298 2305
2299 c->recv_task = NULL; 2306 c->recv_task = NULL;
2300 /* first, check if there is still something in the buffer */ 2307 /* first, check if there is still something in the buffer */
2301 ret = GNUNET_MST_next (c->mst, GNUNET_YES); 2308 ret = GNUNET_MST_next(c->mst, GNUNET_YES);
2302 if (GNUNET_SYSERR == ret) 2309 if (GNUNET_SYSERR == ret)
2303 { 2310 {
2304 if (NULL == c->drop_task) 2311 if (NULL == c->drop_task)
2305 GNUNET_SERVICE_client_drop (c); 2312 GNUNET_SERVICE_client_drop(c);
2306 return; 2313 return;
2307 } 2314 }
2308 if (GNUNET_NO == ret) 2315 if (GNUNET_NO == ret)
2309 return; /* done processing, wait for more later */ 2316 return; /* done processing, wait for more later */
2310 GNUNET_assert (GNUNET_OK == ret); 2317 GNUNET_assert(GNUNET_OK == ret);
2311 if (GNUNET_YES == c->needs_continue) 2318 if (GNUNET_YES == c->needs_continue)
2312 return; /* #GNUNET_MST_next() did give a message to the client */ 2319 return; /* #GNUNET_MST_next() did give a message to the client */
2313 /* need to receive more data from the network first */ 2320 /* need to receive more data from the network first */
2314 if (NULL != c->recv_task) 2321 if (NULL != c->recv_task)
2315 return; 2322 return;
2316 c->recv_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, 2323 c->recv_task = GNUNET_SCHEDULER_add_read_net(GNUNET_TIME_UNIT_FOREVER_REL,
2317 c->sock, 2324 c->sock,
2318 &service_client_recv, 2325 &service_client_recv,
2319 c); 2326 c);
2320} 2327}
2321 2328
2322 2329
@@ -2327,18 +2334,18 @@ resume_client_receive (void *cls)
2327 * @param c the client to continue receiving from 2334 * @param c the client to continue receiving from
2328 */ 2335 */
2329void 2336void
2330GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c) 2337GNUNET_SERVICE_client_continue(struct GNUNET_SERVICE_Client *c)
2331{ 2338{
2332 GNUNET_assert (NULL == c->drop_task); 2339 GNUNET_assert(NULL == c->drop_task);
2333 GNUNET_assert (GNUNET_YES == c->needs_continue); 2340 GNUNET_assert(GNUNET_YES == c->needs_continue);
2334 GNUNET_assert (NULL == c->recv_task); 2341 GNUNET_assert(NULL == c->recv_task);
2335 c->needs_continue = GNUNET_NO; 2342 c->needs_continue = GNUNET_NO;
2336 if (NULL != c->warn_task) 2343 if (NULL != c->warn_task)
2337 { 2344 {
2338 GNUNET_SCHEDULER_cancel (c->warn_task); 2345 GNUNET_SCHEDULER_cancel(c->warn_task);
2339 c->warn_task = NULL; 2346 c->warn_task = NULL;
2340 } 2347 }
2341 c->recv_task = GNUNET_SCHEDULER_add_now (&resume_client_receive, c); 2348 c->recv_task = GNUNET_SCHEDULER_add_now(&resume_client_receive, c);
2342} 2349}
2343 2350
2344 2351
@@ -2351,14 +2358,14 @@ GNUNET_SERVICE_client_continue (struct GNUNET_SERVICE_Client *c)
2351 * @param c client for which to disable the warning 2358 * @param c client for which to disable the warning
2352 */ 2359 */
2353void 2360void
2354GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c) 2361GNUNET_SERVICE_client_disable_continue_warning(struct GNUNET_SERVICE_Client *c)
2355{ 2362{
2356 GNUNET_break (NULL != c->warn_task); 2363 GNUNET_break(NULL != c->warn_task);
2357 if (NULL != c->warn_task) 2364 if (NULL != c->warn_task)
2358 { 2365 {
2359 GNUNET_SCHEDULER_cancel (c->warn_task); 2366 GNUNET_SCHEDULER_cancel(c->warn_task);
2360 c->warn_task = NULL; 2367 c->warn_task = NULL;
2361 } 2368 }
2362} 2369}
2363 2370
2364 2371
@@ -2368,32 +2375,32 @@ GNUNET_SERVICE_client_disable_continue_warning (struct GNUNET_SERVICE_Client *c)
2368 * @param cls the `struct GNUNET_SERVICE_Client`. 2375 * @param cls the `struct GNUNET_SERVICE_Client`.
2369 */ 2376 */
2370static void 2377static void
2371finish_client_drop (void *cls) 2378finish_client_drop(void *cls)
2372{ 2379{
2373 struct GNUNET_SERVICE_Client *c = cls; 2380 struct GNUNET_SERVICE_Client *c = cls;
2374 struct GNUNET_SERVICE_Handle *sh = c->sh; 2381 struct GNUNET_SERVICE_Handle *sh = c->sh;
2375 2382
2376 c->drop_task = NULL; 2383 c->drop_task = NULL;
2377 GNUNET_assert (NULL == c->send_task); 2384 GNUNET_assert(NULL == c->send_task);
2378 GNUNET_assert (NULL == c->recv_task); 2385 GNUNET_assert(NULL == c->recv_task);
2379 GNUNET_assert (NULL == c->warn_task); 2386 GNUNET_assert(NULL == c->warn_task);
2380 GNUNET_MST_destroy (c->mst); 2387 GNUNET_MST_destroy(c->mst);
2381 GNUNET_MQ_destroy (c->mq); 2388 GNUNET_MQ_destroy(c->mq);
2382 if (GNUNET_NO == c->persist) 2389 if (GNUNET_NO == c->persist)
2383 { 2390 {
2384 GNUNET_break (GNUNET_OK == GNUNET_NETWORK_socket_close (c->sock)); 2391 GNUNET_break(GNUNET_OK == GNUNET_NETWORK_socket_close(c->sock));
2385 if ((0 != (SUSPEND_STATE_EMFILE & sh->suspend_state)) && 2392 if ((0 != (SUSPEND_STATE_EMFILE & sh->suspend_state)) &&
2386 (0 == (SUSPEND_STATE_SHUTDOWN & sh->suspend_state))) 2393 (0 == (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)))
2387 do_resume (sh, SUSPEND_STATE_EMFILE); 2394 do_resume(sh, SUSPEND_STATE_EMFILE);
2388 } 2395 }
2389 else 2396 else
2390 { 2397 {
2391 GNUNET_NETWORK_socket_free_memory_only_ (c->sock); 2398 GNUNET_NETWORK_socket_free_memory_only_(c->sock);
2392 } 2399 }
2393 GNUNET_free (c); 2400 GNUNET_free(c);
2394 if ((0 != (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) && 2401 if ((0 != (SUSPEND_STATE_SHUTDOWN & sh->suspend_state)) &&
2395 (GNUNET_NO == have_non_monitor_clients (sh))) 2402 (GNUNET_NO == have_non_monitor_clients(sh)))
2396 GNUNET_SERVICE_shutdown (sh); 2403 GNUNET_SERVICE_shutdown(sh);
2397} 2404}
2398 2405
2399 2406
@@ -2408,52 +2415,52 @@ finish_client_drop (void *cls)
2408 * @param c client to disconnect now 2415 * @param c client to disconnect now
2409 */ 2416 */
2410void 2417void
2411GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c) 2418GNUNET_SERVICE_client_drop(struct GNUNET_SERVICE_Client *c)
2412{ 2419{
2413 struct GNUNET_SERVICE_Handle *sh = c->sh; 2420 struct GNUNET_SERVICE_Handle *sh = c->sh;
2414 2421
2415 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 2422 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2416 "Client dropped: %p (MQ: %p)\n", 2423 "Client dropped: %p (MQ: %p)\n",
2417 c, 2424 c,
2418 c->mq); 2425 c->mq);
2419#if EXECINFO 2426#if EXECINFO
2420 { 2427 {
2421 void *backtrace_array[MAX_TRACE_DEPTH]; 2428 void *backtrace_array[MAX_TRACE_DEPTH];
2422 int num_backtrace_strings = backtrace (backtrace_array, MAX_TRACE_DEPTH); 2429 int num_backtrace_strings = backtrace(backtrace_array, MAX_TRACE_DEPTH);
2423 char **backtrace_strings = 2430 char **backtrace_strings =
2424 backtrace_symbols (backtrace_array, t->num_backtrace_strings); 2431 backtrace_symbols(backtrace_array, t->num_backtrace_strings);
2425 for (unsigned int i = 0; i < num_backtrace_strings; i++) 2432 for (unsigned int i = 0; i < num_backtrace_strings; i++)
2426 LOG (GNUNET_ERROR_TYPE_DEBUG, 2433 LOG(GNUNET_ERROR_TYPE_DEBUG,
2427 "client drop trace %u: %s\n", 2434 "client drop trace %u: %s\n",
2428 i, 2435 i,
2429 backtrace_strings[i]); 2436 backtrace_strings[i]);
2430 } 2437 }
2431#endif 2438#endif
2432 if (NULL != c->drop_task) 2439 if (NULL != c->drop_task)
2433 { 2440 {
2434 /* asked to drop twice! */ 2441 /* asked to drop twice! */
2435 GNUNET_assert (0); 2442 GNUNET_assert(0);
2436 return; 2443 return;
2437 } 2444 }
2438 GNUNET_CONTAINER_DLL_remove (sh->clients_head, sh->clients_tail, c); 2445 GNUNET_CONTAINER_DLL_remove(sh->clients_head, sh->clients_tail, c);
2439 if (NULL != sh->disconnect_cb) 2446 if (NULL != sh->disconnect_cb)
2440 sh->disconnect_cb (sh->cb_cls, c, c->user_context); 2447 sh->disconnect_cb(sh->cb_cls, c, c->user_context);
2441 if (NULL != c->warn_task) 2448 if (NULL != c->warn_task)
2442 { 2449 {
2443 GNUNET_SCHEDULER_cancel (c->warn_task); 2450 GNUNET_SCHEDULER_cancel(c->warn_task);
2444 c->warn_task = NULL; 2451 c->warn_task = NULL;
2445 } 2452 }
2446 if (NULL != c->recv_task) 2453 if (NULL != c->recv_task)
2447 { 2454 {
2448 GNUNET_SCHEDULER_cancel (c->recv_task); 2455 GNUNET_SCHEDULER_cancel(c->recv_task);
2449 c->recv_task = NULL; 2456 c->recv_task = NULL;
2450 } 2457 }
2451 if (NULL != c->send_task) 2458 if (NULL != c->send_task)
2452 { 2459 {
2453 GNUNET_SCHEDULER_cancel (c->send_task); 2460 GNUNET_SCHEDULER_cancel(c->send_task);
2454 c->send_task = NULL; 2461 c->send_task = NULL;
2455 } 2462 }
2456 c->drop_task = GNUNET_SCHEDULER_add_now (&finish_client_drop, c); 2463 c->drop_task = GNUNET_SCHEDULER_add_now(&finish_client_drop, c);
2457} 2464}
2458 2465
2459 2466
@@ -2463,14 +2470,14 @@ GNUNET_SERVICE_client_drop (struct GNUNET_SERVICE_Client *c)
2463 * @param sh server to shutdown 2470 * @param sh server to shutdown
2464 */ 2471 */
2465void 2472void
2466GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh) 2473GNUNET_SERVICE_shutdown(struct GNUNET_SERVICE_Handle *sh)
2467{ 2474{
2468 struct GNUNET_SERVICE_Client *client; 2475 struct GNUNET_SERVICE_Client *client;
2469 2476
2470 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN)) 2477 if (0 == (sh->suspend_state & SUSPEND_STATE_SHUTDOWN))
2471 do_suspend (sh, SUSPEND_STATE_SHUTDOWN); 2478 do_suspend(sh, SUSPEND_STATE_SHUTDOWN);
2472 while (NULL != (client = sh->clients_head)) 2479 while (NULL != (client = sh->clients_head))
2473 GNUNET_SERVICE_client_drop (client); 2480 GNUNET_SERVICE_client_drop(client);
2474} 2481}
2475 2482
2476 2483
@@ -2487,12 +2494,12 @@ GNUNET_SERVICE_shutdown (struct GNUNET_SERVICE_Handle *sh)
2487 * @param c client to mark as a monitor 2494 * @param c client to mark as a monitor
2488 */ 2495 */
2489void 2496void
2490GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c) 2497GNUNET_SERVICE_client_mark_monitor(struct GNUNET_SERVICE_Client *c)
2491{ 2498{
2492 c->is_monitor = GNUNET_YES; 2499 c->is_monitor = GNUNET_YES;
2493 if (((0 != (SUSPEND_STATE_SHUTDOWN & c->sh->suspend_state)) && 2500 if (((0 != (SUSPEND_STATE_SHUTDOWN & c->sh->suspend_state)) &&
2494 (GNUNET_NO == have_non_monitor_clients (c->sh)))) 2501 (GNUNET_NO == have_non_monitor_clients(c->sh))))
2495 GNUNET_SERVICE_shutdown (c->sh); 2502 GNUNET_SERVICE_shutdown(c->sh);
2496} 2503}
2497 2504
2498 2505
@@ -2504,7 +2511,7 @@ GNUNET_SERVICE_client_mark_monitor (struct GNUNET_SERVICE_Client *c)
2504 * @param c client to persist the socket (never to be closed) 2511 * @param c client to persist the socket (never to be closed)
2505 */ 2512 */
2506void 2513void
2507GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c) 2514GNUNET_SERVICE_client_persist(struct GNUNET_SERVICE_Client *c)
2508{ 2515{
2509 c->persist = GNUNET_YES; 2516 c->persist = GNUNET_YES;
2510} 2517}
@@ -2517,7 +2524,7 @@ GNUNET_SERVICE_client_persist (struct GNUNET_SERVICE_Client *c)
2517 * @return the message queue of @a c 2524 * @return the message queue of @a c
2518 */ 2525 */
2519struct GNUNET_MQ_Handle * 2526struct GNUNET_MQ_Handle *
2520GNUNET_SERVICE_client_get_mq (struct GNUNET_SERVICE_Client *c) 2527GNUNET_SERVICE_client_get_mq(struct GNUNET_SERVICE_Client *c)
2521{ 2528{
2522 return c->mq; 2529 return c->mq;
2523} 2530}
diff --git a/src/util/signal.c b/src/util/signal.c
index 3e23f4a59..96e40ba7f 100644
--- a/src/util/signal.c
+++ b/src/util/signal.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/signal.c 22 * @file util/signal.c
@@ -27,12 +27,10 @@
27#include "platform.h" 27#include "platform.h"
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define LOG(kind,...) GNUNET_log_from (kind, "util-signal", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-signal", __VA_ARGS__)
31 31
32 32
33struct GNUNET_SIGNAL_Context 33struct GNUNET_SIGNAL_Context {
34{
35
36 struct GNUNET_SIGNAL_Context *next; 34 struct GNUNET_SIGNAL_Context *next;
37 35
38 struct GNUNET_SIGNAL_Context *prev; 36 struct GNUNET_SIGNAL_Context *prev;
@@ -56,7 +54,7 @@ GNUNET_SIGNAL_Handler w32_sigchld_handler = NULL;
56#endif 54#endif
57 55
58struct GNUNET_SIGNAL_Context * 56struct GNUNET_SIGNAL_Context *
59GNUNET_SIGNAL_handler_install (int signum, GNUNET_SIGNAL_Handler handler) 57GNUNET_SIGNAL_handler_install(int signum, GNUNET_SIGNAL_Handler handler)
60{ 58{
61 struct GNUNET_SIGNAL_Context *ret; 59 struct GNUNET_SIGNAL_Context *ret;
62 60
@@ -64,48 +62,48 @@ GNUNET_SIGNAL_handler_install (int signum, GNUNET_SIGNAL_Handler handler)
64 struct sigaction sig; 62 struct sigaction sig;
65#endif 63#endif
66 64
67 ret = GNUNET_new (struct GNUNET_SIGNAL_Context); 65 ret = GNUNET_new(struct GNUNET_SIGNAL_Context);
68 ret->sig = signum; 66 ret->sig = signum;
69 ret->method = handler; 67 ret->method = handler;
70#ifndef MINGW 68#ifndef MINGW
71 memset (&sig, 0, sizeof (sig)); 69 memset(&sig, 0, sizeof(sig));
72 sig.sa_handler = (void *) handler; 70 sig.sa_handler = (void *)handler;
73 sigemptyset (&sig.sa_mask); 71 sigemptyset(&sig.sa_mask);
74#ifdef SA_INTERRUPT 72#ifdef SA_INTERRUPT
75 sig.sa_flags = SA_INTERRUPT; /* SunOS */ 73 sig.sa_flags = SA_INTERRUPT; /* SunOS */
76#else 74#else
77 sig.sa_flags = SA_RESTART; 75 sig.sa_flags = SA_RESTART;
78#endif 76#endif
79 sigaction (signum, &sig, &ret->oldsig); 77 sigaction(signum, &sig, &ret->oldsig);
80#else 78#else
81 if (signum == GNUNET_SIGCHLD) 79 if (signum == GNUNET_SIGCHLD)
82 w32_sigchld_handler = handler; 80 w32_sigchld_handler = handler;
83 else 81 else
84 {
85 __p_sig_fn_t sigret = signal (signum, (__p_sig_fn_t) handler);
86
87 if (sigret == SIG_ERR)
88 { 82 {
89 LOG (GNUNET_ERROR_TYPE_WARNING, _("signal (%d, %p) returned %d.\n"), 83 __p_sig_fn_t sigret = signal(signum, (__p_sig_fn_t)handler);
90 signum, handler, sigret); 84
85 if (sigret == SIG_ERR)
86 {
87 LOG(GNUNET_ERROR_TYPE_WARNING, _("signal (%d, %p) returned %d.\n"),
88 signum, handler, sigret);
89 }
91 } 90 }
92 }
93#endif 91#endif
94 GNUNET_CONTAINER_DLL_insert_tail (sc_head, sc_tail, ret); 92 GNUNET_CONTAINER_DLL_insert_tail(sc_head, sc_tail, ret);
95 return ret; 93 return ret;
96} 94}
97 95
98void 96void
99GNUNET_SIGNAL_handler_uninstall (struct GNUNET_SIGNAL_Context *ctx) 97GNUNET_SIGNAL_handler_uninstall(struct GNUNET_SIGNAL_Context *ctx)
100{ 98{
101#ifndef MINGW 99#ifndef MINGW
102 struct sigaction sig; 100 struct sigaction sig;
103 101
104 sigemptyset (&sig.sa_mask); 102 sigemptyset(&sig.sa_mask);
105 sigaction (ctx->sig, &ctx->oldsig, &sig); 103 sigaction(ctx->sig, &ctx->oldsig, &sig);
106#endif 104#endif
107 GNUNET_CONTAINER_DLL_remove (sc_head, sc_tail, ctx); 105 GNUNET_CONTAINER_DLL_remove(sc_head, sc_tail, ctx);
108 GNUNET_free (ctx); 106 GNUNET_free(ctx);
109} 107}
110 108
111 109
@@ -117,16 +115,16 @@ GNUNET_SIGNAL_handler_uninstall (struct GNUNET_SIGNAL_Context *ctx)
117 * @param sig the signal to raise 115 * @param sig the signal to raise
118 */ 116 */
119void 117void
120GNUNET_SIGNAL_raise (const int sig) 118GNUNET_SIGNAL_raise(const int sig)
121{ 119{
122 struct GNUNET_SIGNAL_Context *ctx; 120 struct GNUNET_SIGNAL_Context *ctx;
123 121
124 for (ctx = sc_head; NULL != ctx; ctx = ctx->next) 122 for (ctx = sc_head; NULL != ctx; ctx = ctx->next)
125 { 123 {
126 if (sig != ctx->sig) 124 if (sig != ctx->sig)
127 continue; 125 continue;
128 if (NULL == ctx->method) 126 if (NULL == ctx->method)
129 continue; 127 continue;
130 ctx->method (); 128 ctx->method();
131 } 129 }
132} 130}
diff --git a/src/util/socks.c b/src/util/socks.c
index 66b7bf7df..ca3d1e8c4 100644
--- a/src/util/socks.c
+++ b/src/util/socks.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/socks.c 22 * @file util/socks.c
@@ -29,10 +29,10 @@
29#include "gnunet_util_lib.h" 29#include "gnunet_util_lib.h"
30 30
31 31
32#define LOG(kind, ...) GNUNET_log_from (kind, "util-socks", __VA_ARGS__) 32#define LOG(kind, ...) GNUNET_log_from(kind, "util-socks", __VA_ARGS__)
33 33
34#define LOG_STRERROR(kind, syscall) \ 34#define LOG_STRERROR(kind, syscall) \
35 GNUNET_log_from_strerror (kind, "util-socks", syscall) 35 GNUNET_log_from_strerror(kind, "util-socks", syscall)
36 36
37 37
38/* SOCKS5 authentication methods */ 38/* SOCKS5 authentication methods */
@@ -58,33 +58,43 @@
58#define SOCKS5_REP_INVADDR 0x09 /* Inalid address */ 58#define SOCKS5_REP_INVADDR 0x09 /* Inalid address */
59 59
60const char * 60const char *
61SOCKS5_REP_names (int rep) 61SOCKS5_REP_names(int rep)
62{ 62{
63 switch (rep) 63 switch (rep)
64 { 64 {
65 case SOCKS5_REP_SUCCEEDED: 65 case SOCKS5_REP_SUCCEEDED:
66 return "succeeded"; 66 return "succeeded";
67 case SOCKS5_REP_FAIL: 67
68 return "general SOCKS server failure"; 68 case SOCKS5_REP_FAIL:
69 case SOCKS5_REP_NALLOWED: 69 return "general SOCKS server failure";
70 return "connection not allowed by ruleset"; 70
71 case SOCKS5_REP_NUNREACH: 71 case SOCKS5_REP_NALLOWED:
72 return "Network unreachable"; 72 return "connection not allowed by ruleset";
73 case SOCKS5_REP_HUNREACH: 73
74 return "Host unreachable"; 74 case SOCKS5_REP_NUNREACH:
75 case SOCKS5_REP_REFUSED: 75 return "Network unreachable";
76 return "connection refused"; 76
77 case SOCKS5_REP_EXPIRED: 77 case SOCKS5_REP_HUNREACH:
78 return "TTL expired"; 78 return "Host unreachable";
79 case SOCKS5_REP_CNOTSUP: 79
80 return "Command not supported"; 80 case SOCKS5_REP_REFUSED:
81 case SOCKS5_REP_ANOTSUP: 81 return "connection refused";
82 return "Address not supported"; 82
83 case SOCKS5_REP_INVADDR: 83 case SOCKS5_REP_EXPIRED:
84 return "Invalid address"; 84 return "TTL expired";
85 default: 85
86 return NULL; 86 case SOCKS5_REP_CNOTSUP:
87 } 87 return "Command not supported";
88
89 case SOCKS5_REP_ANOTSUP:
90 return "Address not supported";
91
92 case SOCKS5_REP_INVADDR:
93 return "Invalid address";
94
95 default:
96 return NULL;
97 }
88}; 98};
89 99
90 100
@@ -98,18 +108,18 @@ SOCKS5_REP_names (int rep)
98 * @return pointer to the end of the encoded string in the buffer 108 * @return pointer to the end of the encoded string in the buffer
99 */ 109 */
100unsigned char * 110unsigned char *
101SOCK5_proto_string (unsigned char *b, const char *s) 111SOCK5_proto_string(unsigned char *b, const char *s)
102{ 112{
103 size_t l = strlen (s); 113 size_t l = strlen(s);
104 114
105 if (l > 255) 115 if (l > 255)
106 { 116 {
107 LOG (GNUNET_ERROR_TYPE_WARNING, 117 LOG(GNUNET_ERROR_TYPE_WARNING,
108 "SOCKS5 cannot handle hostnames, usernames, or passwords over 255 bytes, truncating.\n"); 118 "SOCKS5 cannot handle hostnames, usernames, or passwords over 255 bytes, truncating.\n");
109 l = 255; 119 l = 255;
110 } 120 }
111 *(b++) = (unsigned char) l; 121 *(b++) = (unsigned char)l;
112 memcpy (b, s, l); 122 memcpy(b, s, l);
113 return b + l; 123 return b + l;
114} 124}
115 125
@@ -122,9 +132,7 @@ SOCK5_proto_string (unsigned char *b, const char *s)
122/** 132/**
123 * State of the SOCKS5 handshake. 133 * State of the SOCKS5 handshake.
124 */ 134 */
125struct GNUNET_SOCKS_Handshake 135struct GNUNET_SOCKS_Handshake {
126{
127
128 /** 136 /**
129 * Connection handle used for SOCKS5 137 * Connection handle used for SOCKS5
130 */ 138 */
@@ -171,16 +179,16 @@ struct GNUNET_SOCKS_Handshake
171/* Regitering prototypes */ 179/* Regitering prototypes */
172 180
173void 181void
174register_reciever (struct GNUNET_SOCKS_Handshake *ih, int want); 182register_reciever(struct GNUNET_SOCKS_Handshake *ih, int want);
175 183
176/* In fact, the client sends first rule in GNUnet suggests one could take 184/* In fact, the client sends first rule in GNUnet suggests one could take
177 * large mac read sizes without fear of screwing up the proxied protocol, 185 * large mac read sizes without fear of screwing up the proxied protocol,
178 * but we make a proper SOCKS5 client. */ 186 * but we make a proper SOCKS5 client. */
179#define register_reciever_wants(ih) ((SOCKS5_step_cmd == ih->step) ? 10 : 2) 187#define register_reciever_wants(ih) ((SOCKS5_step_cmd == ih->step) ? 10 : 2)
180 188
181 189
182struct GNUNET_CONNECTION_TransmitHandle * 190struct GNUNET_CONNECTION_TransmitHandle *
183register_sender (struct GNUNET_SOCKS_Handshake *ih); 191register_sender(struct GNUNET_SOCKS_Handshake *ih);
184 192
185 193
186/** 194/**
@@ -191,9 +199,9 @@ register_sender (struct GNUNET_SOCKS_Handshake *ih);
191 * @return Connection handle that becomes usable when the handshake completes. 199 * @return Connection handle that becomes usable when the handshake completes.
192 */ 200 */
193void 201void
194SOCKS5_handshake_done (struct GNUNET_SOCKS_Handshake *ih) 202SOCKS5_handshake_done(struct GNUNET_SOCKS_Handshake *ih)
195{ 203{
196 GNUNET_CONNECTION_acivate_proxied (ih->target_connection); 204 GNUNET_CONNECTION_acivate_proxied(ih->target_connection);
197} 205}
198 206
199 207
@@ -203,100 +211,109 @@ SOCKS5_handshake_done (struct GNUNET_SOCKS_Handshake *ih)
203 * @param ih SOCKS5 Handshake 211 * @param ih SOCKS5 Handshake
204 */ 212 */
205void 213void
206SOCKS5_handshake_step (struct GNUNET_SOCKS_Handshake *ih) 214SOCKS5_handshake_step(struct GNUNET_SOCKS_Handshake *ih)
207{ 215{
208 unsigned char *b = ih->instart; 216 unsigned char *b = ih->instart;
209 size_t available = ih->inend - b; 217 size_t available = ih->inend - b;
210 218
211 int want = register_reciever_wants (ih); 219 int want = register_reciever_wants(ih);
220
212 if (available < want) 221 if (available < want)
213 {
214 register_reciever (ih, want - available);
215 return;
216 }
217 GNUNET_assert (SOCKS5_step_done > ih->step && ih->step >= 0);
218 switch (ih->step)
219 {
220 case SOCKS5_step_greet: /* SOCKS5 server's greeting */
221 if (b[0] != 5)
222 {
223 LOG (GNUNET_ERROR_TYPE_ERROR, "Not a SOCKS5 server\n");
224 GNUNET_assert (0);
225 }
226 switch (b[1])
227 { 222 {
228 case SOCKS5_AUTH_NOAUTH: 223 register_reciever(ih, want - available);
229 ih->step = SOCKS5_step_cmd; /* no authentication to do */
230 break;
231 case SOCKS5_AUTH_USERPASS:
232 ih->step = SOCKS5_step_auth;
233 break;
234 case SOCKS5_AUTH_REJECT:
235 LOG (GNUNET_ERROR_TYPE_ERROR, "No authentication method accepted\n");
236 return;
237 default:
238 LOG (GNUNET_ERROR_TYPE_ERROR,
239 "Not a SOCKS5 server / Nonsensical authentication\n");
240 return; 224 return;
241 } 225 }
242 b += 2; 226 GNUNET_assert(SOCKS5_step_done > ih->step && ih->step >= 0);
243 break; 227 switch (ih->step)
244 case SOCKS5_step_auth: /* SOCKS5 server's responce to authentication */
245 if (b[1] != 0)
246 {
247 LOG (GNUNET_ERROR_TYPE_ERROR, "SOCKS5 authentication failed\n");
248 GNUNET_assert (0);
249 }
250 ih->step = SOCKS5_step_cmd;
251 b += 2;
252 break;
253 case SOCKS5_step_cmd: /* SOCKS5 server's responce to command */
254 if (b[0] != 5)
255 {
256 LOG (GNUNET_ERROR_TYPE_ERROR, "SOCKS5 protocol error\n");
257 GNUNET_assert (0);
258 }
259 if (0 != b[1])
260 {
261 LOG (GNUNET_ERROR_TYPE_ERROR,
262 "SOCKS5 connection error : %s\n",
263 SOCKS5_REP_names (b[1]));
264 return;
265 }
266 b += 3;
267 /* There is no reason to verify host and port afaik. */
268 switch (*(b++))
269 { 228 {
270 case 1: /* IPv4 */ 229 case SOCKS5_step_greet: /* SOCKS5 server's greeting */
271 b += sizeof (struct in_addr); /* 4 */ 230 if (b[0] != 5)
231 {
232 LOG(GNUNET_ERROR_TYPE_ERROR, "Not a SOCKS5 server\n");
233 GNUNET_assert(0);
234 }
235 switch (b[1])
236 {
237 case SOCKS5_AUTH_NOAUTH:
238 ih->step = SOCKS5_step_cmd; /* no authentication to do */
239 break;
240
241 case SOCKS5_AUTH_USERPASS:
242 ih->step = SOCKS5_step_auth;
243 break;
244
245 case SOCKS5_AUTH_REJECT:
246 LOG(GNUNET_ERROR_TYPE_ERROR, "No authentication method accepted\n");
247 return;
248
249 default:
250 LOG(GNUNET_ERROR_TYPE_ERROR,
251 "Not a SOCKS5 server / Nonsensical authentication\n");
252 return;
253 }
254 b += 2;
272 break; 255 break;
273 case 4: /* IPv6 */ 256
274 b += sizeof (struct in6_addr); /* 16 */ 257 case SOCKS5_step_auth: /* SOCKS5 server's responce to authentication */
275 break; 258 if (b[1] != 0)
276 case 3: /* hostname */ 259 {
277 b += *b; 260 LOG(GNUNET_ERROR_TYPE_ERROR, "SOCKS5 authentication failed\n");
261 GNUNET_assert(0);
262 }
263 ih->step = SOCKS5_step_cmd;
264 b += 2;
278 break; 265 break;
279 } 266
280 b += 2; /* port */ 267 case SOCKS5_step_cmd: /* SOCKS5 server's responce to command */
281 if (b > ih->inend) 268 if (b[0] != 5)
282 { 269 {
283 register_reciever (ih, b - ih->inend); 270 LOG(GNUNET_ERROR_TYPE_ERROR, "SOCKS5 protocol error\n");
271 GNUNET_assert(0);
272 }
273 if (0 != b[1])
274 {
275 LOG(GNUNET_ERROR_TYPE_ERROR,
276 "SOCKS5 connection error : %s\n",
277 SOCKS5_REP_names(b[1]));
278 return;
279 }
280 b += 3;
281 /* There is no reason to verify host and port afaik. */
282 switch (*(b++))
283 {
284 case 1: /* IPv4 */
285 b += sizeof(struct in_addr); /* 4 */
286 break;
287
288 case 4: /* IPv6 */
289 b += sizeof(struct in6_addr); /* 16 */
290 break;
291
292 case 3: /* hostname */
293 b += *b;
294 break;
295 }
296 b += 2; /* port */
297 if (b > ih->inend)
298 {
299 register_reciever(ih, b - ih->inend);
300 return;
301 }
302 ih->step = SOCKS5_step_done;
303 LOG(GNUNET_ERROR_TYPE_DEBUG,
304 "SOCKS5 server : %s\n",
305 SOCKS5_REP_names(b[1]));
306 ih->instart = b;
307 SOCKS5_handshake_done(ih);
284 return; 308 return;
309
310 case SOCKS5_step_done:
311 GNUNET_assert(0);
285 } 312 }
286 ih->step = SOCKS5_step_done;
287 LOG (GNUNET_ERROR_TYPE_DEBUG,
288 "SOCKS5 server : %s\n",
289 SOCKS5_REP_names (b[1]));
290 ih->instart = b;
291 SOCKS5_handshake_done (ih);
292 return;
293 case SOCKS5_step_done:
294 GNUNET_assert (0);
295 }
296 ih->instart = b; 313 ih->instart = b;
297 /* Do not reschedule the sender unless we're done reading. 314 /* Do not reschedule the sender unless we're done reading.
298 * I imagine this lets us avoid ever cancelling the transmit handle. */ 315 * I imagine this lets us avoid ever cancelling the transmit handle. */
299 register_sender (ih); 316 register_sender(ih);
300} 317}
301 318
302 319
@@ -308,18 +325,19 @@ SOCKS5_handshake_step (struct GNUNET_SOCKS_Handshake *ih)
308 * @param handler_cls closure for @a handler 325 * @param handler_cls closure for @a handler
309 */ 326 */
310void 327void
311reciever (void *cls, 328reciever(void *cls,
312 const void *buf, 329 const void *buf,
313 size_t available, 330 size_t available,
314 const struct sockaddr *addr, 331 const struct sockaddr *addr,
315 socklen_t addrlen, 332 socklen_t addrlen,
316 int errCode) 333 int errCode)
317{ 334{
318 struct GNUNET_SOCKS_Handshake *ih = cls; 335 struct GNUNET_SOCKS_Handshake *ih = cls;
319 GNUNET_assert (&ih->inend[available] < &ih->inbuf[1024]); 336
320 GNUNET_memcpy (ih->inend, buf, available); 337 GNUNET_assert(&ih->inend[available] < &ih->inbuf[1024]);
338 GNUNET_memcpy(ih->inend, buf, available);
321 ih->inend += available; 339 ih->inend += available;
322 SOCKS5_handshake_step (ih); 340 SOCKS5_handshake_step(ih);
323} 341}
324 342
325 343
@@ -331,13 +349,13 @@ reciever (void *cls,
331 * @param handler_cls closure for @a handler 349 * @param handler_cls closure for @a handler
332 */ 350 */
333void 351void
334register_reciever (struct GNUNET_SOCKS_Handshake *ih, int want) 352register_reciever(struct GNUNET_SOCKS_Handshake *ih, int want)
335{ 353{
336 GNUNET_CONNECTION_receive (ih->socks5_connection, 354 GNUNET_CONNECTION_receive(ih->socks5_connection,
337 want, 355 want,
338 GNUNET_TIME_relative_get_minute_ (), 356 GNUNET_TIME_relative_get_minute_(),
339 &reciever, 357 &reciever,
340 ih); 358 ih);
341} 359}
342 360
343 361
@@ -350,7 +368,7 @@ register_reciever (struct GNUNET_SOCKS_Handshake *ih, int want)
350 * @return number of bytes written to @a buf 368 * @return number of bytes written to @a buf
351 */ 369 */
352size_t 370size_t
353transmit_ready (void *cls, size_t size, void *buf) 371transmit_ready(void *cls, size_t size, void *buf)
354{ 372{
355 struct GNUNET_SOCKS_Handshake *ih = cls; 373 struct GNUNET_SOCKS_Handshake *ih = cls;
356 374
@@ -370,32 +388,32 @@ transmit_ready (void *cls, size_t size, void *buf)
370 * maybe that should change for error handling pruposes. It appears that 388 * maybe that should change for error handling pruposes. It appears that
371 * successful operations, including DNS resolution, do not use this. */ 389 * successful operations, including DNS resolution, do not use this. */
372 if (NULL == buf) 390 if (NULL == buf)
373 {
374 if (0 == ih->step)
375 {
376 LOG (GNUNET_ERROR_TYPE_WARNING,
377 "Timeout contacting SOCKS server, retrying indefinitely, but probably hopeless.\n");
378 register_sender (ih);
379 }
380 else
381 { 391 {
382 LOG (GNUNET_ERROR_TYPE_ERROR, 392 if (0 == ih->step)
383 "Timeout during mid SOCKS handshake (step %u), probably not a SOCKS server.\n", 393 {
384 ih->step); 394 LOG(GNUNET_ERROR_TYPE_WARNING,
385 GNUNET_break (0); 395 "Timeout contacting SOCKS server, retrying indefinitely, but probably hopeless.\n");
396 register_sender(ih);
397 }
398 else
399 {
400 LOG(GNUNET_ERROR_TYPE_ERROR,
401 "Timeout during mid SOCKS handshake (step %u), probably not a SOCKS server.\n",
402 ih->step);
403 GNUNET_break(0);
404 }
405 return 0;
386 } 406 }
387 return 0;
388 }
389 407
390 GNUNET_assert ((1024 >= size) && (size > 0)); 408 GNUNET_assert((1024 >= size) && (size > 0));
391 GNUNET_assert ((SOCKS5_step_done > ih->step) && (ih->step >= 0)); 409 GNUNET_assert((SOCKS5_step_done > ih->step) && (ih->step >= 0));
392 unsigned char *b = ih->outstep[ih->step]; 410 unsigned char *b = ih->outstep[ih->step];
393 unsigned char *e = ih->outstep[ih->step + 1]; 411 unsigned char *e = ih->outstep[ih->step + 1];
394 GNUNET_assert (e <= &ih->outbuf[1024]); 412 GNUNET_assert(e <= &ih->outbuf[1024]);
395 unsigned int l = e - b; 413 unsigned int l = e - b;
396 GNUNET_assert (size >= l); 414 GNUNET_assert(size >= l);
397 GNUNET_memcpy (buf, b, l); 415 GNUNET_memcpy(buf, b, l);
398 register_reciever (ih, register_reciever_wants (ih)); 416 register_reciever(ih, register_reciever_wants(ih));
399 return l; 417 return l;
400} 418}
401 419
@@ -408,22 +426,22 @@ transmit_ready (void *cls, size_t size, void *buf)
408 * NULL if we are already going to notify someone else (busy) 426 * NULL if we are already going to notify someone else (busy)
409 */ 427 */
410struct GNUNET_CONNECTION_TransmitHandle * 428struct GNUNET_CONNECTION_TransmitHandle *
411register_sender (struct GNUNET_SOCKS_Handshake *ih) 429register_sender(struct GNUNET_SOCKS_Handshake *ih)
412{ 430{
413 struct GNUNET_TIME_Relative timeout = GNUNET_TIME_UNIT_MINUTES; 431 struct GNUNET_TIME_Relative timeout = GNUNET_TIME_UNIT_MINUTES;
414 432
415 GNUNET_assert (SOCKS5_step_done > ih->step); 433 GNUNET_assert(SOCKS5_step_done > ih->step);
416 GNUNET_assert (ih->step >= 0); 434 GNUNET_assert(ih->step >= 0);
417 if (0 == ih->step) 435 if (0 == ih->step)
418 timeout = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MINUTES, 3); 436 timeout = GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MINUTES, 3);
419 unsigned char *b = ih->outstep[ih->step]; 437 unsigned char *b = ih->outstep[ih->step];
420 unsigned char *e = ih->outstep[ih->step + 1]; 438 unsigned char *e = ih->outstep[ih->step + 1];
421 GNUNET_assert (ih->outbuf <= b && b < e && e < &ih->outbuf[1024]); 439 GNUNET_assert(ih->outbuf <= b && b < e && e < &ih->outbuf[1024]);
422 ih->th = GNUNET_CONNECTION_notify_transmit_ready (ih->socks5_connection, 440 ih->th = GNUNET_CONNECTION_notify_transmit_ready(ih->socks5_connection,
423 e - b, 441 e - b,
424 timeout, 442 timeout,
425 &transmit_ready, 443 &transmit_ready,
426 ih); 444 ih);
427 return ih->th; 445 return ih->th;
428} 446}
429 447
@@ -438,10 +456,10 @@ register_sender (struct GNUNET_SOCKS_Handshake *ih)
438 * @return Valid SOCKS5 hanbdshake handle 456 * @return Valid SOCKS5 hanbdshake handle
439 */ 457 */
440struct GNUNET_SOCKS_Handshake * 458struct GNUNET_SOCKS_Handshake *
441GNUNET_SOCKS_init_handshake (const char *user, const char *pass) 459GNUNET_SOCKS_init_handshake(const char *user, const char *pass)
442{ 460{
443 struct GNUNET_SOCKS_Handshake *ih = 461 struct GNUNET_SOCKS_Handshake *ih =
444 GNUNET_new (struct GNUNET_SOCKS_Handshake); 462 GNUNET_new(struct GNUNET_SOCKS_Handshake);
445 unsigned char *b = ih->outbuf; 463 unsigned char *b = ih->outbuf;
446 464
447 ih->outstep[SOCKS5_step_greet] = b; 465 ih->outstep[SOCKS5_step_greet] = b;
@@ -453,10 +471,10 @@ GNUNET_SOCKS_init_handshake (const char *user, const char *pass)
453 * And some SOCKS5 servers might require this. */ 471 * And some SOCKS5 servers might require this. */
454 *(b++) = SOCKS5_AUTH_NOAUTH; 472 *(b++) = SOCKS5_AUTH_NOAUTH;
455 if (NULL != user) 473 if (NULL != user)
456 { 474 {
457 *(b++) = SOCKS5_AUTH_USERPASS; 475 *(b++) = SOCKS5_AUTH_USERPASS;
458 (*n)++; 476 (*n)++;
459 } 477 }
460 /* There is no apperent reason to support authentication methods beyond 478 /* There is no apperent reason to support authentication methods beyond
461 * username and password since afaik Tor does not support them. */ 479 * username and password since afaik Tor does not support them. */
462 480
@@ -469,8 +487,8 @@ GNUNET_SOCKS_init_handshake (const char *user, const char *pass)
469 487
470 ih->outstep[SOCKS5_step_auth] = b; 488 ih->outstep[SOCKS5_step_auth] = b;
471 *(b++) = 1; /* subnegotiation ver.: 1 */ 489 *(b++) = 1; /* subnegotiation ver.: 1 */
472 b = SOCK5_proto_string (b, user); 490 b = SOCK5_proto_string(b, user);
473 b = SOCK5_proto_string (b, pass); 491 b = SOCK5_proto_string(b, pass);
474 492
475 ih->outstep[SOCKS5_step_cmd] = b; 493 ih->outstep[SOCKS5_step_cmd] = b;
476 494
@@ -487,9 +505,9 @@ GNUNET_SOCKS_init_handshake (const char *user, const char *pass)
487 * @return Valid SOCKS5 hanbdshake handle 505 * @return Valid SOCKS5 hanbdshake handle
488 */ 506 */
489struct GNUNET_SOCKS_Handshake * 507struct GNUNET_SOCKS_Handshake *
490GNUNET_SOCKS_init_handshake_noauth () 508GNUNET_SOCKS_init_handshake_noauth()
491{ 509{
492 return GNUNET_SOCKS_init_handshake (NULL, NULL); 510 return GNUNET_SOCKS_init_handshake(NULL, NULL);
493} 511}
494 512
495 513
@@ -502,12 +520,11 @@ GNUNET_SOCKS_init_handshake_noauth ()
502 * @param port 520 * @param port
503 */ 521 */
504void 522void
505GNUNET_SOCKS_set_handshake_destination (struct GNUNET_SOCKS_Handshake *ih, 523GNUNET_SOCKS_set_handshake_destination(struct GNUNET_SOCKS_Handshake *ih,
506 const char *host, 524 const char *host,
507 uint16_t port) 525 uint16_t port)
508{ 526{
509 union 527 union {
510 {
511 struct in_addr in4; 528 struct in_addr in4;
512 struct in6_addr in6; 529 struct in6_addr in6;
513 } ia; 530 } ia;
@@ -518,26 +535,26 @@ GNUNET_SOCKS_set_handshake_destination (struct GNUNET_SOCKS_Handshake *ih,
518 *(b++) = 0; /* reserved */ 535 *(b++) = 0; /* reserved */
519 536
520 /* Specify destination */ 537 /* Specify destination */
521 if (1 == inet_pton (AF_INET, host, &ia.in4)) 538 if (1 == inet_pton(AF_INET, host, &ia.in4))
522 { 539 {
523 *(b++) = 1; /* IPv4 */ 540 *(b++) = 1; /* IPv4 */
524 GNUNET_memcpy (b, &ia.in4, sizeof (struct in_addr)); 541 GNUNET_memcpy(b, &ia.in4, sizeof(struct in_addr));
525 b += sizeof (struct in_addr); /* 4 */ 542 b += sizeof(struct in_addr); /* 4 */
526 } 543 }
527 else if (1 == inet_pton (AF_INET6, host, &ia.in6)) 544 else if (1 == inet_pton(AF_INET6, host, &ia.in6))
528 { 545 {
529 *(b++) = 4; /* IPv6 */ 546 *(b++) = 4; /* IPv6 */
530 GNUNET_memcpy (b, &ia.in6, sizeof (struct in6_addr)); 547 GNUNET_memcpy(b, &ia.in6, sizeof(struct in6_addr));
531 b += sizeof (struct in6_addr); /* 16 */ 548 b += sizeof(struct in6_addr); /* 16 */
532 } 549 }
533 else 550 else
534 { 551 {
535 *(b++) = 3; /* hostname */ 552 *(b++) = 3; /* hostname */
536 b = SOCK5_proto_string (b, host); 553 b = SOCK5_proto_string(b, host);
537 } 554 }
538 555
539 /* Specify port */ 556 /* Specify port */
540 *(uint16_t *) b = htons (port); 557 *(uint16_t *)b = htons(port);
541 b += 2; 558 b += 2;
542 559
543 ih->outstep[SOCKS5_step_done] = b; 560 ih->outstep[SOCKS5_step_done] = b;
@@ -552,12 +569,12 @@ GNUNET_SOCKS_set_handshake_destination (struct GNUNET_SOCKS_Handshake *ih,
552 * @return Connection handle that becomes usable when the SOCKS5 handshake completes. 569 * @return Connection handle that becomes usable when the SOCKS5 handshake completes.
553 */ 570 */
554struct GNUNET_CONNECTION_Handle * 571struct GNUNET_CONNECTION_Handle *
555GNUNET_SOCKS_run_handshake (struct GNUNET_SOCKS_Handshake *ih, 572GNUNET_SOCKS_run_handshake(struct GNUNET_SOCKS_Handshake *ih,
556 struct GNUNET_CONNECTION_Handle *c) 573 struct GNUNET_CONNECTION_Handle *c)
557{ 574{
558 ih->socks5_connection = c; 575 ih->socks5_connection = c;
559 ih->target_connection = GNUNET_CONNECTION_create_proxied_from_handshake (c); 576 ih->target_connection = GNUNET_CONNECTION_create_proxied_from_handshake(c);
560 register_sender (ih); 577 register_sender(ih);
561 578
562 return ih->target_connection; 579 return ih->target_connection;
563} 580}
@@ -572,11 +589,11 @@ GNUNET_SOCKS_run_handshake (struct GNUNET_SOCKS_Handshake *ih,
572 * @return GNUNET_YES if so, GNUNET_NO if not 589 * @return GNUNET_YES if so, GNUNET_NO if not
573 */ 590 */
574int 591int
575GNUNET_SOCKS_check_service (const char *service_name, 592GNUNET_SOCKS_check_service(const char *service_name,
576 const struct GNUNET_CONFIGURATION_Handle *cfg) 593 const struct GNUNET_CONFIGURATION_Handle *cfg)
577{ 594{
578 return GNUNET_CONFIGURATION_have_value (cfg, service_name, "SOCKSPORT") || 595 return GNUNET_CONFIGURATION_have_value(cfg, service_name, "SOCKSPORT") ||
579 GNUNET_CONFIGURATION_have_value (cfg, service_name, "SOCKSHOST"); 596 GNUNET_CONFIGURATION_have_value(cfg, service_name, "SOCKSHOST");
580} 597}
581 598
582 599
@@ -589,8 +606,8 @@ GNUNET_SOCKS_check_service (const char *service_name,
589 * NULL if SOCKS not configured or not configured properly 606 * NULL if SOCKS not configured or not configured properly
590 */ 607 */
591struct GNUNET_CONNECTION_Handle * 608struct GNUNET_CONNECTION_Handle *
592GNUNET_SOCKS_do_connect (const char *service_name, 609GNUNET_SOCKS_do_connect(const char *service_name,
593 const struct GNUNET_CONFIGURATION_Handle *cfg) 610 const struct GNUNET_CONFIGURATION_Handle *cfg)
594{ 611{
595 struct GNUNET_SOCKS_Handshake *ih; 612 struct GNUNET_SOCKS_Handshake *ih;
596 struct GNUNET_CONNECTION_Handle *socks5; /* *proxied */ 613 struct GNUNET_CONNECTION_Handle *socks5; /* *proxied */
@@ -601,70 +618,70 @@ GNUNET_SOCKS_do_connect (const char *service_name,
601 unsigned long long port0; 618 unsigned long long port0;
602 unsigned long long port1; 619 unsigned long long port1;
603 620
604 if (GNUNET_YES != GNUNET_SOCKS_check_service (service_name, cfg)) 621 if (GNUNET_YES != GNUNET_SOCKS_check_service(service_name, cfg))
605 return NULL; 622 return NULL;
606 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, 623 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg,
607 service_name, 624 service_name,
608 "SOCKSPORT", 625 "SOCKSPORT",
609 &port0)) 626 &port0))
610 port0 = 9050; 627 port0 = 9050;
611 /* A typical Tor client should usually try port 9150 for the TBB too, but 628 /* A typical Tor client should usually try port 9150 for the TBB too, but
612 * GNUnet can probably assume a system Tor installation. */ 629 * GNUnet can probably assume a system Tor installation. */
613 if (port0 > 65535 || port0 <= 0) 630 if (port0 > 65535 || port0 <= 0)
614 { 631 {
615 LOG (GNUNET_ERROR_TYPE_WARNING, 632 LOG(GNUNET_ERROR_TYPE_WARNING,
616 _ ( 633 _(
617 "Attempting to use invalid port %d as SOCKS proxy for service `%s'.\n"), 634 "Attempting to use invalid port %d as SOCKS proxy for service `%s'.\n"),
618 port0, 635 port0,
619 service_name); 636 service_name);
620 return NULL; 637 return NULL;
621 } 638 }
622 if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (cfg, 639 if ((GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(cfg,
623 service_name, 640 service_name,
624 "PORT", 641 "PORT",
625 &port1)) || 642 &port1)) ||
626 (port1 > 65535) || (port1 <= 0) || 643 (port1 > 65535) || (port1 <= 0) ||
627 (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, 644 (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg,
628 service_name, 645 service_name,
629 "HOSTNAME", 646 "HOSTNAME",
630 &host1))) 647 &host1)))
631 { 648 {
632 LOG (GNUNET_ERROR_TYPE_WARNING, 649 LOG(GNUNET_ERROR_TYPE_WARNING,
633 _ ( 650 _(
634 "Attempting to proxy service `%s' to invalid port %d or hostname.\n"), 651 "Attempting to proxy service `%s' to invalid port %d or hostname.\n"),
635 service_name, 652 service_name,
636 port1); 653 port1);
637 return NULL; 654 return NULL;
638 } 655 }
639 /* Appeared to still work after host0 corrupted, so either test case is broken, or 656 /* Appeared to still work after host0 corrupted, so either test case is broken, or
640 this whole routine is not being called. */ 657 this whole routine is not being called. */
641 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, 658 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg,
642 service_name, 659 service_name,
643 "SOCKSHOST", 660 "SOCKSHOST",
644 &host0)) 661 &host0))
645 host0 = NULL; 662 host0 = NULL;
646 socks5 = GNUNET_CONNECTION_create_from_connect (cfg, 663 socks5 = GNUNET_CONNECTION_create_from_connect(cfg,
647 (host0 != NULL) ? host0 664 (host0 != NULL) ? host0
648 : "127.0.0.1", 665 : "127.0.0.1",
649 port0); 666 port0);
650 GNUNET_free_non_null (host0); 667 GNUNET_free_non_null(host0);
651 668
652 /* Sets to NULL if they do not exist */ 669 /* Sets to NULL if they do not exist */
653 (void) GNUNET_CONFIGURATION_get_value_string (cfg, 670 (void)GNUNET_CONFIGURATION_get_value_string(cfg,
654 service_name, 671 service_name,
655 "SOCKSUSER", 672 "SOCKSUSER",
656 &user); 673 &user);
657 (void) GNUNET_CONFIGURATION_get_value_string (cfg, 674 (void)GNUNET_CONFIGURATION_get_value_string(cfg,
658 service_name, 675 service_name,
659 "SOCKSPASS", 676 "SOCKSPASS",
660 &pass); 677 &pass);
661 ih = GNUNET_SOCKS_init_handshake (user, pass); 678 ih = GNUNET_SOCKS_init_handshake(user, pass);
662 GNUNET_free_non_null (user); 679 GNUNET_free_non_null(user);
663 GNUNET_free_non_null (pass); 680 GNUNET_free_non_null(pass);
664 681
665 GNUNET_SOCKS_set_handshake_destination (ih, host1, port1); 682 GNUNET_SOCKS_set_handshake_destination(ih, host1, port1);
666 GNUNET_free (host1); 683 GNUNET_free(host1);
667 return GNUNET_SOCKS_run_handshake (ih, socks5); 684 return GNUNET_SOCKS_run_handshake(ih, socks5);
668} 685}
669 686
670/* socks.c */ 687/* socks.c */
diff --git a/src/util/speedup.c b/src/util/speedup.c
index c5c1f6a53..735da18c3 100644
--- a/src/util/speedup.c
+++ b/src/util/speedup.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/speedup.c 22 * @file util/speedup.c
@@ -27,7 +27,7 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28#include "speedup.h" 28#include "speedup.h"
29 29
30#define LOG(kind,...) GNUNET_log_from (kind, "util-speedup", __VA_ARGS__) 30#define LOG(kind, ...) GNUNET_log_from(kind, "util-speedup", __VA_ARGS__)
31 31
32 32
33static struct GNUNET_TIME_Relative interval; 33static struct GNUNET_TIME_Relative interval;
@@ -38,20 +38,20 @@ static struct GNUNET_SCHEDULER_Task *speedup_task;
38 38
39 39
40static void 40static void
41do_speedup (void *cls) 41do_speedup(void *cls)
42{ 42{
43 static long long current_offset; 43 static long long current_offset;
44 44
45 (void) cls; 45 (void)cls;
46 speedup_task = NULL; 46 speedup_task = NULL;
47 current_offset += delta.rel_value_us; 47 current_offset += delta.rel_value_us;
48 GNUNET_TIME_set_offset (current_offset); 48 GNUNET_TIME_set_offset(current_offset);
49 LOG (GNUNET_ERROR_TYPE_DEBUG, 49 LOG(GNUNET_ERROR_TYPE_DEBUG,
50 "Speeding up execution time by %s\n", 50 "Speeding up execution time by %s\n",
51 GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_NO)); 51 GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_NO));
52 speedup_task = GNUNET_SCHEDULER_add_delayed (interval, 52 speedup_task = GNUNET_SCHEDULER_add_delayed(interval,
53 &do_speedup, 53 &do_speedup,
54 NULL); 54 NULL);
55} 55}
56 56
57 57
@@ -62,38 +62,38 @@ do_speedup (void *cls)
62 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the speedup was not configured 62 * @return #GNUNET_OK on success, #GNUNET_SYSERR if the speedup was not configured
63 */ 63 */
64int 64int
65GNUNET_SPEEDUP_start_ (const struct GNUNET_CONFIGURATION_Handle *cfg) 65GNUNET_SPEEDUP_start_(const struct GNUNET_CONFIGURATION_Handle *cfg)
66{ 66{
67 GNUNET_assert (NULL == speedup_task); 67 GNUNET_assert(NULL == speedup_task);
68 if (GNUNET_OK != 68 if (GNUNET_OK !=
69 GNUNET_CONFIGURATION_get_value_time (cfg, 69 GNUNET_CONFIGURATION_get_value_time(cfg,
70 "testing", 70 "testing",
71 "SPEEDUP_INTERVAL", 71 "SPEEDUP_INTERVAL",
72 &interval)) 72 &interval))
73 return GNUNET_SYSERR; 73 return GNUNET_SYSERR;
74 if (GNUNET_OK != 74 if (GNUNET_OK !=
75 GNUNET_CONFIGURATION_get_value_time (cfg, 75 GNUNET_CONFIGURATION_get_value_time(cfg,
76 "testing", 76 "testing",
77 "SPEEDUP_DELTA", 77 "SPEEDUP_DELTA",
78 &delta)) 78 &delta))
79 return GNUNET_SYSERR; 79 return GNUNET_SYSERR;
80 80
81 if ( (0 == interval.rel_value_us) || 81 if ((0 == interval.rel_value_us) ||
82 (0 == delta.rel_value_us) ) 82 (0 == delta.rel_value_us))
83 { 83 {
84 LOG (GNUNET_ERROR_TYPE_DEBUG, 84 LOG(GNUNET_ERROR_TYPE_DEBUG,
85 "Speed up disabled\n"); 85 "Speed up disabled\n");
86 return GNUNET_OK; 86 return GNUNET_OK;
87 } 87 }
88 LOG (GNUNET_ERROR_TYPE_DEBUG, 88 LOG(GNUNET_ERROR_TYPE_DEBUG,
89 "Speed up execution by %s\n", 89 "Speed up execution by %s\n",
90 GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_NO)); 90 GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_NO));
91 LOG (GNUNET_ERROR_TYPE_DEBUG, 91 LOG(GNUNET_ERROR_TYPE_DEBUG,
92 "Speed up executed every %s\n", 92 "Speed up executed every %s\n",
93 GNUNET_STRINGS_relative_time_to_string (interval, GNUNET_NO)); 93 GNUNET_STRINGS_relative_time_to_string(interval, GNUNET_NO));
94 speedup_task = GNUNET_SCHEDULER_add_now_with_lifeness (GNUNET_NO, 94 speedup_task = GNUNET_SCHEDULER_add_now_with_lifeness(GNUNET_NO,
95 &do_speedup, 95 &do_speedup,
96 NULL); 96 NULL);
97 return GNUNET_OK; 97 return GNUNET_OK;
98} 98}
99 99
@@ -102,17 +102,17 @@ GNUNET_SPEEDUP_start_ (const struct GNUNET_CONFIGURATION_Handle *cfg)
102 * Stop tasks that modify clock behavior. 102 * Stop tasks that modify clock behavior.
103 */ 103 */
104void 104void
105GNUNET_SPEEDUP_stop_ () 105GNUNET_SPEEDUP_stop_()
106{ 106{
107 if (NULL != speedup_task) 107 if (NULL != speedup_task)
108 { 108 {
109 GNUNET_SCHEDULER_cancel (speedup_task); 109 GNUNET_SCHEDULER_cancel(speedup_task);
110 speedup_task = NULL; 110 speedup_task = NULL;
111 } 111 }
112 if ( (0 != interval.rel_value_us) && 112 if ((0 != interval.rel_value_us) &&
113 (0 != delta.rel_value_us) ) 113 (0 != delta.rel_value_us))
114 LOG (GNUNET_ERROR_TYPE_DEBUG, 114 LOG(GNUNET_ERROR_TYPE_DEBUG,
115 "Stopped execution speed up\n"); 115 "Stopped execution speed up\n");
116} 116}
117 117
118/* end of speedup.c */ 118/* end of speedup.c */
diff --git a/src/util/speedup.h b/src/util/speedup.h
index 5b665133e..232d74f7d 100644
--- a/src/util/speedup.h
+++ b/src/util/speedup.h
@@ -11,17 +11,17 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/speedup.c 22 * @file util/speedup.c
23 * @brief Interface for speedup routinues 23 * @brief Interface for speedup routinues
24 * @author Sree Harsha Totakura <sreeharsha@totakura.in> 24 * @author Sree Harsha Totakura <sreeharsha@totakura.in>
25 */ 25 */
26 26
27#ifndef SPEEDUP_H_ 27#ifndef SPEEDUP_H_
@@ -34,12 +34,12 @@
34 * @return GNUNET_OK on success, GNUNET_SYSERR if the speedup was not configured 34 * @return GNUNET_OK on success, GNUNET_SYSERR if the speedup was not configured
35 */ 35 */
36int 36int
37GNUNET_SPEEDUP_start_ (const struct GNUNET_CONFIGURATION_Handle *cfg); 37GNUNET_SPEEDUP_start_(const struct GNUNET_CONFIGURATION_Handle *cfg);
38 38
39/** 39/**
40 * Stop tasks that modify clock behavior. 40 * Stop tasks that modify clock behavior.
41 */ 41 */
42void 42void
43GNUNET_SPEEDUP_stop_ (void); 43GNUNET_SPEEDUP_stop_(void);
44 44
45#endif /* SPEEDUP_H_ */ 45#endif /* SPEEDUP_H_ */
diff --git a/src/util/strings.c b/src/util/strings.c
index ef9fdd693..1b4f75ab0 100644
--- a/src/util/strings.c
+++ b/src/util/strings.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/strings.c 21 * @file util/strings.c
22 * @brief string functions 22 * @brief string functions
@@ -34,10 +34,10 @@
34#include <unistr.h> 34#include <unistr.h>
35#include <uniconv.h> 35#include <uniconv.h>
36 36
37#define LOG(kind, ...) GNUNET_log_from (kind, "util-strings", __VA_ARGS__) 37#define LOG(kind, ...) GNUNET_log_from(kind, "util-strings", __VA_ARGS__)
38 38
39#define LOG_STRERROR(kind, syscall) \ 39#define LOG_STRERROR(kind, syscall) \
40 GNUNET_log_from_strerror (kind, "util-strings", syscall) 40 GNUNET_log_from_strerror(kind, "util-strings", syscall)
41 41
42 42
43/** 43/**
@@ -62,7 +62,7 @@
62 * (or number of bytes that would have been written) 62 * (or number of bytes that would have been written)
63 */ 63 */
64size_t 64size_t
65GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...) 65GNUNET_STRINGS_buffer_fill(char *buffer, size_t size, unsigned int count, ...)
66{ 66{
67 size_t needed; 67 size_t needed;
68 size_t slen; 68 size_t slen;
@@ -70,21 +70,21 @@ GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
70 va_list ap; 70 va_list ap;
71 71
72 needed = 0; 72 needed = 0;
73 va_start (ap, count); 73 va_start(ap, count);
74 while (count > 0) 74 while (count > 0)
75 {
76 s = va_arg (ap, const char *);
77
78 slen = strlen (s) + 1;
79 if (buffer != NULL)
80 { 75 {
81 GNUNET_assert (needed + slen <= size); 76 s = va_arg(ap, const char *);
82 GNUNET_memcpy (&buffer[needed], s, slen); 77
78 slen = strlen(s) + 1;
79 if (buffer != NULL)
80 {
81 GNUNET_assert(needed + slen <= size);
82 GNUNET_memcpy(&buffer[needed], s, slen);
83 }
84 needed += slen;
85 count--;
83 } 86 }
84 needed += slen; 87 va_end(ap);
85 count--;
86 }
87 va_end (ap);
88 return needed; 88 return needed;
89} 89}
90 90
@@ -97,23 +97,23 @@ GNUNET_STRINGS_buffer_fill (char *buffer, size_t size, unsigned int count, ...)
97 * @return string representing the array of @a pids 97 * @return string representing the array of @a pids
98 */ 98 */
99char * 99char *
100GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids, 100GNUNET_STRINGS_pp2s(const struct GNUNET_PeerIdentity *pids,
101 unsigned int num_pids) 101 unsigned int num_pids)
102{ 102{
103 char *buf; 103 char *buf;
104 size_t off; 104 size_t off;
105 size_t plen = num_pids * 5 + 1; 105 size_t plen = num_pids * 5 + 1;
106 106
107 off = 0; 107 off = 0;
108 buf = GNUNET_malloc (plen); 108 buf = GNUNET_malloc(plen);
109 for (unsigned int i = 0; i < num_pids; i++) 109 for (unsigned int i = 0; i < num_pids; i++)
110 { 110 {
111 off += GNUNET_snprintf (&buf[off], 111 off += GNUNET_snprintf(&buf[off],
112 plen - off, 112 plen - off,
113 "%s%s", 113 "%s%s",
114 GNUNET_i2s (&pids[i]), 114 GNUNET_i2s(&pids[i]),
115 (i == num_pids - 1) ? "" : "-"); 115 (i == num_pids - 1) ? "" : "-");
116 } 116 }
117 return buf; 117 return buf;
118} 118}
119 119
@@ -132,10 +132,10 @@ GNUNET_STRINGS_pp2s (const struct GNUNET_PeerIdentity *pids,
132 * in the buffer, or 0 on error. 132 * in the buffer, or 0 on error.
133 */ 133 */
134unsigned int 134unsigned int
135GNUNET_STRINGS_buffer_tokenize (const char *buffer, 135GNUNET_STRINGS_buffer_tokenize(const char *buffer,
136 size_t size, 136 size_t size,
137 unsigned int count, 137 unsigned int count,
138 ...) 138 ...)
139{ 139{
140 unsigned int start; 140 unsigned int start;
141 unsigned int needed; 141 unsigned int needed;
@@ -143,24 +143,24 @@ GNUNET_STRINGS_buffer_tokenize (const char *buffer,
143 va_list ap; 143 va_list ap;
144 144
145 needed = 0; 145 needed = 0;
146 va_start (ap, count); 146 va_start(ap, count);
147 while (count > 0) 147 while (count > 0)
148 {
149 r = va_arg (ap, const char **);
150
151 start = needed;
152 while ((needed < size) && (buffer[needed] != '\0'))
153 needed++;
154 if (needed == size)
155 { 148 {
156 va_end (ap); 149 r = va_arg(ap, const char **);
157 return 0; /* error */ 150
151 start = needed;
152 while ((needed < size) && (buffer[needed] != '\0'))
153 needed++;
154 if (needed == size)
155 {
156 va_end(ap);
157 return 0; /* error */
158 }
159 *r = &buffer[start];
160 needed++; /* skip 0-termination */
161 count--;
158 } 162 }
159 *r = &buffer[start]; 163 va_end(ap);
160 needed++; /* skip 0-termination */
161 count--;
162 }
163 va_end (ap);
164 return needed; 164 return needed;
165} 165}
166 166
@@ -172,33 +172,33 @@ GNUNET_STRINGS_buffer_tokenize (const char *buffer,
172 * @return fancy representation of the size (possibly rounded) for humans 172 * @return fancy representation of the size (possibly rounded) for humans
173 */ 173 */
174char * 174char *
175GNUNET_STRINGS_byte_size_fancy (unsigned long long size) 175GNUNET_STRINGS_byte_size_fancy(unsigned long long size)
176{ 176{
177 const char *unit = _ (/* size unit */ "b"); 177 const char *unit = _(/* size unit */ "b");
178 char *ret; 178 char *ret;
179 179
180 if (size > 5 * 1024) 180 if (size > 5 * 1024)
181 {
182 size = size / 1024;
183 unit = "KiB";
184 if (size > 5 * 1024)
185 { 181 {
186 size = size / 1024; 182 size = size / 1024;
187 unit = "MiB"; 183 unit = "KiB";
188 if (size > 5 * 1024) 184 if (size > 5 * 1024)
189 {
190 size = size / 1024;
191 unit = "GiB";
192 if (size > 5 * 1024)
193 { 185 {
194 size = size / 1024; 186 size = size / 1024;
195 unit = "TiB"; 187 unit = "MiB";
188 if (size > 5 * 1024)
189 {
190 size = size / 1024;
191 unit = "GiB";
192 if (size > 5 * 1024)
193 {
194 size = size / 1024;
195 unit = "TiB";
196 }
197 }
196 } 198 }
197 }
198 } 199 }
199 } 200 ret = GNUNET_malloc(32);
200 ret = GNUNET_malloc (32); 201 GNUNET_snprintf(ret, 32, "%llu %s", size, unit);
201 GNUNET_snprintf (ret, 32, "%llu %s", size, unit);
202 return ret; 202 return ret;
203} 203}
204 204
@@ -213,16 +213,16 @@ GNUNET_STRINGS_byte_size_fancy (unsigned long long size)
213 * @param n the length of the string to copy, including its terminating null 213 * @param n the length of the string to copy, including its terminating null
214 * byte 214 * byte
215 * @return the length of the string that was copied, excluding the terminating 215 * @return the length of the string that was copied, excluding the terminating
216 * null byte 216 * null byte
217 */ 217 */
218size_t 218size_t
219GNUNET_strlcpy (char *dst, const char *src, size_t n) 219GNUNET_strlcpy(char *dst, const char *src, size_t n)
220{ 220{
221 size_t slen; 221 size_t slen;
222 222
223 GNUNET_assert (0 != n); 223 GNUNET_assert(0 != n);
224 slen = strnlen (src, n - 1); 224 slen = strnlen(src, n - 1);
225 memcpy (dst, src, slen); 225 memcpy(dst, src, slen);
226 dst[slen] = '\0'; 226 dst[slen] = '\0';
227 return slen; 227 return slen;
228} 228}
@@ -231,8 +231,7 @@ GNUNET_strlcpy (char *dst, const char *src, size_t n)
231/** 231/**
232 * Unit conversion table entry for 'convert_with_table'. 232 * Unit conversion table entry for 'convert_with_table'.
233 */ 233 */
234struct ConversionTable 234struct ConversionTable {
235{
236 /** 235 /**
237 * Name of the unit (or NULL for end of table). 236 * Name of the unit (or NULL for end of table).
238 */ 237 */
@@ -257,9 +256,9 @@ struct ConversionTable
257 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 256 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
258 */ 257 */
259static int 258static int
260convert_with_table (const char *input, 259convert_with_table(const char *input,
261 const struct ConversionTable *table, 260 const struct ConversionTable *table,
262 unsigned long long *output) 261 unsigned long long *output)
263{ 262{
264 unsigned long long ret; 263 unsigned long long ret;
265 char *in; 264 char *in;
@@ -269,40 +268,41 @@ convert_with_table (const char *input,
269 268
270 ret = 0; 269 ret = 0;
271 last = 0; 270 last = 0;
272 in = GNUNET_strdup (input); 271 in = GNUNET_strdup(input);
273 for (tok = strtok (in, " "); tok != NULL; tok = strtok (NULL, " ")) 272 for (tok = strtok(in, " "); tok != NULL; tok = strtok(NULL, " "))
274 {
275 do
276 { 273 {
277 i = 0; 274 do
278 while ((table[i].name != NULL) && (0 != strcasecmp (table[i].name, tok)))
279 i++;
280 if (table[i].name != NULL)
281 {
282 last *= table[i].value;
283 break; /* next tok */
284 }
285 else
286 {
287 char *endptr;
288 ret += last;
289 errno = 0;
290 last = strtoull (tok, &endptr, 10);
291 if ((0 != errno) || (endptr == tok))
292 { 275 {
293 GNUNET_free (in); 276 i = 0;
294 return GNUNET_SYSERR; /* expected number */ 277 while ((table[i].name != NULL) && (0 != strcasecmp(table[i].name, tok)))
278 i++;
279 if (table[i].name != NULL)
280 {
281 last *= table[i].value;
282 break; /* next tok */
283 }
284 else
285 {
286 char *endptr;
287 ret += last;
288 errno = 0;
289 last = strtoull(tok, &endptr, 10);
290 if ((0 != errno) || (endptr == tok))
291 {
292 GNUNET_free(in);
293 return GNUNET_SYSERR; /* expected number */
294 }
295 if ('\0' == endptr[0])
296 break; /* next tok */
297 else
298 tok = endptr; /* and re-check (handles times like "10s") */
299 }
295 } 300 }
296 if ('\0' == endptr[0]) 301 while (GNUNET_YES);
297 break; /* next tok */ 302 }
298 else
299 tok = endptr; /* and re-check (handles times like "10s") */
300 }
301 } while (GNUNET_YES);
302 }
303 ret += last; 303 ret += last;
304 *output = ret; 304 *output = ret;
305 GNUNET_free (in); 305 GNUNET_free(in);
306 return GNUNET_OK; 306 return GNUNET_OK;
307} 307}
308 308
@@ -315,26 +315,26 @@ convert_with_table (const char *input,
315 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 315 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
316 */ 316 */
317int 317int
318GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size, 318GNUNET_STRINGS_fancy_size_to_bytes(const char *fancy_size,
319 unsigned long long *size) 319 unsigned long long *size)
320{ 320{
321 static const struct ConversionTable table[] = 321 static const struct ConversionTable table[] =
322 {{"B", 1}, 322 { { "B", 1 },
323 {"KiB", 1024}, 323 { "KiB", 1024 },
324 {"kB", 1000}, 324 { "kB", 1000 },
325 {"MiB", 1024 * 1024}, 325 { "MiB", 1024 * 1024 },
326 {"MB", 1000 * 1000}, 326 { "MB", 1000 * 1000 },
327 {"GiB", 1024 * 1024 * 1024}, 327 { "GiB", 1024 * 1024 * 1024 },
328 {"GB", 1000 * 1000 * 1000}, 328 { "GB", 1000 * 1000 * 1000 },
329 {"TiB", 1024LL * 1024LL * 1024LL * 1024LL}, 329 { "TiB", 1024LL * 1024LL * 1024LL * 1024LL },
330 {"TB", 1000LL * 1000LL * 1000LL * 1024LL}, 330 { "TB", 1000LL * 1000LL * 1000LL * 1024LL },
331 {"PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL}, 331 { "PiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
332 {"PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL}, 332 { "PB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL },
333 {"EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL}, 333 { "EiB", 1024LL * 1024LL * 1024LL * 1024LL * 1024LL * 1024LL },
334 {"EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL}, 334 { "EB", 1000LL * 1000LL * 1000LL * 1024LL * 1000LL * 1000LL },
335 {NULL, 0}}; 335 { NULL, 0 } };
336 336
337 return convert_with_table (fancy_size, table, size); 337 return convert_with_table(fancy_size, table, size);
338} 338}
339 339
340 340
@@ -347,43 +347,43 @@ GNUNET_STRINGS_fancy_size_to_bytes (const char *fancy_size,
347 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 347 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
348 */ 348 */
349int 349int
350GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time, 350GNUNET_STRINGS_fancy_time_to_relative(const char *fancy_time,
351 struct GNUNET_TIME_Relative *rtime) 351 struct GNUNET_TIME_Relative *rtime)
352{ 352{
353 static const struct ConversionTable table[] = 353 static const struct ConversionTable table[] =
354 {{"us", 1}, 354 { { "us", 1 },
355 {"ms", 1000}, 355 { "ms", 1000 },
356 {"s", 1000 * 1000LL}, 356 { "s", 1000 * 1000LL },
357 {"second", 1000 * 1000LL}, 357 { "second", 1000 * 1000LL },
358 {"seconds", 1000 * 1000LL}, 358 { "seconds", 1000 * 1000LL },
359 {"\"", 1000 * 1000LL}, 359 { "\"", 1000 * 1000LL },
360 {"m", 60 * 1000 * 1000LL}, 360 { "m", 60 * 1000 * 1000LL },
361 {"min", 60 * 1000 * 1000LL}, 361 { "min", 60 * 1000 * 1000LL },
362 {"minute", 60 * 1000 * 1000LL}, 362 { "minute", 60 * 1000 * 1000LL },
363 {"minutes", 60 * 1000 * 1000LL}, 363 { "minutes", 60 * 1000 * 1000LL },
364 {"'", 60 * 1000 * 1000LL}, 364 { "'", 60 * 1000 * 1000LL },
365 {"h", 60 * 60 * 1000 * 1000LL}, 365 { "h", 60 * 60 * 1000 * 1000LL },
366 {"hour", 60 * 60 * 1000 * 1000LL}, 366 { "hour", 60 * 60 * 1000 * 1000LL },
367 {"hours", 60 * 60 * 1000 * 1000LL}, 367 { "hours", 60 * 60 * 1000 * 1000LL },
368 {"d", 24 * 60 * 60 * 1000LL * 1000LL}, 368 { "d", 24 * 60 * 60 * 1000LL * 1000LL },
369 {"day", 24 * 60 * 60 * 1000LL * 1000LL}, 369 { "day", 24 * 60 * 60 * 1000LL * 1000LL },
370 {"days", 24 * 60 * 60 * 1000LL * 1000LL}, 370 { "days", 24 * 60 * 60 * 1000LL * 1000LL },
371 {"week", 7 * 24 * 60 * 60 * 1000LL * 1000LL}, 371 { "week", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
372 {"weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL}, 372 { "weeks", 7 * 24 * 60 * 60 * 1000LL * 1000LL },
373 {"year", 31536000000000LL /* year */}, 373 { "year", 31536000000000LL /* year */ },
374 {"years", 31536000000000LL /* year */}, 374 { "years", 31536000000000LL /* year */ },
375 {"a", 31536000000000LL /* year */}, 375 { "a", 31536000000000LL /* year */ },
376 {NULL, 0}}; 376 { NULL, 0 } };
377 int ret; 377 int ret;
378 unsigned long long val; 378 unsigned long long val;
379 379
380 if (0 == strcasecmp ("forever", fancy_time)) 380 if (0 == strcasecmp("forever", fancy_time))
381 { 381 {
382 *rtime = GNUNET_TIME_UNIT_FOREVER_REL; 382 *rtime = GNUNET_TIME_UNIT_FOREVER_REL;
383 return GNUNET_OK; 383 return GNUNET_OK;
384 } 384 }
385 ret = convert_with_table (fancy_time, table, &val); 385 ret = convert_with_table(fancy_time, table, &val);
386 rtime->rel_value_us = (uint64_t) val; 386 rtime->rel_value_us = (uint64_t)val;
387 return ret; 387 return ret;
388} 388}
389 389
@@ -398,33 +398,33 @@ GNUNET_STRINGS_fancy_time_to_relative (const char *fancy_time,
398 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error 398 * @return #GNUNET_OK on success, #GNUNET_SYSERR on error
399 */ 399 */
400int 400int
401GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time, 401GNUNET_STRINGS_fancy_time_to_absolute(const char *fancy_time,
402 struct GNUNET_TIME_Absolute *atime) 402 struct GNUNET_TIME_Absolute *atime)
403{ 403{
404 struct tm tv; 404 struct tm tv;
405 time_t t; 405 time_t t;
406 const char *eos; 406 const char *eos;
407 407
408 if (0 == strcasecmp ("end of time", fancy_time)) 408 if (0 == strcasecmp("end of time", fancy_time))
409 { 409 {
410 *atime = GNUNET_TIME_UNIT_FOREVER_ABS; 410 *atime = GNUNET_TIME_UNIT_FOREVER_ABS;
411 return GNUNET_OK; 411 return GNUNET_OK;
412 } 412 }
413 eos = &fancy_time[strlen (fancy_time)]; 413 eos = &fancy_time[strlen(fancy_time)];
414 memset (&tv, 0, sizeof (tv)); 414 memset(&tv, 0, sizeof(tv));
415 if ((eos != strptime (fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) && 415 if ((eos != strptime(fancy_time, "%a %b %d %H:%M:%S %Y", &tv)) &&
416 (eos != strptime (fancy_time, "%c", &tv)) && 416 (eos != strptime(fancy_time, "%c", &tv)) &&
417 (eos != strptime (fancy_time, "%Ec", &tv)) && 417 (eos != strptime(fancy_time, "%Ec", &tv)) &&
418 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) && 418 (eos != strptime(fancy_time, "%Y-%m-%d %H:%M:%S", &tv)) &&
419 (eos != strptime (fancy_time, "%Y-%m-%d %H:%M", &tv)) && 419 (eos != strptime(fancy_time, "%Y-%m-%d %H:%M", &tv)) &&
420 (eos != strptime (fancy_time, "%x", &tv)) && 420 (eos != strptime(fancy_time, "%x", &tv)) &&
421 (eos != strptime (fancy_time, "%Ex", &tv)) && 421 (eos != strptime(fancy_time, "%Ex", &tv)) &&
422 (eos != strptime (fancy_time, "%Y-%m-%d", &tv)) && 422 (eos != strptime(fancy_time, "%Y-%m-%d", &tv)) &&
423 (eos != strptime (fancy_time, "%Y-%m", &tv)) && 423 (eos != strptime(fancy_time, "%Y-%m", &tv)) &&
424 (eos != strptime (fancy_time, "%Y", &tv))) 424 (eos != strptime(fancy_time, "%Y", &tv)))
425 return GNUNET_SYSERR; 425 return GNUNET_SYSERR;
426 t = mktime (&tv); 426 t = mktime(&tv);
427 atime->abs_value_us = (uint64_t) ((uint64_t) t * 1000LL * 1000LL); 427 atime->abs_value_us = (uint64_t)((uint64_t)t * 1000LL * 1000LL);
428 return GNUNET_OK; 428 return GNUNET_OK;
429} 429}
430 430
@@ -443,10 +443,10 @@ GNUNET_STRINGS_fancy_time_to_absolute (const char *fancy_time,
443 * string is returned. 443 * string is returned.
444 */ 444 */
445char * 445char *
446GNUNET_STRINGS_conv (const char *input, 446GNUNET_STRINGS_conv(const char *input,
447 size_t len, 447 size_t len,
448 const char *input_charset, 448 const char *input_charset,
449 const char *output_charset) 449 const char *output_charset)
450{ 450{
451 char *ret; 451 char *ret;
452 uint8_t *u8_string; 452 uint8_t *u8_string;
@@ -454,51 +454,51 @@ GNUNET_STRINGS_conv (const char *input,
454 size_t u8_string_length; 454 size_t u8_string_length;
455 size_t encoded_string_length; 455 size_t encoded_string_length;
456 456
457 u8_string = u8_conv_from_encoding (input_charset, 457 u8_string = u8_conv_from_encoding(input_charset,
458 iconveh_error, 458 iconveh_error,
459 input, 459 input,
460 len, 460 len,
461 NULL, 461 NULL,
462 NULL, 462 NULL,
463 &u8_string_length); 463 &u8_string_length);
464 if (NULL == u8_string) 464 if (NULL == u8_string)
465 { 465 {
466 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding"); 466 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "u8_conv_from_encoding");
467 goto fail; 467 goto fail;
468 } 468 }
469 if (0 == strcmp (output_charset, "UTF-8")) 469 if (0 == strcmp(output_charset, "UTF-8"))
470 { 470 {
471 ret = GNUNET_malloc (u8_string_length + 1); 471 ret = GNUNET_malloc(u8_string_length + 1);
472 GNUNET_memcpy (ret, u8_string, u8_string_length); 472 GNUNET_memcpy(ret, u8_string, u8_string_length);
473 ret[u8_string_length] = '\0'; 473 ret[u8_string_length] = '\0';
474 free (u8_string); 474 free(u8_string);
475 return ret; 475 return ret;
476 } 476 }
477 encoded_string = u8_conv_to_encoding (output_charset, 477 encoded_string = u8_conv_to_encoding(output_charset,
478 iconveh_error, 478 iconveh_error,
479 u8_string, 479 u8_string,
480 u8_string_length, 480 u8_string_length,
481 NULL, 481 NULL,
482 NULL, 482 NULL,
483 &encoded_string_length); 483 &encoded_string_length);
484 free (u8_string); 484 free(u8_string);
485 if (NULL == encoded_string) 485 if (NULL == encoded_string)
486 { 486 {
487 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding"); 487 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "u8_conv_to_encoding");
488 goto fail; 488 goto fail;
489 } 489 }
490 ret = GNUNET_malloc (encoded_string_length + 1); 490 ret = GNUNET_malloc(encoded_string_length + 1);
491 GNUNET_memcpy (ret, encoded_string, encoded_string_length); 491 GNUNET_memcpy(ret, encoded_string, encoded_string_length);
492 ret[encoded_string_length] = '\0'; 492 ret[encoded_string_length] = '\0';
493 free (encoded_string); 493 free(encoded_string);
494 return ret; 494 return ret;
495fail: 495fail:
496 LOG (GNUNET_ERROR_TYPE_WARNING, 496 LOG(GNUNET_ERROR_TYPE_WARNING,
497 _ ("Character sets requested were `%s'->`%s'\n"), 497 _("Character sets requested were `%s'->`%s'\n"),
498 "UTF-8", 498 "UTF-8",
499 output_charset); 499 output_charset);
500 ret = GNUNET_malloc (len + 1); 500 ret = GNUNET_malloc(len + 1);
501 GNUNET_memcpy (ret, input, len); 501 GNUNET_memcpy(ret, input, len);
502 ret[len] = '\0'; 502 ret[len] = '\0';
503 return ret; 503 return ret;
504} 504}
@@ -517,9 +517,9 @@ fail:
517 * string is returned. 517 * string is returned.
518 */ 518 */
519char * 519char *
520GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset) 520GNUNET_STRINGS_to_utf8(const char *input, size_t len, const char *charset)
521{ 521{
522 return GNUNET_STRINGS_conv (input, len, charset, "UTF-8"); 522 return GNUNET_STRINGS_conv(input, len, charset, "UTF-8");
523} 523}
524 524
525 525
@@ -535,9 +535,9 @@ GNUNET_STRINGS_to_utf8 (const char *input, size_t len, const char *charset)
535 * string is returned. 535 * string is returned.
536 */ 536 */
537char * 537char *
538GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset) 538GNUNET_STRINGS_from_utf8(const char *input, size_t len, const char *charset)
539{ 539{
540 return GNUNET_STRINGS_conv (input, len, "UTF-8", charset); 540 return GNUNET_STRINGS_conv(input, len, "UTF-8", charset);
541} 541}
542 542
543 543
@@ -549,20 +549,20 @@ GNUNET_STRINGS_from_utf8 (const char *input, size_t len, const char *charset)
549 * @param output output buffer 549 * @param output output buffer
550 */ 550 */
551void 551void
552GNUNET_STRINGS_utf8_tolower (const char *input, char *output) 552GNUNET_STRINGS_utf8_tolower(const char *input, char *output)
553{ 553{
554 uint8_t *tmp_in; 554 uint8_t *tmp_in;
555 size_t len; 555 size_t len;
556 556
557 tmp_in = u8_tolower ((uint8_t *) input, 557 tmp_in = u8_tolower((uint8_t *)input,
558 strlen ((char *) input), 558 strlen((char *)input),
559 NULL, 559 NULL,
560 UNINORM_NFD, 560 UNINORM_NFD,
561 NULL, 561 NULL,
562 &len); 562 &len);
563 GNUNET_memcpy (output, tmp_in, len); 563 GNUNET_memcpy(output, tmp_in, len);
564 output[len] = '\0'; 564 output[len] = '\0';
565 free (tmp_in); 565 free(tmp_in);
566} 566}
567 567
568 568
@@ -574,20 +574,20 @@ GNUNET_STRINGS_utf8_tolower (const char *input, char *output)
574 * @param output output buffer 574 * @param output output buffer
575 */ 575 */
576void 576void
577GNUNET_STRINGS_utf8_toupper (const char *input, char *output) 577GNUNET_STRINGS_utf8_toupper(const char *input, char *output)
578{ 578{
579 uint8_t *tmp_in; 579 uint8_t *tmp_in;
580 size_t len; 580 size_t len;
581 581
582 tmp_in = u8_toupper ((uint8_t *) input, 582 tmp_in = u8_toupper((uint8_t *)input,
583 strlen ((char *) input), 583 strlen((char *)input),
584 NULL, 584 NULL,
585 UNINORM_NFD, 585 UNINORM_NFD,
586 NULL, 586 NULL,
587 &len); 587 &len);
588 GNUNET_memcpy (output, tmp_in, len); 588 GNUNET_memcpy(output, tmp_in, len);
589 output[len] = '\0'; 589 output[len] = '\0';
590 free (tmp_in); 590 free(tmp_in);
591} 591}
592 592
593 593
@@ -599,9 +599,10 @@ GNUNET_STRINGS_utf8_toupper (const char *input, char *output)
599 * NULL is returned on error 599 * NULL is returned on error
600 */ 600 */
601char * 601char *
602GNUNET_STRINGS_filename_expand (const char *fil) 602GNUNET_STRINGS_filename_expand(const char *fil)
603{ 603{
604 char *buffer; 604 char *buffer;
605
605#ifndef MINGW 606#ifndef MINGW
606 size_t len; 607 size_t len;
607 char *fm; 608 char *fm;
@@ -617,90 +618,90 @@ GNUNET_STRINGS_filename_expand (const char *fil)
617#ifndef MINGW 618#ifndef MINGW
618 if (fil[0] == DIR_SEPARATOR) 619 if (fil[0] == DIR_SEPARATOR)
619 /* absolute path, just copy */ 620 /* absolute path, just copy */
620 return GNUNET_strdup (fil); 621 return GNUNET_strdup(fil);
621 if (fil[0] == '~') 622 if (fil[0] == '~')
622 {
623 fm = getenv ("HOME");
624 if (fm == NULL)
625 { 623 {
626 LOG (GNUNET_ERROR_TYPE_WARNING, 624 fm = getenv("HOME");
627 _ ("Failed to expand `$HOME': environment variable `HOME' not set")); 625 if (fm == NULL)
628 return NULL; 626 {
629 } 627 LOG(GNUNET_ERROR_TYPE_WARNING,
630 fm = GNUNET_strdup (fm); 628 _("Failed to expand `$HOME': environment variable `HOME' not set"));
631 /* do not copy '~' */ 629 return NULL;
632 fil_ptr = fil + 1; 630 }
631 fm = GNUNET_strdup(fm);
632 /* do not copy '~' */
633 fil_ptr = fil + 1;
633 634
634 /* skip over dir seperator to be consistent */ 635 /* skip over dir seperator to be consistent */
635 if (fil_ptr[0] == DIR_SEPARATOR) 636 if (fil_ptr[0] == DIR_SEPARATOR)
636 fil_ptr++; 637 fil_ptr++;
637 }
638 else
639 {
640 /* relative path */
641 fil_ptr = fil;
642 len = 512;
643 fm = NULL;
644 while (1)
645 {
646 buffer = GNUNET_malloc (len);
647 if (getcwd (buffer, len) != NULL)
648 {
649 fm = buffer;
650 break;
651 }
652 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
653 {
654 len *= 2;
655 GNUNET_free (buffer);
656 continue;
657 }
658 GNUNET_free (buffer);
659 break;
660 } 638 }
661 if (fm == NULL) 639 else
662 { 640 {
663 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "getcwd"); 641 /* relative path */
664 buffer = getenv ("PWD"); /* alternative */ 642 fil_ptr = fil;
665 if (buffer != NULL) 643 len = 512;
666 fm = GNUNET_strdup (buffer); 644 fm = NULL;
645 while (1)
646 {
647 buffer = GNUNET_malloc(len);
648 if (getcwd(buffer, len) != NULL)
649 {
650 fm = buffer;
651 break;
652 }
653 if ((errno == ERANGE) && (len < 1024 * 1024 * 4))
654 {
655 len *= 2;
656 GNUNET_free(buffer);
657 continue;
658 }
659 GNUNET_free(buffer);
660 break;
661 }
662 if (fm == NULL)
663 {
664 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "getcwd");
665 buffer = getenv("PWD"); /* alternative */
666 if (buffer != NULL)
667 fm = GNUNET_strdup(buffer);
668 }
669 if (fm == NULL)
670 fm = GNUNET_strdup("./"); /* give up */
667 } 671 }
668 if (fm == NULL) 672 GNUNET_asprintf(&buffer,
669 fm = GNUNET_strdup ("./"); /* give up */ 673 "%s%s%s",
670 } 674 fm,
671 GNUNET_asprintf (&buffer, 675 (fm[strlen(fm) - 1] == DIR_SEPARATOR) ? ""
672 "%s%s%s", 676 : DIR_SEPARATOR_STR,
673 fm, 677 fil_ptr);
674 (fm[strlen (fm) - 1] == DIR_SEPARATOR) ? "" 678 GNUNET_free(fm);
675 : DIR_SEPARATOR_STR,
676 fil_ptr);
677 GNUNET_free (fm);
678 return buffer; 679 return buffer;
679#else 680#else
680 fn = GNUNET_malloc (MAX_PATH + 1); 681 fn = GNUNET_malloc(MAX_PATH + 1);
681
682 if ((lRet = plibc_conv_to_win_path (fil, fn)) != ERROR_SUCCESS)
683 {
684 SetErrnoFromWinError (lRet);
685 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
686 return NULL;
687 }
688 /* is the path relative? */
689 if ((0 != strncmp (fn + 1, ":\\", 2)) && (0 != strncmp (fn, "\\\\", 2)))
690 {
691 char szCurDir[MAX_PATH + 1];
692 682
693 lRet = GetCurrentDirectory (MAX_PATH + 1, szCurDir); 683 if ((lRet = plibc_conv_to_win_path(fil, fn)) != ERROR_SUCCESS)
694 if (lRet + strlen (fn) + 1 > (MAX_PATH + 1))
695 { 684 {
696 SetErrnoFromWinError (ERROR_BUFFER_OVERFLOW); 685 SetErrnoFromWinError(lRet);
697 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory"); 686 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "plibc_conv_to_win_path");
698 return NULL; 687 return NULL;
699 } 688 }
700 GNUNET_asprintf (&buffer, "%s\\%s", szCurDir, fn); 689 /* is the path relative? */
701 GNUNET_free (fn); 690 if ((0 != strncmp(fn + 1, ":\\", 2)) && (0 != strncmp(fn, "\\\\", 2)))
702 fn = buffer; 691 {
703 } 692 char szCurDir[MAX_PATH + 1];
693
694 lRet = GetCurrentDirectory(MAX_PATH + 1, szCurDir);
695 if (lRet + strlen(fn) + 1 > (MAX_PATH + 1))
696 {
697 SetErrnoFromWinError(ERROR_BUFFER_OVERFLOW);
698 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "GetCurrentDirectory");
699 return NULL;
700 }
701 GNUNET_asprintf(&buffer, "%s\\%s", szCurDir, fn);
702 GNUNET_free(fn);
703 fn = buffer;
704 }
704 705
705 return fn; 706 return fn;
706#endif 707#endif
@@ -717,47 +718,47 @@ GNUNET_STRINGS_filename_expand (const char *fil)
717 * @return time as human-readable string 718 * @return time as human-readable string
718 */ 719 */
719const char * 720const char *
720GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta, 721GNUNET_STRINGS_relative_time_to_string(struct GNUNET_TIME_Relative delta,
721 int do_round) 722 int do_round)
722{ 723{
723 static char buf[128]; 724 static char buf[128];
724 const char *unit = _ (/* time unit */ "µs"); 725 const char *unit = _(/* time unit */ "µs");
725 uint64_t dval = delta.rel_value_us; 726 uint64_t dval = delta.rel_value_us;
726 727
727 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us) 728 if (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == delta.rel_value_us)
728 return _ ("forever"); 729 return _("forever");
729 if (0 == delta.rel_value_us) 730 if (0 == delta.rel_value_us)
730 return _ ("0 ms"); 731 return _("0 ms");
731 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000))) 732 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
732 {
733 dval = dval / 1000;
734 unit = _ (/* time unit */ "ms");
735 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
736 { 733 {
737 dval = dval / 1000; 734 dval = dval / 1000;
738 unit = _ (/* time unit */ "s"); 735 unit = _(/* time unit */ "ms");
739 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60))) 736 if (((GNUNET_YES == do_round) && (dval > 5 * 1000)) || (0 == (dval % 1000)))
740 {
741 dval = dval / 60;
742 unit = _ (/* time unit */ "m");
743 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
744 { 737 {
745 dval = dval / 60; 738 dval = dval / 1000;
746 unit = _ (/* time unit */ "h"); 739 unit = _(/* time unit */ "s");
747 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) || 740 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
748 (0 == (dval % 24))) 741 {
749 { 742 dval = dval / 60;
750 dval = dval / 24; 743 unit = _(/* time unit */ "m");
751 if (1 == dval) 744 if (((GNUNET_YES == do_round) && (dval > 5 * 60)) || (0 == (dval % 60)))
752 unit = _ (/* time unit */ "day"); 745 {
753 else 746 dval = dval / 60;
754 unit = _ (/* time unit */ "days"); 747 unit = _(/* time unit */ "h");
755 } 748 if (((GNUNET_YES == do_round) && (dval > 5 * 24)) ||
749 (0 == (dval % 24)))
750 {
751 dval = dval / 24;
752 if (1 == dval)
753 unit = _(/* time unit */ "day");
754 else
755 unit = _(/* time unit */ "days");
756 }
757 }
758 }
756 } 759 }
757 }
758 } 760 }
759 } 761 GNUNET_snprintf(buf, sizeof(buf), "%llu %s", dval, unit);
760 GNUNET_snprintf (buf, sizeof (buf), "%llu %s", dval, unit);
761 return buf; 762 return buf;
762} 763}
763 764
@@ -772,16 +773,16 @@ GNUNET_STRINGS_relative_time_to_string (struct GNUNET_TIME_Relative delta,
772 * @return timestamp in human-readable form in local time 773 * @return timestamp in human-readable form in local time
773 */ 774 */
774const char * 775const char *
775GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t) 776GNUNET_STRINGS_absolute_time_to_string(struct GNUNET_TIME_Absolute t)
776{ 777{
777 static char buf[255]; 778 static char buf[255];
778 time_t tt; 779 time_t tt;
779 struct tm *tp; 780 struct tm *tp;
780 781
781 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) 782 if (t.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
782 return _ ("end of time"); 783 return _("end of time");
783 tt = t.abs_value_us / 1000LL / 1000LL; 784 tt = t.abs_value_us / 1000LL / 1000LL;
784 tp = localtime (&tt); 785 tp = localtime(&tt);
785 /* This is hacky, but i don't know a way to detect libc character encoding. 786 /* This is hacky, but i don't know a way to detect libc character encoding.
786 * Just expect utf8 from glibc these days. 787 * Just expect utf8 from glibc these days.
787 * As for msvcrt, use the wide variant, which always returns utf16 788 * As for msvcrt, use the wide variant, which always returns utf16
@@ -789,28 +790,28 @@ GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
789 * set conversion routines to convert to UTF8). 790 * set conversion routines to convert to UTF8).
790 */ 791 */
791#ifndef WINDOWS 792#ifndef WINDOWS
792 strftime (buf, sizeof (buf), "%a %b %d %H:%M:%S %Y", tp); 793 strftime(buf, sizeof(buf), "%a %b %d %H:%M:%S %Y", tp);
793#else 794#else
794 { 795 {
795 static wchar_t wbuf[255]; 796 static wchar_t wbuf[255];
796 uint8_t *conved; 797 uint8_t *conved;
797 size_t ssize; 798 size_t ssize;
798 799
799 wcsftime (wbuf, 800 wcsftime(wbuf,
800 sizeof (wbuf) / sizeof (wchar_t), 801 sizeof(wbuf) / sizeof(wchar_t),
801 L"%a %b %d %H:%M:%S %Y", 802 L"%a %b %d %H:%M:%S %Y",
802 tp); 803 tp);
803 804
804 ssize = sizeof (buf); 805 ssize = sizeof(buf);
805 conved = u16_to_u8 (wbuf, 806 conved = u16_to_u8(wbuf,
806 sizeof (wbuf) / sizeof (wchar_t), 807 sizeof(wbuf) / sizeof(wchar_t),
807 (uint8_t *) buf, 808 (uint8_t *)buf,
808 &ssize); 809 &ssize);
809 if (conved != (uint8_t *) buf) 810 if (conved != (uint8_t *)buf)
810 { 811 {
811 GNUNET_strlcpy (buf, (char *) conved, sizeof (buf)); 812 GNUNET_strlcpy(buf, (char *)conved, sizeof(buf));
812 free (conved); 813 free(conved);
813 } 814 }
814 } 815 }
815#endif 816#endif
816 return buf; 817 return buf;
@@ -829,12 +830,12 @@ GNUNET_STRINGS_absolute_time_to_string (struct GNUNET_TIME_Absolute t)
829 * itself. 830 * itself.
830 */ 831 */
831const char * 832const char *
832GNUNET_STRINGS_get_short_name (const char *filename) 833GNUNET_STRINGS_get_short_name(const char *filename)
833{ 834{
834 const char *short_fn = filename; 835 const char *short_fn = filename;
835 const char *ss; 836 const char *ss;
836 837
837 while (NULL != (ss = strstr (short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0')) 838 while (NULL != (ss = strstr(short_fn, DIR_SEPARATOR_STR)) && (ss[1] != '\0'))
838 short_fn = 1 + ss; 839 short_fn = 1 + ss;
839 return short_fn; 840 return short_fn;
840} 841}
@@ -848,48 +849,51 @@ GNUNET_STRINGS_get_short_name (const char *filename)
848 * @return corresponding numeric value 849 * @return corresponding numeric value
849 */ 850 */
850static unsigned int 851static unsigned int
851getValue__ (unsigned char a) 852getValue__(unsigned char a)
852{ 853{
853 unsigned int dec; 854 unsigned int dec;
854 855
855 switch (a) 856 switch (a)
856 { 857 {
857 case 'O': 858 case 'O':
858 case 'o': 859 case 'o':
859 a = '0'; 860 a = '0';
860 break; 861 break;
861 case 'i': 862
862 case 'I': 863 case 'i':
863 case 'l': 864 case 'I':
864 case 'L': 865 case 'l':
865 a = '1'; 866 case 'L':
866 break; 867 a = '1';
868 break;
869
867 /* also consider U to be V */ 870 /* also consider U to be V */
868 case 'u': 871 case 'u':
869 case 'U': 872 case 'U':
870 a = 'V'; 873 a = 'V';
871 break; 874 break;
872 default: 875
873 break; 876 default:
874 } 877 break;
878 }
875 if ((a >= '0') && (a <= '9')) 879 if ((a >= '0') && (a <= '9'))
876 return a - '0'; 880 return a - '0';
877 if ((a >= 'a') && (a <= 'z')) 881 if ((a >= 'a') && (a <= 'z'))
878 a = toupper (a); 882 a = toupper(a);
879 /* return (a - 'a' + 10); */ 883 /* return (a - 'a' + 10); */
880 dec = 0; 884 dec = 0;
881 if ((a >= 'A') && (a <= 'Z')) 885 if ((a >= 'A') && (a <= 'Z'))
882 { 886 {
883 if ('I' < a) 887 if ('I' < a)
884 dec++; 888 dec++;
885 if ('L' < a) 889 if ('L' < a)
886 dec++; 890 dec++;
887 if ('O' < a) 891 if ('O' < a)
888 dec++; 892 dec++;
889 if ('U' < a) 893 if ('U' < a)
890 dec++; 894 dec++;
891 return (a - 'A' + 10 - dec); 895 return(a - 'A' + 10 - dec);
892 } 896 }
893 return -1; 897 return -1;
894} 898}
895 899
@@ -907,10 +911,10 @@ getValue__ (unsigned char a)
907 * @return pointer to the next byte in @a out or NULL on error. 911 * @return pointer to the next byte in @a out or NULL on error.
908 */ 912 */
909char * 913char *
910GNUNET_STRINGS_data_to_string (const void *data, 914GNUNET_STRINGS_data_to_string(const void *data,
911 size_t size, 915 size_t size,
912 char *out, 916 char *out,
913 size_t out_size) 917 size_t out_size)
914{ 918{
915 /** 919 /**
916 * 32 characters for encoding 920 * 32 characters for encoding
@@ -924,36 +928,36 @@ GNUNET_STRINGS_data_to_string (const void *data,
924 928
925 udata = data; 929 udata = data;
926 if (out_size < (size * 8 + 4) / 5) 930 if (out_size < (size * 8 + 4) / 5)
927 { 931 {
928 GNUNET_break (0); 932 GNUNET_break(0);
929 return NULL; 933 return NULL;
930 } 934 }
931 vbit = 0; 935 vbit = 0;
932 wpos = 0; 936 wpos = 0;
933 rpos = 0; 937 rpos = 0;
934 bits = 0; 938 bits = 0;
935 while ((rpos < size) || (vbit > 0)) 939 while ((rpos < size) || (vbit > 0))
936 {
937 if ((rpos < size) && (vbit < 5))
938 {
939 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
940 vbit += 8;
941 }
942 if (vbit < 5)
943 {
944 bits <<= (5 - vbit); /* zero-padding */
945 GNUNET_assert (vbit == ((size * 8) % 5));
946 vbit = 5;
947 }
948 if (wpos >= out_size)
949 { 940 {
950 GNUNET_break (0); 941 if ((rpos < size) && (vbit < 5))
951 return NULL; 942 {
943 bits = (bits << 8) | udata[rpos++]; /* eat 8 more bits */
944 vbit += 8;
945 }
946 if (vbit < 5)
947 {
948 bits <<= (5 - vbit); /* zero-padding */
949 GNUNET_assert(vbit == ((size * 8) % 5));
950 vbit = 5;
951 }
952 if (wpos >= out_size)
953 {
954 GNUNET_break(0);
955 return NULL;
956 }
957 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
958 vbit -= 5;
952 } 959 }
953 out[wpos++] = encTable__[(bits >> (vbit - 5)) & 31]; 960 GNUNET_assert(0 == vbit);
954 vbit -= 5;
955 }
956 GNUNET_assert (0 == vbit);
957 if (wpos < out_size) 961 if (wpos < out_size)
958 out[wpos] = '\0'; 962 out[wpos] = '\0';
959 return &out[wpos]; 963 return &out[wpos];
@@ -971,7 +975,7 @@ GNUNET_STRINGS_data_to_string (const void *data,
971 * @return freshly allocated, null-terminated string 975 * @return freshly allocated, null-terminated string
972 */ 976 */
973char * 977char *
974GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size) 978GNUNET_STRINGS_data_to_string_alloc(const void *buf, size_t size)
975{ 979{
976 char *str_buf; 980 char *str_buf;
977 size_t len = size * 8; 981 size_t len = size * 8;
@@ -980,13 +984,13 @@ GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size)
980 if (len % 5 > 0) 984 if (len % 5 > 0)
981 len += 5 - len % 5; 985 len += 5 - len % 5;
982 len /= 5; 986 len /= 5;
983 str_buf = GNUNET_malloc (len + 1); 987 str_buf = GNUNET_malloc(len + 1);
984 end = GNUNET_STRINGS_data_to_string (buf, size, str_buf, len); 988 end = GNUNET_STRINGS_data_to_string(buf, size, str_buf, len);
985 if (NULL == end) 989 if (NULL == end)
986 { 990 {
987 GNUNET_free (str_buf); 991 GNUNET_free(str_buf);
988 return NULL; 992 return NULL;
989 } 993 }
990 *end = '\0'; 994 *end = '\0';
991 return str_buf; 995 return str_buf;
992} 996}
@@ -1003,10 +1007,10 @@ GNUNET_STRINGS_data_to_string_alloc (const void *buf, size_t size)
1003 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding 1007 * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
1004 */ 1008 */
1005int 1009int
1006GNUNET_STRINGS_string_to_data (const char *enc, 1010GNUNET_STRINGS_string_to_data(const char *enc,
1007 size_t enclen, 1011 size_t enclen,
1008 void *out, 1012 void *out,
1009 size_t out_size) 1013 size_t out_size)
1010{ 1014{
1011 unsigned int rpos; 1015 unsigned int rpos;
1012 unsigned int wpos; 1016 unsigned int wpos;
@@ -1018,48 +1022,48 @@ GNUNET_STRINGS_string_to_data (const char *enc,
1018 unsigned int encoded_len = out_size * 8; 1022 unsigned int encoded_len = out_size * 8;
1019 1023
1020 if (0 == enclen) 1024 if (0 == enclen)
1021 { 1025 {
1022 if (0 == out_size) 1026 if (0 == out_size)
1023 return GNUNET_OK; 1027 return GNUNET_OK;
1024 return GNUNET_SYSERR; 1028 return GNUNET_SYSERR;
1025 } 1029 }
1026 uout = out; 1030 uout = out;
1027 wpos = out_size; 1031 wpos = out_size;
1028 rpos = enclen; 1032 rpos = enclen;
1029 if ((encoded_len % 5) > 0) 1033 if ((encoded_len % 5) > 0)
1030 { 1034 {
1031 vbit = encoded_len % 5; /* padding! */ 1035 vbit = encoded_len % 5; /* padding! */
1032 shift = 5 - vbit; 1036 shift = 5 - vbit;
1033 bits = (ret = getValue__ (enc[--rpos])) >> shift; 1037 bits = (ret = getValue__(enc[--rpos])) >> shift;
1034 } 1038 }
1035 else 1039 else
1036 { 1040 {
1037 vbit = 5; 1041 vbit = 5;
1038 shift = 0; 1042 shift = 0;
1039 bits = (ret = getValue__ (enc[--rpos])); 1043 bits = (ret = getValue__(enc[--rpos]));
1040 } 1044 }
1041 if ((encoded_len + shift) / 5 != enclen) 1045 if ((encoded_len + shift) / 5 != enclen)
1042 return GNUNET_SYSERR; 1046 return GNUNET_SYSERR;
1043 if (-1 == ret) 1047 if (-1 == ret)
1044 return GNUNET_SYSERR; 1048 return GNUNET_SYSERR;
1045 while (wpos > 0) 1049 while (wpos > 0)
1046 {
1047 if (0 == rpos)
1048 { 1050 {
1049 GNUNET_break (0); 1051 if (0 == rpos)
1050 return GNUNET_SYSERR; 1052 {
1051 } 1053 GNUNET_break(0);
1052 bits = ((ret = getValue__ (enc[--rpos])) << vbit) | bits; 1054 return GNUNET_SYSERR;
1053 if (-1 == ret) 1055 }
1054 return GNUNET_SYSERR; 1056 bits = ((ret = getValue__(enc[--rpos])) << vbit) | bits;
1055 vbit += 5; 1057 if (-1 == ret)
1056 if (vbit >= 8) 1058 return GNUNET_SYSERR;
1057 { 1059 vbit += 5;
1058 uout[--wpos] = (unsigned char) bits; 1060 if (vbit >= 8)
1059 bits >>= 8; 1061 {
1060 vbit -= 8; 1062 uout[--wpos] = (unsigned char)bits;
1063 bits >>= 8;
1064 vbit -= 8;
1065 }
1061 } 1066 }
1062 }
1063 if ((0 != rpos) || (0 != vbit)) 1067 if ((0 != rpos) || (0 != vbit))
1064 return GNUNET_SYSERR; 1068 return GNUNET_SYSERR;
1065 return GNUNET_OK; 1069 return GNUNET_OK;
@@ -1083,57 +1087,61 @@ GNUNET_STRINGS_string_to_data (const char *enc,
1083 * (if they weren't NULL). 1087 * (if they weren't NULL).
1084 */ 1088 */
1085int 1089int
1086GNUNET_STRINGS_parse_uri (const char *path, 1090GNUNET_STRINGS_parse_uri(const char *path,
1087 char **scheme_part, 1091 char **scheme_part,
1088 const char **path_part) 1092 const char **path_part)
1089{ 1093{
1090 size_t len; 1094 size_t len;
1091 size_t i; 1095 size_t i;
1092 int end; 1096 int end;
1093 int pp_state = 0; 1097 int pp_state = 0;
1094 const char *post_scheme_part = NULL; 1098 const char *post_scheme_part = NULL;
1095 len = strlen (path); 1099
1096 for (end = 0, i = 0; ! end && i < len; i++) 1100 len = strlen(path);
1097 { 1101 for (end = 0, i = 0; !end && i < len; i++)
1098 switch (pp_state)
1099 { 1102 {
1100 case 0: 1103 switch (pp_state)
1101 if ((path[i] == ':') && (i > 0)) 1104 {
1102 { 1105 case 0:
1103 pp_state += 1; 1106 if ((path[i] == ':') && (i > 0))
1104 continue; 1107 {
1105 } 1108 pp_state += 1;
1106 if (! ((path[i] >= 'A' && path[i] <= 'Z') || 1109 continue;
1107 (path[i] >= 'a' && path[i] <= 'z') || 1110 }
1108 (path[i] >= '0' && path[i] <= '9') || path[i] == '+' || 1111 if (!((path[i] >= 'A' && path[i] <= 'Z') ||
1109 path[i] == '-' || (path[i] == '.'))) 1112 (path[i] >= 'a' && path[i] <= 'z') ||
1110 end = 1; 1113 (path[i] >= '0' && path[i] <= '9') || path[i] == '+' ||
1111 break; 1114 path[i] == '-' || (path[i] == '.')))
1112 case 1: 1115 end = 1;
1113 case 2: 1116 break;
1114 if (path[i] == '/') 1117
1115 { 1118 case 1:
1116 pp_state += 1; 1119 case 2:
1117 continue; 1120 if (path[i] == '/')
1118 } 1121 {
1119 end = 1; 1122 pp_state += 1;
1120 break; 1123 continue;
1121 case 3: 1124 }
1122 post_scheme_part = &path[i]; 1125 end = 1;
1123 end = 1; 1126 break;
1124 break; 1127
1125 default: 1128 case 3:
1126 end = 1; 1129 post_scheme_part = &path[i];
1130 end = 1;
1131 break;
1132
1133 default:
1134 end = 1;
1135 }
1127 } 1136 }
1128 }
1129 if (post_scheme_part == NULL) 1137 if (post_scheme_part == NULL)
1130 return GNUNET_NO; 1138 return GNUNET_NO;
1131 if (scheme_part) 1139 if (scheme_part)
1132 { 1140 {
1133 *scheme_part = GNUNET_malloc (post_scheme_part - path + 1); 1141 *scheme_part = GNUNET_malloc(post_scheme_part - path + 1);
1134 GNUNET_memcpy (*scheme_part, path, post_scheme_part - path); 1142 GNUNET_memcpy(*scheme_part, path, post_scheme_part - path);
1135 (*scheme_part)[post_scheme_part - path] = '\0'; 1143 (*scheme_part)[post_scheme_part - path] = '\0';
1136 } 1144 }
1137 if (path_part) 1145 if (path_part)
1138 *path_part = post_scheme_part; 1146 *path_part = post_scheme_part;
1139 return GNUNET_YES; 1147 return GNUNET_YES;
@@ -1155,10 +1163,10 @@ GNUNET_STRINGS_parse_uri (const char *path,
1155 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise. 1163 * @return #GNUNET_YES if @a filename is absolute, #GNUNET_NO otherwise.
1156 */ 1164 */
1157int 1165int
1158GNUNET_STRINGS_path_is_absolute (const char *filename, 1166GNUNET_STRINGS_path_is_absolute(const char *filename,
1159 int can_be_uri, 1167 int can_be_uri,
1160 int *r_is_uri, 1168 int *r_is_uri,
1161 char **r_uri_scheme) 1169 char **r_uri_scheme)
1162{ 1170{
1163#if WINDOWS 1171#if WINDOWS
1164 size_t len; 1172 size_t len;
@@ -1172,37 +1180,37 @@ GNUNET_STRINGS_path_is_absolute (const char *filename,
1172 if (filename[0] == '/') 1180 if (filename[0] == '/')
1173 return GNUNET_YES; 1181 return GNUNET_YES;
1174 if (can_be_uri) 1182 if (can_be_uri)
1175 {
1176 is_uri = GNUNET_STRINGS_parse_uri (filename, &uri, &post_scheme_path);
1177 if (r_is_uri)
1178 *r_is_uri = is_uri;
1179 if (is_uri)
1180 { 1183 {
1181 if (r_uri_scheme) 1184 is_uri = GNUNET_STRINGS_parse_uri(filename, &uri, &post_scheme_path);
1182 *r_uri_scheme = uri; 1185 if (r_is_uri)
1183 else 1186 *r_is_uri = is_uri;
1184 GNUNET_free_non_null (uri); 1187 if (is_uri)
1188 {
1189 if (r_uri_scheme)
1190 *r_uri_scheme = uri;
1191 else
1192 GNUNET_free_non_null(uri);
1185#if WINDOWS 1193#if WINDOWS
1186 len = strlen (post_scheme_path); 1194 len = strlen(post_scheme_path);
1187 /* Special check for file:///c:/blah 1195 /* Special check for file:///c:/blah
1188 * We want to parse 'c:/', not '/c:/' 1196 * We want to parse 'c:/', not '/c:/'
1189 */ 1197 */
1190 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':') 1198 if (post_scheme_path[0] == '/' && len >= 3 && post_scheme_path[2] == ':')
1191 post_scheme_path = &post_scheme_path[1]; 1199 post_scheme_path = &post_scheme_path[1];
1192#endif 1200#endif
1193 return GNUNET_STRINGS_path_is_absolute (post_scheme_path, 1201 return GNUNET_STRINGS_path_is_absolute(post_scheme_path,
1194 GNUNET_NO, 1202 GNUNET_NO,
1195 NULL, 1203 NULL,
1196 NULL); 1204 NULL);
1205 }
1197 } 1206 }
1198 }
1199 else 1207 else
1200 { 1208 {
1201 if (r_is_uri) 1209 if (r_is_uri)
1202 *r_is_uri = GNUNET_NO; 1210 *r_is_uri = GNUNET_NO;
1203 } 1211 }
1204#if WINDOWS 1212#if WINDOWS
1205 len = strlen (filename); 1213 len = strlen(filename);
1206 if (len >= 3 && 1214 if (len >= 3 &&
1207 ((filename[0] >= 'A' && filename[0] <= 'Z') || 1215 ((filename[0] >= 'A' && filename[0] <= 'Z') ||
1208 (filename[0] >= 'a' && filename[0] <= 'z')) && 1216 (filename[0] >= 'a' && filename[0] <= 'z')) &&
@@ -1215,7 +1223,7 @@ GNUNET_STRINGS_path_is_absolute (const char *filename,
1215#if MINGW 1223#if MINGW
1216#define _IFMT 0170000 /* type of file */ 1224#define _IFMT 0170000 /* type of file */
1217#define _IFLNK 0120000 /* symbolic link */ 1225#define _IFLNK 0120000 /* symbolic link */
1218#define S_ISLNK(m) (((m) &_IFMT) == _IFLNK) 1226#define S_ISLNK(m) (((m) & _IFMT) == _IFLNK)
1219#endif 1227#endif
1220 1228
1221 1229
@@ -1228,32 +1236,33 @@ GNUNET_STRINGS_path_is_absolute (const char *filename,
1228 * fails, #GNUNET_SYSERR when a check can't be performed 1236 * fails, #GNUNET_SYSERR when a check can't be performed
1229 */ 1237 */
1230int 1238int
1231GNUNET_STRINGS_check_filename (const char *filename, 1239GNUNET_STRINGS_check_filename(const char *filename,
1232 enum GNUNET_STRINGS_FilenameCheck checks) 1240 enum GNUNET_STRINGS_FilenameCheck checks)
1233{ 1241{
1234 struct stat st; 1242 struct stat st;
1243
1235 if ((NULL == filename) || (filename[0] == '\0')) 1244 if ((NULL == filename) || (filename[0] == '\0'))
1236 return GNUNET_SYSERR; 1245 return GNUNET_SYSERR;
1237 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE)) 1246 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_ABSOLUTE))
1238 if (! GNUNET_STRINGS_path_is_absolute (filename, GNUNET_NO, NULL, NULL)) 1247 if (!GNUNET_STRINGS_path_is_absolute(filename, GNUNET_NO, NULL, NULL))
1239 return GNUNET_NO; 1248 return GNUNET_NO;
1240 if (0 != (checks & 1249 if (0 != (checks &
1241 (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY | 1250 (GNUNET_STRINGS_CHECK_EXISTS | GNUNET_STRINGS_CHECK_IS_DIRECTORY |
1242 GNUNET_STRINGS_CHECK_IS_LINK))) 1251 GNUNET_STRINGS_CHECK_IS_LINK)))
1243 {
1244 if (0 != stat (filename, &st))
1245 { 1252 {
1246 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS)) 1253 if (0 != stat(filename, &st))
1247 return GNUNET_NO; 1254 {
1248 else 1255 if (0 != (checks & GNUNET_STRINGS_CHECK_EXISTS))
1249 return GNUNET_SYSERR; 1256 return GNUNET_NO;
1257 else
1258 return GNUNET_SYSERR;
1259 }
1250 } 1260 }
1251 }
1252 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY)) 1261 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_DIRECTORY))
1253 if (! S_ISDIR (st.st_mode)) 1262 if (!S_ISDIR(st.st_mode))
1254 return GNUNET_NO; 1263 return GNUNET_NO;
1255 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK)) 1264 if (0 != (checks & GNUNET_STRINGS_CHECK_IS_LINK))
1256 if (! S_ISLNK (st.st_mode)) 1265 if (!S_ISLNK(st.st_mode))
1257 return GNUNET_NO; 1266 return GNUNET_NO;
1258 return GNUNET_YES; 1267 return GNUNET_YES;
1259} 1268}
@@ -1272,9 +1281,9 @@ GNUNET_STRINGS_check_filename (const char *filename,
1272 * case the contents of @a r_buf are undefined. 1281 * case the contents of @a r_buf are undefined.
1273 */ 1282 */
1274int 1283int
1275GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr, 1284GNUNET_STRINGS_to_address_ipv6(const char *zt_addr,
1276 uint16_t addrlen, 1285 uint16_t addrlen,
1277 struct sockaddr_in6 *r_buf) 1286 struct sockaddr_in6 *r_buf)
1278{ 1287{
1279 char zbuf[addrlen + 1]; 1288 char zbuf[addrlen + 1];
1280 int ret; 1289 int ret;
@@ -1284,51 +1293,51 @@ GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1284 1293
1285 if (addrlen < 6) 1294 if (addrlen < 6)
1286 return GNUNET_SYSERR; 1295 return GNUNET_SYSERR;
1287 GNUNET_memcpy (zbuf, zt_addr, addrlen); 1296 GNUNET_memcpy(zbuf, zt_addr, addrlen);
1288 if ('[' != zbuf[0]) 1297 if ('[' != zbuf[0])
1289 { 1298 {
1290 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 1299 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1291 _ ("IPv6 address did not start with `['\n")); 1300 _("IPv6 address did not start with `['\n"));
1292 return GNUNET_SYSERR; 1301 return GNUNET_SYSERR;
1293 } 1302 }
1294 zbuf[addrlen] = '\0'; 1303 zbuf[addrlen] = '\0';
1295 port_colon = strrchr (zbuf, ':'); 1304 port_colon = strrchr(zbuf, ':');
1296 if (NULL == port_colon) 1305 if (NULL == port_colon)
1297 { 1306 {
1298 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 1307 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1299 _ ("IPv6 address did contain ':' to separate port number\n")); 1308 _("IPv6 address did contain ':' to separate port number\n"));
1300 return GNUNET_SYSERR; 1309 return GNUNET_SYSERR;
1301 } 1310 }
1302 if (']' != *(port_colon - 1)) 1311 if (']' != *(port_colon - 1))
1303 { 1312 {
1304 GNUNET_log ( 1313 GNUNET_log(
1305 GNUNET_ERROR_TYPE_WARNING, 1314 GNUNET_ERROR_TYPE_WARNING,
1306 _ ("IPv6 address did contain ']' before ':' to separate port number\n")); 1315 _("IPv6 address did contain ']' before ':' to separate port number\n"));
1307 return GNUNET_SYSERR; 1316 return GNUNET_SYSERR;
1308 } 1317 }
1309 ret = sscanf (port_colon, ":%u%1s", &port, dummy); 1318 ret = sscanf(port_colon, ":%u%1s", &port, dummy);
1310 if ((1 != ret) || (port > 65535)) 1319 if ((1 != ret) || (port > 65535))
1311 { 1320 {
1312 GNUNET_log ( 1321 GNUNET_log(
1313 GNUNET_ERROR_TYPE_WARNING, 1322 GNUNET_ERROR_TYPE_WARNING,
1314 _ ("IPv6 address did contain a valid port number after the last ':'\n")); 1323 _("IPv6 address did contain a valid port number after the last ':'\n"));
1315 return GNUNET_SYSERR; 1324 return GNUNET_SYSERR;
1316 } 1325 }
1317 *(port_colon - 1) = '\0'; 1326 *(port_colon - 1) = '\0';
1318 memset (r_buf, 0, sizeof (struct sockaddr_in6)); 1327 memset(r_buf, 0, sizeof(struct sockaddr_in6));
1319 ret = inet_pton (AF_INET6, &zbuf[1], &r_buf->sin6_addr); 1328 ret = inet_pton(AF_INET6, &zbuf[1], &r_buf->sin6_addr);
1320 if (ret <= 0) 1329 if (ret <= 0)
1321 { 1330 {
1322 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 1331 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1323 _ ("Invalid IPv6 address `%s': %s\n"), 1332 _("Invalid IPv6 address `%s': %s\n"),
1324 &zbuf[1], 1333 &zbuf[1],
1325 strerror (errno)); 1334 strerror(errno));
1326 return GNUNET_SYSERR; 1335 return GNUNET_SYSERR;
1327 } 1336 }
1328 r_buf->sin6_port = htons (port); 1337 r_buf->sin6_port = htons(port);
1329 r_buf->sin6_family = AF_INET6; 1338 r_buf->sin6_family = AF_INET6;
1330#if HAVE_SOCKADDR_IN_SIN_LEN 1339#if HAVE_SOCKADDR_IN_SIN_LEN
1331 r_buf->sin6_len = (u_char) sizeof (struct sockaddr_in6); 1340 r_buf->sin6_len = (u_char)sizeof(struct sockaddr_in6);
1332#endif 1341#endif
1333 return GNUNET_OK; 1342 return GNUNET_OK;
1334} 1343}
@@ -1346,9 +1355,9 @@ GNUNET_STRINGS_to_address_ipv6 (const char *zt_addr,
1346 * the contents of @a r_buf are undefined. 1355 * the contents of @a r_buf are undefined.
1347 */ 1356 */
1348int 1357int
1349GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr, 1358GNUNET_STRINGS_to_address_ipv4(const char *zt_addr,
1350 uint16_t addrlen, 1359 uint16_t addrlen,
1351 struct sockaddr_in *r_buf) 1360 struct sockaddr_in *r_buf)
1352{ 1361{
1353 unsigned int temps[4]; 1362 unsigned int temps[4];
1354 unsigned int port; 1363 unsigned int port;
@@ -1357,14 +1366,14 @@ GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1357 1366
1358 if (addrlen < 9) 1367 if (addrlen < 9)
1359 return GNUNET_SYSERR; 1368 return GNUNET_SYSERR;
1360 cnt = sscanf (zt_addr, 1369 cnt = sscanf(zt_addr,
1361 "%u.%u.%u.%u:%u%1s", 1370 "%u.%u.%u.%u:%u%1s",
1362 &temps[0], 1371 &temps[0],
1363 &temps[1], 1372 &temps[1],
1364 &temps[2], 1373 &temps[2],
1365 &temps[3], 1374 &temps[3],
1366 &port, 1375 &port,
1367 dummy); 1376 dummy);
1368 if (5 != cnt) 1377 if (5 != cnt)
1369 return GNUNET_SYSERR; 1378 return GNUNET_SYSERR;
1370 for (cnt = 0; cnt < 4; cnt++) 1379 for (cnt = 0; cnt < 4; cnt++)
@@ -1373,11 +1382,11 @@ GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1373 if (port > 65535) 1382 if (port > 65535)
1374 return GNUNET_SYSERR; 1383 return GNUNET_SYSERR;
1375 r_buf->sin_family = AF_INET; 1384 r_buf->sin_family = AF_INET;
1376 r_buf->sin_port = htons (port); 1385 r_buf->sin_port = htons(port);
1377 r_buf->sin_addr.s_addr = 1386 r_buf->sin_addr.s_addr =
1378 htonl ((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]); 1387 htonl((temps[0] << 24) + (temps[1] << 16) + (temps[2] << 8) + temps[3]);
1379#if HAVE_SOCKADDR_IN_SIN_LEN 1388#if HAVE_SOCKADDR_IN_SIN_LEN
1380 r_buf->sin_len = (u_char) sizeof (struct sockaddr_in); 1389 r_buf->sin_len = (u_char)sizeof(struct sockaddr_in);
1381#endif 1390#endif
1382 return GNUNET_OK; 1391 return GNUNET_OK;
1383} 1392}
@@ -1395,17 +1404,17 @@ GNUNET_STRINGS_to_address_ipv4 (const char *zt_addr,
1395 * case the contents of @a r_buf are undefined. 1404 * case the contents of @a r_buf are undefined.
1396 */ 1405 */
1397int 1406int
1398GNUNET_STRINGS_to_address_ip (const char *addr, 1407GNUNET_STRINGS_to_address_ip(const char *addr,
1399 uint16_t addrlen, 1408 uint16_t addrlen,
1400 struct sockaddr_storage *r_buf) 1409 struct sockaddr_storage *r_buf)
1401{ 1410{
1402 if (addr[0] == '[') 1411 if (addr[0] == '[')
1403 return GNUNET_STRINGS_to_address_ipv6 (addr, 1412 return GNUNET_STRINGS_to_address_ipv6(addr,
1404 addrlen, 1413 addrlen,
1405 (struct sockaddr_in6 *) r_buf); 1414 (struct sockaddr_in6 *)r_buf);
1406 return GNUNET_STRINGS_to_address_ipv4 (addr, 1415 return GNUNET_STRINGS_to_address_ipv4(addr,
1407 addrlen, 1416 addrlen,
1408 (struct sockaddr_in *) r_buf); 1417 (struct sockaddr_in *)r_buf);
1409} 1418}
1410 1419
1411 1420
@@ -1419,49 +1428,49 @@ GNUNET_STRINGS_to_address_ip (const char *addr,
1419 * @return 0 on error, otherwise number of bytes in @a sa 1428 * @return 0 on error, otherwise number of bytes in @a sa
1420 */ 1429 */
1421size_t 1430size_t
1422GNUNET_STRINGS_parse_socket_addr (const char *addr, 1431GNUNET_STRINGS_parse_socket_addr(const char *addr,
1423 uint8_t *af, 1432 uint8_t *af,
1424 struct sockaddr **sa) 1433 struct sockaddr **sa)
1425{ 1434{
1426 char *cp = GNUNET_strdup (addr); 1435 char *cp = GNUNET_strdup(addr);
1427 1436
1428 *af = AF_UNSPEC; 1437 *af = AF_UNSPEC;
1429 if ('[' == *addr) 1438 if ('[' == *addr)
1430 {
1431 /* IPv6 */
1432 *sa = GNUNET_malloc (sizeof (struct sockaddr_in6));
1433 if (GNUNET_OK !=
1434 GNUNET_STRINGS_to_address_ipv6 (cp,
1435 strlen (cp),
1436 (struct sockaddr_in6 *) *sa))
1437 { 1439 {
1438 GNUNET_free (*sa); 1440 /* IPv6 */
1439 *sa = NULL; 1441 *sa = GNUNET_malloc(sizeof(struct sockaddr_in6));
1440 GNUNET_free (cp); 1442 if (GNUNET_OK !=
1441 return 0; 1443 GNUNET_STRINGS_to_address_ipv6(cp,
1444 strlen(cp),
1445 (struct sockaddr_in6 *)*sa))
1446 {
1447 GNUNET_free(*sa);
1448 *sa = NULL;
1449 GNUNET_free(cp);
1450 return 0;
1451 }
1452 *af = AF_INET6;
1453 GNUNET_free(cp);
1454 return sizeof(struct sockaddr_in6);
1442 } 1455 }
1443 *af = AF_INET6;
1444 GNUNET_free (cp);
1445 return sizeof (struct sockaddr_in6);
1446 }
1447 else 1456 else
1448 {
1449 /* IPv4 */
1450 *sa = GNUNET_malloc (sizeof (struct sockaddr_in));
1451 if (GNUNET_OK !=
1452 GNUNET_STRINGS_to_address_ipv4 (cp,
1453 strlen (cp),
1454 (struct sockaddr_in *) *sa))
1455 { 1457 {
1456 GNUNET_free (*sa); 1458 /* IPv4 */
1457 *sa = NULL; 1459 *sa = GNUNET_malloc(sizeof(struct sockaddr_in));
1458 GNUNET_free (cp); 1460 if (GNUNET_OK !=
1459 return 0; 1461 GNUNET_STRINGS_to_address_ipv4(cp,
1462 strlen(cp),
1463 (struct sockaddr_in *)*sa))
1464 {
1465 GNUNET_free(*sa);
1466 *sa = NULL;
1467 GNUNET_free(cp);
1468 return 0;
1469 }
1470 *af = AF_INET;
1471 GNUNET_free(cp);
1472 return sizeof(struct sockaddr_in);
1460 } 1473 }
1461 *af = AF_INET;
1462 GNUNET_free (cp);
1463 return sizeof (struct sockaddr_in);
1464 }
1465} 1474}
1466 1475
1467 1476
@@ -1470,24 +1479,25 @@ GNUNET_STRINGS_parse_socket_addr (const char *addr,
1470 * freed with a single call to GNUNET_free(); 1479 * freed with a single call to GNUNET_free();
1471 */ 1480 */
1472static char *const * 1481static char *const *
1473_make_continuous_arg_copy (int argc, char *const *argv) 1482_make_continuous_arg_copy(int argc, char *const *argv)
1474{ 1483{
1475 size_t argvsize = 0; 1484 size_t argvsize = 0;
1476 int i; 1485 int i;
1477 char **new_argv; 1486 char **new_argv;
1478 char *p; 1487 char *p;
1488
1479 for (i = 0; i < argc; i++) 1489 for (i = 0; i < argc; i++)
1480 argvsize += strlen (argv[i]) + 1 + sizeof (char *); 1490 argvsize += strlen(argv[i]) + 1 + sizeof(char *);
1481 new_argv = GNUNET_malloc (argvsize + sizeof (char *)); 1491 new_argv = GNUNET_malloc(argvsize + sizeof(char *));
1482 p = (char *) &new_argv[argc + 1]; 1492 p = (char *)&new_argv[argc + 1];
1483 for (i = 0; i < argc; i++) 1493 for (i = 0; i < argc; i++)
1484 { 1494 {
1485 new_argv[i] = p; 1495 new_argv[i] = p;
1486 strcpy (p, argv[i]); 1496 strcpy(p, argv[i]);
1487 p += strlen (argv[i]) + 1; 1497 p += strlen(argv[i]) + 1;
1488 } 1498 }
1489 new_argv[argc] = NULL; 1499 new_argv[argc] = NULL;
1490 return (char *const *) new_argv; 1500 return (char *const *)new_argv;
1491} 1501}
1492 1502
1493 1503
@@ -1506,10 +1516,10 @@ _make_continuous_arg_copy (int argc, char *const *argv)
1506 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure 1516 * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1507 */ 1517 */
1508int 1518int
1509GNUNET_STRINGS_get_utf8_args (int argc, 1519GNUNET_STRINGS_get_utf8_args(int argc,
1510 char *const *argv, 1520 char *const *argv,
1511 int *u8argc, 1521 int *u8argc,
1512 char *const **u8argv) 1522 char *const **u8argv)
1513{ 1523{
1514#if WINDOWS 1524#if WINDOWS
1515 wchar_t *wcmd; 1525 wchar_t *wcmd;
@@ -1518,42 +1528,42 @@ GNUNET_STRINGS_get_utf8_args (int argc,
1518 int i; 1528 int i;
1519 char **split_u8argv; 1529 char **split_u8argv;
1520 1530
1521 wcmd = GetCommandLineW (); 1531 wcmd = GetCommandLineW();
1522 if (NULL == wcmd) 1532 if (NULL == wcmd)
1523 return GNUNET_SYSERR; 1533 return GNUNET_SYSERR;
1524 wargv = CommandLineToArgvW (wcmd, &wargc); 1534 wargv = CommandLineToArgvW(wcmd, &wargc);
1525 if (NULL == wargv) 1535 if (NULL == wargv)
1526 return GNUNET_SYSERR; 1536 return GNUNET_SYSERR;
1527 1537
1528 split_u8argv = GNUNET_malloc (argc * sizeof (char *)); 1538 split_u8argv = GNUNET_malloc(argc * sizeof(char *));
1529 1539
1530 for (i = 0; i < wargc; i++) 1540 for (i = 0; i < wargc; i++)
1531 {
1532 size_t strl;
1533 /* Hopefully it will allocate us NUL-terminated strings... */
1534 split_u8argv[i] =
1535 (char *) u16_to_u8 (wargv[i], wcslen (wargv[i]) + 1, NULL, &strl);
1536 if (NULL == split_u8argv[i])
1537 { 1541 {
1538 int j; 1542 size_t strl;
1539 for (j = 0; j < i; j++) 1543 /* Hopefully it will allocate us NUL-terminated strings... */
1540 free (split_u8argv[j]); 1544 split_u8argv[i] =
1541 GNUNET_free (split_u8argv); 1545 (char *)u16_to_u8(wargv[i], wcslen(wargv[i]) + 1, NULL, &strl);
1542 LocalFree (wargv); 1546 if (NULL == split_u8argv[i])
1543 return GNUNET_SYSERR; 1547 {
1548 int j;
1549 for (j = 0; j < i; j++)
1550 free(split_u8argv[j]);
1551 GNUNET_free(split_u8argv);
1552 LocalFree(wargv);
1553 return GNUNET_SYSERR;
1554 }
1544 } 1555 }
1545 }
1546 1556
1547 *u8argv = _make_continuous_arg_copy (wargc, split_u8argv); 1557 *u8argv = _make_continuous_arg_copy(wargc, split_u8argv);
1548 *u8argc = wargc; 1558 *u8argc = wargc;
1549 1559
1550 for (i = 0; i < wargc; i++) 1560 for (i = 0; i < wargc; i++)
1551 free (split_u8argv[i]); 1561 free(split_u8argv[i]);
1552 free (split_u8argv); 1562 free(split_u8argv);
1553 return GNUNET_OK; 1563 return GNUNET_OK;
1554#else 1564#else
1555 char *const *new_argv = 1565 char *const *new_argv =
1556 (char *const *) _make_continuous_arg_copy (argc, argv); 1566 (char *const *)_make_continuous_arg_copy(argc, argv);
1557 *u8argv = new_argv; 1567 *u8argv = new_argv;
1558 *u8argc = argc; 1568 *u8argc = argc;
1559 return GNUNET_OK; 1569 return GNUNET_OK;
@@ -1571,8 +1581,8 @@ GNUNET_STRINGS_get_utf8_args (int argc,
1571 * @a port_policy is malformed 1581 * @a port_policy is malformed
1572 */ 1582 */
1573static int 1583static int
1574parse_port_policy (const char *port_policy, 1584parse_port_policy(const char *port_policy,
1575 struct GNUNET_STRINGS_PortPolicy *pp) 1585 struct GNUNET_STRINGS_PortPolicy *pp)
1576{ 1586{
1577 const char *pos; 1587 const char *pos;
1578 int s; 1588 int s;
@@ -1581,36 +1591,36 @@ parse_port_policy (const char *port_policy,
1581 1591
1582 pos = port_policy; 1592 pos = port_policy;
1583 if ('!' == *pos) 1593 if ('!' == *pos)
1584 {
1585 pp->negate_portrange = GNUNET_YES;
1586 pos++;
1587 }
1588 if (2 == sscanf (pos, "%u-%u%1s", &s, &e, eol))
1589 {
1590 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1591 { 1594 {
1592 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n")); 1595 pp->negate_portrange = GNUNET_YES;
1593 return GNUNET_SYSERR; 1596 pos++;
1594 } 1597 }
1595 pp->start_port = (uint16_t) s; 1598 if (2 == sscanf(pos, "%u-%u%1s", &s, &e, eol))
1596 pp->end_port = (uint16_t) e;
1597 return GNUNET_OK;
1598 }
1599 if (1 == sscanf (pos, "%u%1s", &s, eol))
1600 {
1601 if ((0 == s) || (s > 0xFFFF))
1602 { 1599 {
1603 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, _ ("Port not in range\n")); 1600 if ((0 == s) || (s > 0xFFFF) || (e < s) || (e > 0xFFFF))
1604 return GNUNET_SYSERR; 1601 {
1602 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("Port not in range\n"));
1603 return GNUNET_SYSERR;
1604 }
1605 pp->start_port = (uint16_t)s;
1606 pp->end_port = (uint16_t)e;
1607 return GNUNET_OK;
1605 } 1608 }
1609 if (1 == sscanf(pos, "%u%1s", &s, eol))
1610 {
1611 if ((0 == s) || (s > 0xFFFF))
1612 {
1613 GNUNET_log(GNUNET_ERROR_TYPE_WARNING, _("Port not in range\n"));
1614 return GNUNET_SYSERR;
1615 }
1606 1616
1607 pp->start_port = (uint16_t) s; 1617 pp->start_port = (uint16_t)s;
1608 pp->end_port = (uint16_t) s; 1618 pp->end_port = (uint16_t)s;
1609 return GNUNET_OK; 1619 return GNUNET_OK;
1610 } 1620 }
1611 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 1621 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
1612 _ ("Malformed port policy `%s'\n"), 1622 _("Malformed port policy `%s'\n"),
1613 port_policy); 1623 port_policy);
1614 return GNUNET_SYSERR; 1624 return GNUNET_SYSERR;
1615} 1625}
1616 1626
@@ -1628,7 +1638,7 @@ parse_port_policy (const char *port_policy,
1628 * NULL if the synatx is flawed 1638 * NULL if the synatx is flawed
1629 */ 1639 */
1630struct GNUNET_STRINGS_IPv4NetworkPolicy * 1640struct GNUNET_STRINGS_IPv4NetworkPolicy *
1631GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX) 1641GNUNET_STRINGS_parse_ipv4_policy(const char *routeListX)
1632{ 1642{
1633 unsigned int count; 1643 unsigned int count;
1634 unsigned int i; 1644 unsigned int i;
@@ -1646,164 +1656,164 @@ GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1646 1656
1647 if (NULL == routeListX) 1657 if (NULL == routeListX)
1648 return NULL; 1658 return NULL;
1649 len = strlen (routeListX); 1659 len = strlen(routeListX);
1650 if (0 == len) 1660 if (0 == len)
1651 return NULL; 1661 return NULL;
1652 routeList = GNUNET_strdup (routeListX); 1662 routeList = GNUNET_strdup(routeListX);
1653 count = 0; 1663 count = 0;
1654 for (i = 0; i < len; i++) 1664 for (i = 0; i < len; i++)
1655 if (routeList[i] == ';') 1665 if (routeList[i] == ';')
1656 count++; 1666 count++;
1657 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv4NetworkPolicy) * 1667 result = GNUNET_malloc(sizeof(struct GNUNET_STRINGS_IPv4NetworkPolicy) *
1658 (count + 1)); 1668 (count + 1));
1659 i = 0; 1669 i = 0;
1660 pos = 0; 1670 pos = 0;
1661 while (i < count) 1671 while (i < count)
1662 {
1663 for (colon = pos; ':' != routeList[colon]; colon++)
1664 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1665 break;
1666 for (end = colon; ';' != routeList[end]; end++)
1667 if ('\0' == routeList[end])
1668 break;
1669 if ('\0' == routeList[end])
1670 break;
1671 routeList[end] = '\0';
1672 if (':' == routeList[colon])
1673 { 1672 {
1674 routeList[colon] = '\0'; 1673 for (colon = pos; ':' != routeList[colon]; colon++)
1675 if (GNUNET_OK != parse_port_policy (&routeList[colon + 1], &result[i].pp)) 1674 if ((';' == routeList[colon]) || ('\0' == routeList[colon]))
1675 break;
1676 for (end = colon; ';' != routeList[end]; end++)
1677 if ('\0' == routeList[end])
1678 break;
1679 if ('\0' == routeList[end])
1676 break; 1680 break;
1677 } 1681 routeList[end] = '\0';
1678 cnt = sscanf (&routeList[pos], 1682 if (':' == routeList[colon])
1679 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1680 &temps[0],
1681 &temps[1],
1682 &temps[2],
1683 &temps[3],
1684 &temps[4],
1685 &temps[5],
1686 &temps[6],
1687 &temps[7],
1688 dummy);
1689 if (8 == cnt)
1690 {
1691 for (j = 0; j < 8; j++)
1692 if (temps[j] > 0xFF)
1693 { 1683 {
1694 LOG (GNUNET_ERROR_TYPE_WARNING, 1684 routeList[colon] = '\0';
1695 _ ("Invalid format for IP: `%s'\n"), 1685 if (GNUNET_OK != parse_port_policy(&routeList[colon + 1], &result[i].pp))
1696 &routeList[pos]); 1686 break;
1697 GNUNET_free (result);
1698 GNUNET_free (routeList);
1699 return NULL;
1700 } 1687 }
1701 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) + 1688 cnt = sscanf(&routeList[pos],
1702 (temps[2] << 8) + temps[3]); 1689 "%u.%u.%u.%u/%u.%u.%u.%u%1s",
1703 result[i].netmask.s_addr = htonl ((temps[4] << 24) + (temps[5] << 16) + 1690 &temps[0],
1704 (temps[6] << 8) + temps[7]); 1691 &temps[1],
1705 pos = end + 1; 1692 &temps[2],
1706 i++; 1693 &temps[3],
1707 continue; 1694 &temps[4],
1708 } 1695 &temps[5],
1709 /* try second notation */ 1696 &temps[6],
1710 cnt = sscanf (&routeList[pos], 1697 &temps[7],
1711 "%u.%u.%u.%u/%u%1s", 1698 dummy);
1712 &temps[0], 1699 if (8 == cnt)
1713 &temps[1],
1714 &temps[2],
1715 &temps[3],
1716 &slash,
1717 dummy);
1718 if (5 == cnt)
1719 {
1720 for (j = 0; j < 4; j++)
1721 if (temps[j] > 0xFF)
1722 { 1700 {
1723 LOG (GNUNET_ERROR_TYPE_WARNING, 1701 for (j = 0; j < 8; j++)
1724 _ ("Invalid format for IP: `%s'\n"), 1702 if (temps[j] > 0xFF)
1725 &routeList[pos]); 1703 {
1726 GNUNET_free (result); 1704 LOG(GNUNET_ERROR_TYPE_WARNING,
1727 GNUNET_free (routeList); 1705 _("Invalid format for IP: `%s'\n"),
1728 return NULL; 1706 &routeList[pos]);
1707 GNUNET_free(result);
1708 GNUNET_free(routeList);
1709 return NULL;
1710 }
1711 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1712 (temps[2] << 8) + temps[3]);
1713 result[i].netmask.s_addr = htonl((temps[4] << 24) + (temps[5] << 16) +
1714 (temps[6] << 8) + temps[7]);
1715 pos = end + 1;
1716 i++;
1717 continue;
1729 } 1718 }
1730 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) + 1719 /* try second notation */
1731 (temps[2] << 8) + temps[3]); 1720 cnt = sscanf(&routeList[pos],
1732 if ((slash <= 32) && (slash >= 0)) 1721 "%u.%u.%u.%u/%u%1s",
1733 { 1722 &temps[0],
1734 result[i].netmask.s_addr = 0; 1723 &temps[1],
1735 while (slash > 0) 1724 &temps[2],
1725 &temps[3],
1726 &slash,
1727 dummy);
1728 if (5 == cnt)
1736 { 1729 {
1737 result[i].netmask.s_addr = 1730 for (j = 0; j < 4; j++)
1738 (result[i].netmask.s_addr >> 1) + 0x80000000; 1731 if (temps[j] > 0xFF)
1739 slash--; 1732 {
1733 LOG(GNUNET_ERROR_TYPE_WARNING,
1734 _("Invalid format for IP: `%s'\n"),
1735 &routeList[pos]);
1736 GNUNET_free(result);
1737 GNUNET_free(routeList);
1738 return NULL;
1739 }
1740 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1741 (temps[2] << 8) + temps[3]);
1742 if ((slash <= 32) && (slash >= 0))
1743 {
1744 result[i].netmask.s_addr = 0;
1745 while (slash > 0)
1746 {
1747 result[i].netmask.s_addr =
1748 (result[i].netmask.s_addr >> 1) + 0x80000000;
1749 slash--;
1750 }
1751 result[i].netmask.s_addr = htonl(result[i].netmask.s_addr);
1752 pos = end + 1;
1753 i++;
1754 continue;
1755 }
1756 else
1757 {
1758 LOG(GNUNET_ERROR_TYPE_WARNING,
1759 _("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."),
1760 slash);
1761 GNUNET_free(result);
1762 GNUNET_free(routeList);
1763 return NULL; /* error */
1764 }
1740 } 1765 }
1741 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr); 1766 /* try third notation */
1742 pos = end + 1; 1767 slash = 32;
1743 i++; 1768 cnt = sscanf(&routeList[pos],
1744 continue; 1769 "%u.%u.%u.%u%1s",
1745 } 1770 &temps[0],
1746 else 1771 &temps[1],
1747 { 1772 &temps[2],
1748 LOG (GNUNET_ERROR_TYPE_WARNING, 1773 &temps[3],
1749 _ ("Invalid network notation ('/%d' is not legal in IPv4 CIDR)."), 1774 dummy);
1750 slash); 1775 if (4 == cnt)
1751 GNUNET_free (result);
1752 GNUNET_free (routeList);
1753 return NULL; /* error */
1754 }
1755 }
1756 /* try third notation */
1757 slash = 32;
1758 cnt = sscanf (&routeList[pos],
1759 "%u.%u.%u.%u%1s",
1760 &temps[0],
1761 &temps[1],
1762 &temps[2],
1763 &temps[3],
1764 dummy);
1765 if (4 == cnt)
1766 {
1767 for (j = 0; j < 4; j++)
1768 if (temps[j] > 0xFF)
1769 { 1776 {
1770 LOG (GNUNET_ERROR_TYPE_WARNING, 1777 for (j = 0; j < 4; j++)
1771 _ ("Invalid format for IP: `%s'\n"), 1778 if (temps[j] > 0xFF)
1772 &routeList[pos]); 1779 {
1773 GNUNET_free (result); 1780 LOG(GNUNET_ERROR_TYPE_WARNING,
1774 GNUNET_free (routeList); 1781 _("Invalid format for IP: `%s'\n"),
1775 return NULL; 1782 &routeList[pos]);
1783 GNUNET_free(result);
1784 GNUNET_free(routeList);
1785 return NULL;
1786 }
1787 result[i].network.s_addr = htonl((temps[0] << 24) + (temps[1] << 16) +
1788 (temps[2] << 8) + temps[3]);
1789 result[i].netmask.s_addr = 0;
1790 while (slash > 0)
1791 {
1792 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000;
1793 slash--;
1794 }
1795 result[i].netmask.s_addr = htonl(result[i].netmask.s_addr);
1796 pos = end + 1;
1797 i++;
1798 continue;
1776 } 1799 }
1777 result[i].network.s_addr = htonl ((temps[0] << 24) + (temps[1] << 16) + 1800 LOG(GNUNET_ERROR_TYPE_WARNING,
1778 (temps[2] << 8) + temps[3]); 1801 _("Invalid format for IP: `%s'\n"),
1779 result[i].netmask.s_addr = 0; 1802 &routeList[pos]);
1780 while (slash > 0) 1803 GNUNET_free(result);
1781 { 1804 GNUNET_free(routeList);
1782 result[i].netmask.s_addr = (result[i].netmask.s_addr >> 1) + 0x80000000; 1805 return NULL; /* error */
1783 slash--;
1784 }
1785 result[i].netmask.s_addr = htonl (result[i].netmask.s_addr);
1786 pos = end + 1;
1787 i++;
1788 continue;
1789 } 1806 }
1790 LOG (GNUNET_ERROR_TYPE_WARNING, 1807 if (pos < strlen(routeList))
1791 _ ("Invalid format for IP: `%s'\n"), 1808 {
1792 &routeList[pos]); 1809 LOG(GNUNET_ERROR_TYPE_WARNING,
1793 GNUNET_free (result); 1810 _("Invalid format: `%s'\n"),
1794 GNUNET_free (routeList); 1811 &routeListX[pos]);
1795 return NULL; /* error */ 1812 GNUNET_free(result);
1796 } 1813 GNUNET_free(routeList);
1797 if (pos < strlen (routeList)) 1814 return NULL; /* oops */
1798 { 1815 }
1799 LOG (GNUNET_ERROR_TYPE_WARNING, 1816 GNUNET_free(routeList);
1800 _ ("Invalid format: `%s'\n"),
1801 &routeListX[pos]);
1802 GNUNET_free (result);
1803 GNUNET_free (routeList);
1804 return NULL; /* oops */
1805 }
1806 GNUNET_free (routeList);
1807 return result; /* ok */ 1817 return result; /* ok */
1808} 1818}
1809 1819
@@ -1820,7 +1830,7 @@ GNUNET_STRINGS_parse_ipv4_policy (const char *routeListX)
1820 * @return the converted list, 0-terminated, NULL if the synatx is flawed 1830 * @return the converted list, 0-terminated, NULL if the synatx is flawed
1821 */ 1831 */
1822struct GNUNET_STRINGS_IPv6NetworkPolicy * 1832struct GNUNET_STRINGS_IPv6NetworkPolicy *
1823GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX) 1833GNUNET_STRINGS_parse_ipv6_policy(const char *routeListX)
1824{ 1834{
1825 unsigned int count; 1835 unsigned int count;
1826 unsigned int i; 1836 unsigned int i;
@@ -1839,110 +1849,110 @@ GNUNET_STRINGS_parse_ipv6_policy (const char *routeListX)
1839 1849
1840 if (NULL == routeListX) 1850 if (NULL == routeListX)
1841 return NULL; 1851 return NULL;
1842 len = strlen (routeListX); 1852 len = strlen(routeListX);
1843 if (0 == len) 1853 if (0 == len)
1844 return NULL; 1854 return NULL;
1845 routeList = GNUNET_strdup (routeListX); 1855 routeList = GNUNET_strdup(routeListX);
1846 count = 0; 1856 count = 0;
1847 for (i = 0; i < len; i++) 1857 for (i = 0; i < len; i++)
1848 if (';' == routeList[i]) 1858 if (';' == routeList[i])
1849 count++; 1859 count++;
1850 if (';' != routeList[len - 1]) 1860 if (';' != routeList[len - 1])
1851 { 1861 {
1852 LOG (GNUNET_ERROR_TYPE_WARNING, 1862 LOG(GNUNET_ERROR_TYPE_WARNING,
1853 _ ("Invalid network notation (does not end with ';': `%s')\n"), 1863 _("Invalid network notation (does not end with ';': `%s')\n"),
1854 routeList); 1864 routeList);
1855 GNUNET_free (routeList); 1865 GNUNET_free(routeList);
1856 return NULL; 1866 return NULL;
1857 } 1867 }
1858 1868
1859 result = GNUNET_malloc (sizeof (struct GNUNET_STRINGS_IPv6NetworkPolicy) * 1869 result = GNUNET_malloc(sizeof(struct GNUNET_STRINGS_IPv6NetworkPolicy) *
1860 (count + 1)); 1870 (count + 1));
1861 i = 0; 1871 i = 0;
1862 pos = 0; 1872 pos = 0;
1863 while (i < count) 1873 while (i < count)
1864 {
1865 start = pos;
1866 while (';' != routeList[pos])
1867 pos++;
1868 slash = pos;
1869 while ((slash >= start) && (routeList[slash] != '/'))
1870 slash--;
1871
1872 if (slash < start)
1873 { 1874 {
1874 memset (&result[i].netmask, 0xFF, sizeof (struct in6_addr)); 1875 start = pos;
1876 while (';' != routeList[pos])
1877 pos++;
1875 slash = pos; 1878 slash = pos;
1876 } 1879 while ((slash >= start) && (routeList[slash] != '/'))
1877 else 1880 slash--;
1878 { 1881
1879 routeList[pos] = '\0'; 1882 if (slash < start)
1880 for (colon = pos; ':' != routeList[colon]; colon--)
1881 if ('/' == routeList[colon])
1882 break;
1883 if (':' == routeList[colon])
1884 {
1885 routeList[colon] = '\0';
1886 if (GNUNET_OK !=
1887 parse_port_policy (&routeList[colon + 1], &result[i].pp))
1888 { 1883 {
1889 GNUNET_free (result); 1884 memset(&result[i].netmask, 0xFF, sizeof(struct in6_addr));
1890 GNUNET_free (routeList); 1885 slash = pos;
1891 return NULL;
1892 } 1886 }
1893 } 1887 else
1894 ret = inet_pton (AF_INET6, &routeList[slash + 1], &result[i].netmask); 1888 {
1889 routeList[pos] = '\0';
1890 for (colon = pos; ':' != routeList[colon]; colon--)
1891 if ('/' == routeList[colon])
1892 break;
1893 if (':' == routeList[colon])
1894 {
1895 routeList[colon] = '\0';
1896 if (GNUNET_OK !=
1897 parse_port_policy(&routeList[colon + 1], &result[i].pp))
1898 {
1899 GNUNET_free(result);
1900 GNUNET_free(routeList);
1901 return NULL;
1902 }
1903 }
1904 ret = inet_pton(AF_INET6, &routeList[slash + 1], &result[i].netmask);
1905 if (ret <= 0)
1906 {
1907 save = errno;
1908 if ((1 != sscanf(&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1909 (bits > 128))
1910 {
1911 if (0 == ret)
1912 LOG(GNUNET_ERROR_TYPE_WARNING,
1913 _("Wrong format `%s' for netmask\n"),
1914 &routeList[slash + 1]);
1915 else
1916 {
1917 errno = save;
1918 LOG_STRERROR(GNUNET_ERROR_TYPE_WARNING, "inet_pton");
1919 }
1920 GNUNET_free(result);
1921 GNUNET_free(routeList);
1922 return NULL;
1923 }
1924 off = 0;
1925 while (bits > 8)
1926 {
1927 result[i].netmask.s6_addr[off++] = 0xFF;
1928 bits -= 8;
1929 }
1930 while (bits > 0)
1931 {
1932 result[i].netmask.s6_addr[off] =
1933 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1934 bits--;
1935 }
1936 }
1937 }
1938 routeList[slash] = '\0';
1939 ret = inet_pton(AF_INET6, &routeList[start], &result[i].network);
1895 if (ret <= 0) 1940 if (ret <= 0)
1896 {
1897 save = errno;
1898 if ((1 != sscanf (&routeList[slash + 1], "%u%1s", &bits, dummy)) ||
1899 (bits > 128))
1900 { 1941 {
1901 if (0 == ret) 1942 if (0 == ret)
1902 LOG (GNUNET_ERROR_TYPE_WARNING, 1943 LOG(GNUNET_ERROR_TYPE_WARNING,
1903 _ ("Wrong format `%s' for netmask\n"), 1944 _("Wrong format `%s' for network\n"),
1904 &routeList[slash + 1]); 1945 &routeList[slash + 1]);
1905 else 1946 else
1906 { 1947 LOG_STRERROR(GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1907 errno = save; 1948 GNUNET_free(result);
1908 LOG_STRERROR (GNUNET_ERROR_TYPE_WARNING, "inet_pton"); 1949 GNUNET_free(routeList);
1909 }
1910 GNUNET_free (result);
1911 GNUNET_free (routeList);
1912 return NULL; 1950 return NULL;
1913 } 1951 }
1914 off = 0; 1952 pos++;
1915 while (bits > 8) 1953 i++;
1916 {
1917 result[i].netmask.s6_addr[off++] = 0xFF;
1918 bits -= 8;
1919 }
1920 while (bits > 0)
1921 {
1922 result[i].netmask.s6_addr[off] =
1923 (result[i].netmask.s6_addr[off] >> 1) + 0x80;
1924 bits--;
1925 }
1926 }
1927 }
1928 routeList[slash] = '\0';
1929 ret = inet_pton (AF_INET6, &routeList[start], &result[i].network);
1930 if (ret <= 0)
1931 {
1932 if (0 == ret)
1933 LOG (GNUNET_ERROR_TYPE_WARNING,
1934 _ ("Wrong format `%s' for network\n"),
1935 &routeList[slash + 1]);
1936 else
1937 LOG_STRERROR (GNUNET_ERROR_TYPE_ERROR, "inet_pton");
1938 GNUNET_free (result);
1939 GNUNET_free (routeList);
1940 return NULL;
1941 } 1954 }
1942 pos++; 1955 GNUNET_free(routeList);
1943 i++;
1944 }
1945 GNUNET_free (routeList);
1946 return result; 1956 return result;
1947} 1957}
1948 1958
@@ -1965,58 +1975,58 @@ static char *cvt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1965 * @return the size of the output 1975 * @return the size of the output
1966 */ 1976 */
1967size_t 1977size_t
1968GNUNET_STRINGS_base64_encode (const void *in, size_t len, char **output) 1978GNUNET_STRINGS_base64_encode(const void *in, size_t len, char **output)
1969{ 1979{
1970 const char *data = in; 1980 const char *data = in;
1971 size_t ret; 1981 size_t ret;
1972 char *opt; 1982 char *opt;
1973 1983
1974 ret = 0; 1984 ret = 0;
1975 opt = GNUNET_malloc (2 + (len * 4 / 3) + 8); 1985 opt = GNUNET_malloc(2 + (len * 4 / 3) + 8);
1976 for (size_t i = 0; i < len; ++i) 1986 for (size_t i = 0; i < len; ++i)
1977 {
1978 char c;
1979
1980 c = (data[i] >> 2) & 0x3f;
1981 opt[ret++] = cvt[(int) c];
1982 c = (data[i] << 4) & 0x3f;
1983 if (++i < len)
1984 c |= (data[i] >> 4) & 0x0f;
1985 opt[ret++] = cvt[(int) c];
1986 if (i < len)
1987 { 1987 {
1988 c = (data[i] << 2) & 0x3f; 1988 char c;
1989
1990 c = (data[i] >> 2) & 0x3f;
1991 opt[ret++] = cvt[(int)c];
1992 c = (data[i] << 4) & 0x3f;
1989 if (++i < len) 1993 if (++i < len)
1990 c |= (data[i] >> 6) & 0x03; 1994 c |= (data[i] >> 4) & 0x0f;
1991 opt[ret++] = cvt[(int) c]; 1995 opt[ret++] = cvt[(int)c];
1992 } 1996 if (i < len)
1993 else 1997 {
1994 { 1998 c = (data[i] << 2) & 0x3f;
1995 ++i; 1999 if (++i < len)
1996 opt[ret++] = FILLCHAR; 2000 c |= (data[i] >> 6) & 0x03;
1997 } 2001 opt[ret++] = cvt[(int)c];
1998 if (i < len) 2002 }
1999 { 2003 else
2000 c = data[i] & 0x3f; 2004 {
2001 opt[ret++] = cvt[(int) c]; 2005 ++i;
2002 } 2006 opt[ret++] = FILLCHAR;
2003 else 2007 }
2004 { 2008 if (i < len)
2005 opt[ret++] = FILLCHAR; 2009 {
2010 c = data[i] & 0x3f;
2011 opt[ret++] = cvt[(int)c];
2012 }
2013 else
2014 {
2015 opt[ret++] = FILLCHAR;
2016 }
2006 } 2017 }
2007 }
2008 *output = opt; 2018 *output = opt;
2009 return ret; 2019 return ret;
2010} 2020}
2011 2021
2012#define cvtfind(a) \ 2022#define cvtfind(a) \
2013 ((((a) >= 'A') && ((a) <= 'Z')) \ 2023 ((((a) >= 'A') && ((a) <= 'Z')) \
2014 ? (a) - 'A' \ 2024 ? (a) - 'A' \
2015 : (((a) >= 'a') && ((a) <= 'z')) \ 2025 : (((a) >= 'a') && ((a) <= 'z')) \
2016 ? (a) - 'a' + 26 \ 2026 ? (a) - 'a' + 26 \
2017 : (((a) >= '0') && ((a) <= '9')) \ 2027 : (((a) >= '0') && ((a) <= '9')) \
2018 ? (a) - '0' + 52 \ 2028 ? (a) - '0' + 52 \
2019 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1) 2029 : ((a) == '+') ? 62 : ((a) == '/') ? 63 : -1)
2020 2030
2021 2031
2022/** 2032/**
@@ -2029,61 +2039,61 @@ GNUNET_STRINGS_base64_encode (const void *in, size_t len, char **output)
2029 * @return the size of the output 2039 * @return the size of the output
2030 */ 2040 */
2031size_t 2041size_t
2032GNUNET_STRINGS_base64_decode (const char *data, size_t len, void **out) 2042GNUNET_STRINGS_base64_decode(const char *data, size_t len, void **out)
2033{ 2043{
2034 char *output; 2044 char *output;
2035 size_t ret = 0; 2045 size_t ret = 0;
2036 2046
2037#define CHECK_CRLF \ 2047#define CHECK_CRLF \
2038 while (data[i] == '\r' || data[i] == '\n') \ 2048 while (data[i] == '\r' || data[i] == '\n') \
2039 { \ 2049 { \
2040 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \ 2050 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG | GNUNET_ERROR_TYPE_BULK, \
2041 "ignoring CR/LF\n"); \ 2051 "ignoring CR/LF\n"); \
2042 i++; \ 2052 i++; \
2043 if (i >= len) \ 2053 if (i >= len) \
2044 goto END; \ 2054 goto END; \
2045 } 2055 }
2046 2056
2047 output = GNUNET_malloc ((len * 3 / 4) + 8); 2057 output = GNUNET_malloc((len * 3 / 4) + 8);
2048 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 2058 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
2049 "base64_decode decoding len=%d\n", 2059 "base64_decode decoding len=%d\n",
2050 (int) len); 2060 (int)len);
2051 for (size_t i = 0; i < len; ++i) 2061 for (size_t i = 0; i < len; ++i)
2052 {
2053 char c;
2054 char c1;
2055
2056 CHECK_CRLF;
2057 if (FILLCHAR == data[i])
2058 break;
2059 c = (char) cvtfind (data[i]);
2060 ++i;
2061 CHECK_CRLF;
2062 c1 = (char) cvtfind (data[i]);
2063 c = (c << 2) | ((c1 >> 4) & 0x3);
2064 output[ret++] = c;
2065 if (++i < len)
2066 { 2062 {
2063 char c;
2064 char c1;
2065
2067 CHECK_CRLF; 2066 CHECK_CRLF;
2068 c = data[i]; 2067 if (FILLCHAR == data[i])
2069 if (FILLCHAR == c)
2070 break; 2068 break;
2071 c = (char) cvtfind (c); 2069 c = (char)cvtfind(data[i]);
2072 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf); 2070 ++i;
2073 output[ret++] = c1;
2074 }
2075 if (++i < len)
2076 {
2077 CHECK_CRLF; 2071 CHECK_CRLF;
2078 c1 = data[i]; 2072 c1 = (char)cvtfind(data[i]);
2079 if (FILLCHAR == c1) 2073 c = (c << 2) | ((c1 >> 4) & 0x3);
2080 break;
2081
2082 c1 = (char) cvtfind (c1);
2083 c = ((c << 6) & 0xc0) | c1;
2084 output[ret++] = c; 2074 output[ret++] = c;
2075 if (++i < len)
2076 {
2077 CHECK_CRLF;
2078 c = data[i];
2079 if (FILLCHAR == c)
2080 break;
2081 c = (char)cvtfind(c);
2082 c1 = ((c1 << 4) & 0xf0) | ((c >> 2) & 0xf);
2083 output[ret++] = c1;
2084 }
2085 if (++i < len)
2086 {
2087 CHECK_CRLF;
2088 c1 = data[i];
2089 if (FILLCHAR == c1)
2090 break;
2091
2092 c1 = (char)cvtfind(c1);
2093 c = ((c << 6) & 0xc0) | c1;
2094 output[ret++] = c;
2095 }
2085 } 2096 }
2086 }
2087END: 2097END:
2088 *out = output; 2098 *out = output;
2089 return ret; 2099 return ret;
diff --git a/src/util/test_bio.c b/src/util/test_bio.c
index 719f622ba..c8887e246 100644
--- a/src/util/test_bio.c
+++ b/src/util/test_bio.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_bio.c 22 * @file util/test_bio.c
@@ -31,212 +31,212 @@
31#define TESTNUMBER64 ((int64_t)100000L) 31#define TESTNUMBER64 ((int64_t)100000L)
32 32
33static int 33static int
34test_normal_rw () 34test_normal_rw()
35{ 35{
36 char *msg; 36 char *msg;
37 int64_t testNum; 37 int64_t testNum;
38 char *readResultString; 38 char *readResultString;
39 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 39 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
40 struct GNUNET_BIO_WriteHandle *fileW; 40 struct GNUNET_BIO_WriteHandle *fileW;
41 struct GNUNET_BIO_ReadHandle *fileR; 41 struct GNUNET_BIO_ReadHandle *fileR;
42 struct GNUNET_CONTAINER_MetaData *metaDataW; 42 struct GNUNET_CONTAINER_MetaData *metaDataW;
43 struct GNUNET_CONTAINER_MetaData *metaDataR; 43 struct GNUNET_CONTAINER_MetaData *metaDataR;
44 44
45 metaDataW = GNUNET_CONTAINER_meta_data_create (); 45 metaDataW = GNUNET_CONTAINER_meta_data_create();
46 metaDataR = NULL; 46 metaDataR = NULL;
47 GNUNET_CONTAINER_meta_data_add_publication_date (metaDataW); 47 GNUNET_CONTAINER_meta_data_add_publication_date(metaDataW);
48 48
49 fileW = GNUNET_BIO_write_open (fileName); 49 fileW = GNUNET_BIO_write_open(fileName);
50 GNUNET_assert (NULL != fileW); 50 GNUNET_assert(NULL != fileW);
51 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_string (fileW, TESTSTRING)); 51 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_string(fileW, TESTSTRING));
52 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_meta_data (fileW, metaDataW)); 52 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_meta_data(fileW, metaDataW));
53 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_int64 (fileW, TESTNUMBER64)); 53 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_int64(fileW, TESTNUMBER64));
54 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 54 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
55 55
56 fileR = GNUNET_BIO_read_open (fileName); 56 fileR = GNUNET_BIO_read_open(fileName);
57 GNUNET_assert (NULL != fileR); 57 GNUNET_assert(NULL != fileR);
58 readResultString = NULL; 58 readResultString = NULL;
59 GNUNET_assert (GNUNET_OK == 59 GNUNET_assert(GNUNET_OK ==
60 GNUNET_BIO_read_string (fileR, "Read string error", 60 GNUNET_BIO_read_string(fileR, "Read string error",
61 &readResultString, 200)); 61 &readResultString, 200));
62 GNUNET_assert (NULL != readResultString); 62 GNUNET_assert(NULL != readResultString);
63 GNUNET_assert (0 == strcmp (TESTSTRING, readResultString)); 63 GNUNET_assert(0 == strcmp(TESTSTRING, readResultString));
64 GNUNET_free (readResultString); 64 GNUNET_free(readResultString);
65 GNUNET_assert (GNUNET_OK == 65 GNUNET_assert(GNUNET_OK ==
66 GNUNET_BIO_read_meta_data (fileR, "Read meta error", 66 GNUNET_BIO_read_meta_data(fileR, "Read meta error",
67 &metaDataR)); 67 &metaDataR));
68 GNUNET_assert (GNUNET_YES == 68 GNUNET_assert(GNUNET_YES ==
69 GNUNET_CONTAINER_meta_data_test_equal (metaDataR, metaDataW)); 69 GNUNET_CONTAINER_meta_data_test_equal(metaDataR, metaDataW));
70 GNUNET_assert (GNUNET_OK == GNUNET_BIO_read_int64 (fileR, &testNum)); 70 GNUNET_assert(GNUNET_OK == GNUNET_BIO_read_int64(fileR, &testNum));
71 GNUNET_BIO_read_close (fileR, &msg); 71 GNUNET_BIO_read_close(fileR, &msg);
72 GNUNET_CONTAINER_meta_data_destroy (metaDataW); 72 GNUNET_CONTAINER_meta_data_destroy(metaDataW);
73 GNUNET_CONTAINER_meta_data_destroy (metaDataR); 73 GNUNET_CONTAINER_meta_data_destroy(metaDataR);
74 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 74 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
75 GNUNET_free (fileName); 75 GNUNET_free(fileName);
76 return 0; 76 return 0;
77} 77}
78 78
79static int 79static int
80test_nullstring_rw () 80test_nullstring_rw()
81{ 81{
82 char *msg; 82 char *msg;
83 char *readResultString = (char *) "not null"; 83 char *readResultString = (char *)"not null";
84 struct GNUNET_BIO_WriteHandle *fileW; 84 struct GNUNET_BIO_WriteHandle *fileW;
85 struct GNUNET_BIO_ReadHandle *fileR; 85 struct GNUNET_BIO_ReadHandle *fileR;
86 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 86 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
87 87
88 fileW = GNUNET_BIO_write_open (fileName); 88 fileW = GNUNET_BIO_write_open(fileName);
89 GNUNET_assert (NULL != fileW); 89 GNUNET_assert(NULL != fileW);
90 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_string (fileW, NULL)); 90 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_string(fileW, NULL));
91 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 91 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
92 92
93 fileR = GNUNET_BIO_read_open (fileName); 93 fileR = GNUNET_BIO_read_open(fileName);
94 GNUNET_assert (NULL != fileR); 94 GNUNET_assert(NULL != fileR);
95 GNUNET_assert (GNUNET_OK == 95 GNUNET_assert(GNUNET_OK ==
96 GNUNET_BIO_read_string (fileR, "Read string error", 96 GNUNET_BIO_read_string(fileR, "Read string error",
97 &readResultString, 200)); 97 &readResultString, 200));
98 GNUNET_assert (NULL == readResultString); 98 GNUNET_assert(NULL == readResultString);
99 GNUNET_BIO_read_close (fileR, &msg); 99 GNUNET_BIO_read_close(fileR, &msg);
100 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 100 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
101 GNUNET_free (fileName); 101 GNUNET_free(fileName);
102 102
103 return 0; 103 return 0;
104} 104}
105 105
106static int 106static int
107test_emptystring_rw () 107test_emptystring_rw()
108{ 108{
109 char *msg; 109 char *msg;
110 char *readResultString; 110 char *readResultString;
111 struct GNUNET_BIO_WriteHandle *fileW; 111 struct GNUNET_BIO_WriteHandle *fileW;
112 struct GNUNET_BIO_ReadHandle *fileR; 112 struct GNUNET_BIO_ReadHandle *fileR;
113 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 113 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
114 114
115 fileW = GNUNET_BIO_write_open (fileName); 115 fileW = GNUNET_BIO_write_open(fileName);
116 GNUNET_assert (NULL != fileW); 116 GNUNET_assert(NULL != fileW);
117 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_string (fileW, "")); 117 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_string(fileW, ""));
118 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 118 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
119 119
120 fileR = GNUNET_BIO_read_open (fileName); 120 fileR = GNUNET_BIO_read_open(fileName);
121 GNUNET_assert (NULL != fileR); 121 GNUNET_assert(NULL != fileR);
122 readResultString = NULL; 122 readResultString = NULL;
123 GNUNET_assert (GNUNET_OK == 123 GNUNET_assert(GNUNET_OK ==
124 GNUNET_BIO_read_string (fileR, "Read string error", 124 GNUNET_BIO_read_string(fileR, "Read string error",
125 &readResultString, 200)); 125 &readResultString, 200));
126 GNUNET_free (readResultString); 126 GNUNET_free(readResultString);
127 GNUNET_BIO_read_close (fileR, &msg); 127 GNUNET_BIO_read_close(fileR, &msg);
128 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 128 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
129 GNUNET_free (fileName); 129 GNUNET_free(fileName);
130 return 0; 130 return 0;
131} 131}
132 132
133static int 133static int
134test_bigstring_rw () 134test_bigstring_rw()
135{ 135{
136 char *msg; 136 char *msg;
137 char *readResultString; 137 char *readResultString;
138 struct GNUNET_BIO_WriteHandle *fileW; 138 struct GNUNET_BIO_WriteHandle *fileW;
139 struct GNUNET_BIO_ReadHandle *fileR; 139 struct GNUNET_BIO_ReadHandle *fileR;
140 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 140 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
141 141
142 fileW = GNUNET_BIO_write_open (fileName); 142 fileW = GNUNET_BIO_write_open(fileName);
143 GNUNET_assert (NULL != fileW); 143 GNUNET_assert(NULL != fileW);
144 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_string (fileW, TESTSTRING)); 144 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_string(fileW, TESTSTRING));
145 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 145 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
146 146
147 fileR = GNUNET_BIO_read_open (fileName); 147 fileR = GNUNET_BIO_read_open(fileName);
148 GNUNET_assert (NULL != fileR); 148 GNUNET_assert(NULL != fileR);
149 readResultString = NULL; 149 readResultString = NULL;
150 GNUNET_assert (GNUNET_SYSERR == 150 GNUNET_assert(GNUNET_SYSERR ==
151 GNUNET_BIO_read_string (fileR, "Read string error", 151 GNUNET_BIO_read_string(fileR, "Read string error",
152 &readResultString, 1)); 152 &readResultString, 1));
153 GNUNET_assert (NULL == readResultString); 153 GNUNET_assert(NULL == readResultString);
154 msg = NULL; 154 msg = NULL;
155 GNUNET_BIO_read_close (fileR, &msg); 155 GNUNET_BIO_read_close(fileR, &msg);
156 GNUNET_free (msg); 156 GNUNET_free(msg);
157 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 157 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
158 GNUNET_free (fileName); 158 GNUNET_free(fileName);
159 return 0; 159 return 0;
160} 160}
161 161
162static int 162static int
163test_bigmeta_rw () 163test_bigmeta_rw()
164{ 164{
165 char *msg; 165 char *msg;
166 static char meta[1024 * 1024 * 10]; 166 static char meta[1024 * 1024 * 10];
167 struct GNUNET_BIO_WriteHandle *fileW; 167 struct GNUNET_BIO_WriteHandle *fileW;
168 struct GNUNET_BIO_ReadHandle *fileR; 168 struct GNUNET_BIO_ReadHandle *fileR;
169 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 169 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
170 struct GNUNET_CONTAINER_MetaData *metaDataR; 170 struct GNUNET_CONTAINER_MetaData *metaDataR;
171 171
172 memset (meta, 'b', sizeof (meta)); 172 memset(meta, 'b', sizeof(meta));
173 meta[sizeof (meta) - 1] = '\0'; 173 meta[sizeof(meta) - 1] = '\0';
174 fileW = GNUNET_BIO_write_open (fileName); 174 fileW = GNUNET_BIO_write_open(fileName);
175 GNUNET_assert (NULL != fileW); 175 GNUNET_assert(NULL != fileW);
176 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_int32 (fileW, sizeof (meta))); 176 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_int32(fileW, sizeof(meta)));
177 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write (fileW, meta, sizeof (meta))); 177 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write(fileW, meta, sizeof(meta)));
178 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 178 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
179 179
180 fileR = GNUNET_BIO_read_open (fileName); 180 fileR = GNUNET_BIO_read_open(fileName);
181 GNUNET_assert (NULL != fileR); 181 GNUNET_assert(NULL != fileR);
182 metaDataR = NULL; 182 metaDataR = NULL;
183 GNUNET_assert (GNUNET_SYSERR == 183 GNUNET_assert(GNUNET_SYSERR ==
184 GNUNET_BIO_read_meta_data (fileR, "Read meta error", 184 GNUNET_BIO_read_meta_data(fileR, "Read meta error",
185 &metaDataR)); 185 &metaDataR));
186 msg = NULL; 186 msg = NULL;
187 GNUNET_BIO_read_close (fileR, &msg); 187 GNUNET_BIO_read_close(fileR, &msg);
188 GNUNET_free (msg); 188 GNUNET_free(msg);
189 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 189 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
190 GNUNET_assert (NULL == metaDataR); 190 GNUNET_assert(NULL == metaDataR);
191 GNUNET_free (fileName); 191 GNUNET_free(fileName);
192 return 0; 192 return 0;
193} 193}
194 194
195static int 195static int
196test_directory_r () 196test_directory_r()
197{ 197{
198#if LINUX 198#if LINUX
199 char *msg; 199 char *msg;
200 char readResult[200]; 200 char readResult[200];
201 struct GNUNET_BIO_ReadHandle *fileR; 201 struct GNUNET_BIO_ReadHandle *fileR;
202 202
203 fileR = GNUNET_BIO_read_open ("/dev"); 203 fileR = GNUNET_BIO_read_open("/dev");
204 GNUNET_assert (NULL != fileR); 204 GNUNET_assert(NULL != fileR);
205 GNUNET_assert (GNUNET_SYSERR == 205 GNUNET_assert(GNUNET_SYSERR ==
206 GNUNET_BIO_read (fileR, "Read error", readResult, 206 GNUNET_BIO_read(fileR, "Read error", readResult,
207 sizeof (readResult))); 207 sizeof(readResult)));
208 msg = NULL; 208 msg = NULL;
209 GNUNET_BIO_read_close (fileR, &msg); 209 GNUNET_BIO_read_close(fileR, &msg);
210 GNUNET_free (msg); 210 GNUNET_free(msg);
211#endif 211#endif
212 return 0; 212 return 0;
213} 213}
214 214
215static int 215static int
216test_nullfile_rw () 216test_nullfile_rw()
217{ 217{
218 static char fileNameNO[102401]; 218 static char fileNameNO[102401];
219 struct GNUNET_BIO_WriteHandle *fileWNO; 219 struct GNUNET_BIO_WriteHandle *fileWNO;
220 struct GNUNET_BIO_ReadHandle *fileRNO; 220 struct GNUNET_BIO_ReadHandle *fileRNO;
221 221
222 memset (fileNameNO, 'a', sizeof (fileNameNO)); 222 memset(fileNameNO, 'a', sizeof(fileNameNO));
223 fileNameNO[sizeof (fileNameNO) - 1] = '\0'; 223 fileNameNO[sizeof(fileNameNO) - 1] = '\0';
224 224
225 GNUNET_log_skip (1, GNUNET_NO); 225 GNUNET_log_skip(1, GNUNET_NO);
226 fileWNO = GNUNET_BIO_write_open (fileNameNO); 226 fileWNO = GNUNET_BIO_write_open(fileNameNO);
227 GNUNET_log_skip (0, GNUNET_YES); 227 GNUNET_log_skip(0, GNUNET_YES);
228 GNUNET_assert (NULL == fileWNO); 228 GNUNET_assert(NULL == fileWNO);
229 229
230 GNUNET_log_skip (1, GNUNET_NO); 230 GNUNET_log_skip(1, GNUNET_NO);
231 fileRNO = GNUNET_BIO_read_open (fileNameNO); 231 fileRNO = GNUNET_BIO_read_open(fileNameNO);
232 GNUNET_log_skip (0, GNUNET_YES); 232 GNUNET_log_skip(0, GNUNET_YES);
233 GNUNET_assert (NULL == fileRNO); 233 GNUNET_assert(NULL == fileRNO);
234 return 0; 234 return 0;
235} 235}
236 236
237 237
238static int 238static int
239test_fullfile_rw () 239test_fullfile_rw()
240{ 240{
241#ifdef LINUX 241#ifdef LINUX
242 /* /dev/full only seems to exist on Linux */ 242 /* /dev/full only seems to exist on Linux */
@@ -249,168 +249,168 @@ test_fullfile_rw ()
249 struct GNUNET_CONTAINER_MetaData *metaDataW; 249 struct GNUNET_CONTAINER_MetaData *metaDataW;
250 struct GNUNET_CONTAINER_MetaData *metaDataR; 250 struct GNUNET_CONTAINER_MetaData *metaDataR;
251 251
252 metaDataW = GNUNET_CONTAINER_meta_data_create (); 252 metaDataW = GNUNET_CONTAINER_meta_data_create();
253 GNUNET_CONTAINER_meta_data_add_publication_date (metaDataW); 253 GNUNET_CONTAINER_meta_data_add_publication_date(metaDataW);
254 254
255 fileW = GNUNET_BIO_write_open ("/dev/full"); 255 fileW = GNUNET_BIO_write_open("/dev/full");
256 GNUNET_assert (NULL != fileW); 256 GNUNET_assert(NULL != fileW);
257 (void) GNUNET_BIO_write (fileW, TESTSTRING, strlen (TESTSTRING)); 257 (void)GNUNET_BIO_write(fileW, TESTSTRING, strlen(TESTSTRING));
258 (void) GNUNET_BIO_write_string (fileW, TESTSTRING); 258 (void)GNUNET_BIO_write_string(fileW, TESTSTRING);
259 (void) GNUNET_BIO_write_meta_data (fileW, metaDataW); 259 (void)GNUNET_BIO_write_meta_data(fileW, metaDataW);
260 GNUNET_assert (GNUNET_SYSERR == GNUNET_BIO_write_close (fileW)); 260 GNUNET_assert(GNUNET_SYSERR == GNUNET_BIO_write_close(fileW));
261 GNUNET_CONTAINER_meta_data_destroy (metaDataW); 261 GNUNET_CONTAINER_meta_data_destroy(metaDataW);
262 262
263 fileW = GNUNET_BIO_write_open ("/dev/full"); 263 fileW = GNUNET_BIO_write_open("/dev/full");
264 GNUNET_assert (NULL != fileW); 264 GNUNET_assert(NULL != fileW);
265 GNUNET_assert (GNUNET_SYSERR == GNUNET_BIO_write_close (fileW)); 265 GNUNET_assert(GNUNET_SYSERR == GNUNET_BIO_write_close(fileW));
266 266
267 fileR = GNUNET_BIO_read_open ("/dev/null"); 267 fileR = GNUNET_BIO_read_open("/dev/null");
268 GNUNET_assert (NULL != fileR); 268 GNUNET_assert(NULL != fileR);
269 GNUNET_assert (GNUNET_SYSERR == 269 GNUNET_assert(GNUNET_SYSERR ==
270 GNUNET_BIO_read (fileR, "Read error", readResult, 270 GNUNET_BIO_read(fileR, "Read error", readResult,
271 sizeof (readResult))); 271 sizeof(readResult)));
272 readResultString = NULL; 272 readResultString = NULL;
273 GNUNET_assert (GNUNET_SYSERR == 273 GNUNET_assert(GNUNET_SYSERR ==
274 GNUNET_BIO_read_string (fileR, "Read string error", 274 GNUNET_BIO_read_string(fileR, "Read string error",
275 &readResultString, 200)); 275 &readResultString, 200));
276 GNUNET_assert (NULL == readResultString); 276 GNUNET_assert(NULL == readResultString);
277 GNUNET_assert (GNUNET_SYSERR == GNUNET_BIO_read_int64 (fileR, &testNum)); 277 GNUNET_assert(GNUNET_SYSERR == GNUNET_BIO_read_int64(fileR, &testNum));
278 metaDataR = NULL; 278 metaDataR = NULL;
279 GNUNET_assert (GNUNET_SYSERR == 279 GNUNET_assert(GNUNET_SYSERR ==
280 GNUNET_BIO_read_meta_data (fileR, "Read meta error", 280 GNUNET_BIO_read_meta_data(fileR, "Read meta error",
281 &metaDataR)); 281 &metaDataR));
282 msg = NULL; 282 msg = NULL;
283 GNUNET_BIO_read_close (fileR, &msg); 283 GNUNET_BIO_read_close(fileR, &msg);
284 GNUNET_free (msg); 284 GNUNET_free(msg);
285 GNUNET_assert (NULL == metaDataR); 285 GNUNET_assert(NULL == metaDataR);
286#endif 286#endif
287 return 0; 287 return 0;
288} 288}
289 289
290static int 290static int
291test_fakestring_rw () 291test_fakestring_rw()
292{ 292{
293 char *msg; 293 char *msg;
294 int32_t tmpInt = 2; 294 int32_t tmpInt = 2;
295 char *readResult; 295 char *readResult;
296 struct GNUNET_BIO_WriteHandle *fileW; 296 struct GNUNET_BIO_WriteHandle *fileW;
297 struct GNUNET_BIO_ReadHandle *fileR; 297 struct GNUNET_BIO_ReadHandle *fileR;
298 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 298 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
299 299
300 fileW = GNUNET_BIO_write_open (fileName); 300 fileW = GNUNET_BIO_write_open(fileName);
301 GNUNET_assert (NULL != fileW); 301 GNUNET_assert(NULL != fileW);
302 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_int32 (fileW, tmpInt)); 302 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_int32(fileW, tmpInt));
303 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 303 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
304 304
305 fileR = GNUNET_BIO_read_open (fileName); 305 fileR = GNUNET_BIO_read_open(fileName);
306 GNUNET_assert (NULL != fileR); 306 GNUNET_assert(NULL != fileR);
307 GNUNET_assert (GNUNET_SYSERR == 307 GNUNET_assert(GNUNET_SYSERR ==
308 GNUNET_BIO_read_string (fileR, "Read string error", 308 GNUNET_BIO_read_string(fileR, "Read string error",
309 &readResult, 200)); 309 &readResult, 200));
310 msg = NULL; 310 msg = NULL;
311 GNUNET_BIO_read_close (fileR, &msg); 311 GNUNET_BIO_read_close(fileR, &msg);
312 GNUNET_free (msg); 312 GNUNET_free(msg);
313 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 313 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
314 GNUNET_free (fileName); 314 GNUNET_free(fileName);
315 return 0; 315 return 0;
316} 316}
317 317
318static int 318static int
319test_fakemeta_rw () 319test_fakemeta_rw()
320{ 320{
321 char *msg; 321 char *msg;
322 int32_t tmpInt = 2; 322 int32_t tmpInt = 2;
323 struct GNUNET_BIO_WriteHandle *fileW; 323 struct GNUNET_BIO_WriteHandle *fileW;
324 struct GNUNET_BIO_ReadHandle *fileR; 324 struct GNUNET_BIO_ReadHandle *fileR;
325 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 325 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
326 struct GNUNET_CONTAINER_MetaData *metaDataR; 326 struct GNUNET_CONTAINER_MetaData *metaDataR;
327 327
328 fileW = GNUNET_BIO_write_open (fileName); 328 fileW = GNUNET_BIO_write_open(fileName);
329 GNUNET_assert (NULL != fileW); 329 GNUNET_assert(NULL != fileW);
330 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_int32 (fileW, tmpInt)); 330 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_int32(fileW, tmpInt));
331 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 331 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
332 332
333 fileR = GNUNET_BIO_read_open (fileName); 333 fileR = GNUNET_BIO_read_open(fileName);
334 GNUNET_assert (NULL != fileR); 334 GNUNET_assert(NULL != fileR);
335 metaDataR = NULL; 335 metaDataR = NULL;
336 GNUNET_assert (GNUNET_SYSERR == 336 GNUNET_assert(GNUNET_SYSERR ==
337 GNUNET_BIO_read_meta_data (fileR, "Read meta error", 337 GNUNET_BIO_read_meta_data(fileR, "Read meta error",
338 &metaDataR)); 338 &metaDataR));
339 GNUNET_assert (NULL == metaDataR); 339 GNUNET_assert(NULL == metaDataR);
340 msg = NULL; 340 msg = NULL;
341 GNUNET_BIO_read_close (fileR, &msg); 341 GNUNET_BIO_read_close(fileR, &msg);
342 GNUNET_free (msg); 342 GNUNET_free(msg);
343 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 343 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
344 GNUNET_free (fileName); 344 GNUNET_free(fileName);
345 return 0; 345 return 0;
346} 346}
347 347
348static int 348static int
349test_fakebigmeta_rw () 349test_fakebigmeta_rw()
350{ 350{
351 char *msg; 351 char *msg;
352 int32_t tmpInt = 1024 * 1024 * 10; 352 int32_t tmpInt = 1024 * 1024 * 10;
353 struct GNUNET_BIO_WriteHandle *fileW; 353 struct GNUNET_BIO_WriteHandle *fileW;
354 struct GNUNET_BIO_ReadHandle *fileR; 354 struct GNUNET_BIO_ReadHandle *fileR;
355 char *fileName = GNUNET_DISK_mktemp ("gnunet_bio"); 355 char *fileName = GNUNET_DISK_mktemp("gnunet_bio");
356 struct GNUNET_CONTAINER_MetaData *metaDataR; 356 struct GNUNET_CONTAINER_MetaData *metaDataR;
357 357
358 fileW = GNUNET_BIO_write_open (fileName); 358 fileW = GNUNET_BIO_write_open(fileName);
359 GNUNET_assert (NULL != fileW); 359 GNUNET_assert(NULL != fileW);
360 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_int32 (fileW, tmpInt)); 360 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_int32(fileW, tmpInt));
361 GNUNET_assert (GNUNET_OK == GNUNET_BIO_write_close (fileW)); 361 GNUNET_assert(GNUNET_OK == GNUNET_BIO_write_close(fileW));
362 362
363 fileR = GNUNET_BIO_read_open (fileName); 363 fileR = GNUNET_BIO_read_open(fileName);
364 GNUNET_assert (NULL != fileR); 364 GNUNET_assert(NULL != fileR);
365 metaDataR = NULL; 365 metaDataR = NULL;
366 GNUNET_assert (GNUNET_SYSERR == 366 GNUNET_assert(GNUNET_SYSERR ==
367 GNUNET_BIO_read_meta_data (fileR, "Read meta error", 367 GNUNET_BIO_read_meta_data(fileR, "Read meta error",
368 &metaDataR)); 368 &metaDataR));
369 msg = NULL; 369 msg = NULL;
370 GNUNET_BIO_read_close (fileR, &msg); 370 GNUNET_BIO_read_close(fileR, &msg);
371 GNUNET_free (msg); 371 GNUNET_free(msg);
372 GNUNET_assert (GNUNET_OK == GNUNET_DISK_directory_remove (fileName)); 372 GNUNET_assert(GNUNET_OK == GNUNET_DISK_directory_remove(fileName));
373 GNUNET_assert (NULL == metaDataR); 373 GNUNET_assert(NULL == metaDataR);
374 GNUNET_free (fileName); 374 GNUNET_free(fileName);
375 return 0; 375 return 0;
376} 376}
377 377
378static int 378static int
379check_string_rw () 379check_string_rw()
380{ 380{
381 GNUNET_assert (0 == test_nullstring_rw ()); 381 GNUNET_assert(0 == test_nullstring_rw());
382 GNUNET_assert (0 == test_emptystring_rw ()); 382 GNUNET_assert(0 == test_emptystring_rw());
383 GNUNET_assert (0 == test_bigstring_rw ()); 383 GNUNET_assert(0 == test_bigstring_rw());
384 GNUNET_assert (0 == test_fakestring_rw ()); 384 GNUNET_assert(0 == test_fakestring_rw());
385 return 0; 385 return 0;
386} 386}
387 387
388static int 388static int
389check_metadata_rw () 389check_metadata_rw()
390{ 390{
391 GNUNET_assert (0 == test_fakebigmeta_rw ()); 391 GNUNET_assert(0 == test_fakebigmeta_rw());
392 GNUNET_assert (0 == test_fakemeta_rw ()); 392 GNUNET_assert(0 == test_fakemeta_rw());
393 GNUNET_assert (0 == test_bigmeta_rw ()); 393 GNUNET_assert(0 == test_bigmeta_rw());
394 return 0; 394 return 0;
395} 395}
396 396
397static int 397static int
398check_file_rw () 398check_file_rw()
399{ 399{
400 GNUNET_assert (0 == test_normal_rw ()); 400 GNUNET_assert(0 == test_normal_rw());
401 GNUNET_assert (0 == test_nullfile_rw ()); 401 GNUNET_assert(0 == test_nullfile_rw());
402 GNUNET_assert (0 == test_fullfile_rw ()); 402 GNUNET_assert(0 == test_fullfile_rw());
403 GNUNET_assert (0 == test_directory_r ()); 403 GNUNET_assert(0 == test_directory_r());
404 return 0; 404 return 0;
405} 405}
406 406
407int 407int
408main (int argc, char *argv[]) 408main(int argc, char *argv[])
409{ 409{
410 GNUNET_log_setup ("test-bio", "WARNING", NULL); 410 GNUNET_log_setup("test-bio", "WARNING", NULL);
411 GNUNET_assert (0 == check_file_rw ()); 411 GNUNET_assert(0 == check_file_rw());
412 GNUNET_assert (0 == check_metadata_rw ()); 412 GNUNET_assert(0 == check_metadata_rw());
413 GNUNET_assert (0 == check_string_rw ()); 413 GNUNET_assert(0 == check_string_rw());
414 return 0; 414 return 0;
415} 415}
416 416
diff --git a/src/util/test_client.c b/src/util/test_client.c
index 365b8663f..b49fbcd25 100644
--- a/src/util/test_client.c
+++ b/src/util/test_client.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_client.c 21 * @file util/test_client.c
22 * @brief tests for client.c 22 * @brief tests for client.c
@@ -36,31 +36,31 @@ static struct GNUNET_MQ_Handle *client_mq;
36 * Callback that just bounces the message back to the sender. 36 * Callback that just bounces the message back to the sender.
37 */ 37 */
38static void 38static void
39handle_echo (void *cls, 39handle_echo(void *cls,
40 const struct GNUNET_MessageHeader *message) 40 const struct GNUNET_MessageHeader *message)
41{ 41{
42 struct GNUNET_SERVICE_Client *c = cls; 42 struct GNUNET_SERVICE_Client *c = cls;
43 struct GNUNET_MQ_Handle *mq = GNUNET_SERVICE_client_get_mq (c); 43 struct GNUNET_MQ_Handle *mq = GNUNET_SERVICE_client_get_mq(c);
44 struct GNUNET_MQ_Envelope *env; 44 struct GNUNET_MQ_Envelope *env;
45 45
46 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 46 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
47 "Receiving message from client, bouncing back\n"); 47 "Receiving message from client, bouncing back\n");
48 env = GNUNET_MQ_msg_copy (message); 48 env = GNUNET_MQ_msg_copy(message);
49 GNUNET_MQ_send (mq, 49 GNUNET_MQ_send(mq,
50 env); 50 env);
51 GNUNET_SERVICE_client_continue (c); 51 GNUNET_SERVICE_client_continue(c);
52} 52}
53 53
54 54
55static void 55static void
56handle_bounce (void *cls, 56handle_bounce(void *cls,
57 const struct GNUNET_MessageHeader *got) 57 const struct GNUNET_MessageHeader *got)
58{ 58{
59 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 59 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
60 "Receiving bounce, checking content\n"); 60 "Receiving bounce, checking content\n");
61 GNUNET_assert (NULL != got); 61 GNUNET_assert(NULL != got);
62 global_ret = 2; 62 global_ret = 2;
63 GNUNET_MQ_destroy (client_mq); 63 GNUNET_MQ_destroy(client_mq);
64 client_mq = NULL; 64 client_mq = NULL;
65} 65}
66 66
@@ -74,45 +74,45 @@ handle_bounce (void *cls,
74 * @param error error code 74 * @param error error code
75 */ 75 */
76static void 76static void
77mq_error_handler (void *cls, 77mq_error_handler(void *cls,
78 enum GNUNET_MQ_Error error) 78 enum GNUNET_MQ_Error error)
79{ 79{
80 GNUNET_assert (0); /* should never happen */ 80 GNUNET_assert(0); /* should never happen */
81} 81}
82 82
83 83
84static void 84static void
85task (void *cls, 85task(void *cls,
86 const struct GNUNET_CONFIGURATION_Handle *cfg, 86 const struct GNUNET_CONFIGURATION_Handle *cfg,
87 struct GNUNET_SERVICE_Handle *sh) 87 struct GNUNET_SERVICE_Handle *sh)
88{ 88{
89 struct GNUNET_MQ_MessageHandler chandlers[] = { 89 struct GNUNET_MQ_MessageHandler chandlers[] = {
90 GNUNET_MQ_hd_fixed_size (bounce, 90 GNUNET_MQ_hd_fixed_size(bounce,
91 MY_TYPE, 91 MY_TYPE,
92 struct GNUNET_MessageHeader, 92 struct GNUNET_MessageHeader,
93 cls), 93 cls),
94 GNUNET_MQ_handler_end () 94 GNUNET_MQ_handler_end()
95 }; 95 };
96 struct GNUNET_MQ_Envelope *env; 96 struct GNUNET_MQ_Envelope *env;
97 struct GNUNET_MessageHeader *msg; 97 struct GNUNET_MessageHeader *msg;
98 98
99 /* test that ill-configured client fails instantly */ 99 /* test that ill-configured client fails instantly */
100 GNUNET_assert (NULL == 100 GNUNET_assert(NULL ==
101 GNUNET_CLIENT_connect (cfg, 101 GNUNET_CLIENT_connect(cfg,
102 "invalid-service", 102 "invalid-service",
103 NULL, 103 NULL,
104 &mq_error_handler, 104 &mq_error_handler,
105 NULL)); 105 NULL));
106 client_mq = GNUNET_CLIENT_connect (cfg, 106 client_mq = GNUNET_CLIENT_connect(cfg,
107 "test_client", 107 "test_client",
108 chandlers, 108 chandlers,
109 &mq_error_handler, 109 &mq_error_handler,
110 NULL); 110 NULL);
111 GNUNET_assert (NULL != client_mq); 111 GNUNET_assert(NULL != client_mq);
112 env = GNUNET_MQ_msg (msg, 112 env = GNUNET_MQ_msg(msg,
113 MY_TYPE); 113 MY_TYPE);
114 GNUNET_MQ_send (client_mq, 114 GNUNET_MQ_send(client_mq,
115 env); 115 env);
116} 116}
117 117
118 118
@@ -125,9 +125,9 @@ task (void *cls,
125 * @return @a c 125 * @return @a c
126 */ 126 */
127static void * 127static void *
128connect_cb (void *cls, 128connect_cb(void *cls,
129 struct GNUNET_SERVICE_Client *c, 129 struct GNUNET_SERVICE_Client *c,
130 struct GNUNET_MQ_Handle *mq) 130 struct GNUNET_MQ_Handle *mq)
131{ 131{
132 return c; 132 return c;
133} 133}
@@ -139,55 +139,55 @@ connect_cb (void *cls,
139 * @param cls our service name 139 * @param cls our service name
140 * @param c disconnecting client 140 * @param c disconnecting client
141 * @param internal_cls must match @a c 141 * @param internal_cls must match @a c
142 */ 142 */
143static void 143static void
144disconnect_cb (void *cls, 144disconnect_cb(void *cls,
145 struct GNUNET_SERVICE_Client *c, 145 struct GNUNET_SERVICE_Client *c,
146 void *internal_cls) 146 void *internal_cls)
147{ 147{
148 if (2 == global_ret) 148 if (2 == global_ret)
149 { 149 {
150 GNUNET_SCHEDULER_shutdown (); 150 GNUNET_SCHEDULER_shutdown();
151 global_ret = 0; 151 global_ret = 0;
152 } 152 }
153} 153}
154 154
155 155
156int 156int
157main (int argc, 157main(int argc,
158 char *argv[]) 158 char *argv[])
159{ 159{
160 struct GNUNET_MQ_MessageHandler shandlers[] = { 160 struct GNUNET_MQ_MessageHandler shandlers[] = {
161 GNUNET_MQ_hd_fixed_size (echo, 161 GNUNET_MQ_hd_fixed_size(echo,
162 MY_TYPE, 162 MY_TYPE,
163 struct GNUNET_MessageHeader, 163 struct GNUNET_MessageHeader,
164 NULL), 164 NULL),
165 GNUNET_MQ_handler_end () 165 GNUNET_MQ_handler_end()
166 }; 166 };
167 char * test_argv[] = { 167 char * test_argv[] = {
168 (char *) "test_client", 168 (char *)"test_client",
169 "-c", 169 "-c",
170 "test_client_data.conf", 170 "test_client_data.conf",
171 NULL 171 NULL
172 }; 172 };
173 173
174 GNUNET_log_setup ("test_client", 174 GNUNET_log_setup("test_client",
175 "WARNING", 175 "WARNING",
176 NULL); 176 NULL);
177 if (0 != strstr (argv[0], 177 if (0 != strstr(argv[0],
178 "unix")) 178 "unix"))
179 test_argv[2] = "test_client_unix.conf"; 179 test_argv[2] = "test_client_unix.conf";
180 global_ret = 1; 180 global_ret = 1;
181 if (0 != 181 if (0 !=
182 GNUNET_SERVICE_run_ (3, 182 GNUNET_SERVICE_run_(3,
183 test_argv, 183 test_argv,
184 "test_client", 184 "test_client",
185 GNUNET_SERVICE_OPTION_NONE, 185 GNUNET_SERVICE_OPTION_NONE,
186 &task, 186 &task,
187 &connect_cb, 187 &connect_cb,
188 &disconnect_cb, 188 &disconnect_cb,
189 NULL, 189 NULL,
190 shandlers)) 190 shandlers))
191 global_ret = 3; 191 global_ret = 3;
192 return global_ret; 192 return global_ret;
193} 193}
diff --git a/src/util/test_common_allocation.c b/src/util/test_common_allocation.c
index fcc453d6b..e67360044 100644
--- a/src/util/test_common_allocation.c
+++ b/src/util/test_common_allocation.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_common_allocation.c 22 * @file util/test_common_allocation.c
@@ -27,7 +27,7 @@
27 27
28 28
29static int 29static int
30check () 30check()
31{ 31{
32#define MAX_TESTVAL 1024 32#define MAX_TESTVAL 1024
33 char *ptrs[MAX_TESTVAL]; 33 char *ptrs[MAX_TESTVAL];
@@ -41,112 +41,112 @@ check ()
41 /* GNUNET_malloc/GNUNET_free test */ 41 /* GNUNET_malloc/GNUNET_free test */
42 k = 352; /* random start value */ 42 k = 352; /* random start value */
43 for (i = 1; i < MAX_TESTVAL; i++) 43 for (i = 1; i < MAX_TESTVAL; i++)
44 { 44 {
45 ptrs[i] = GNUNET_malloc (i); 45 ptrs[i] = GNUNET_malloc(i);
46 for (j = 0; j < i; j++) 46 for (j = 0; j < i; j++)
47 ptrs[i][j] = k++; 47 ptrs[i][j] = k++;
48 } 48 }
49 49
50 for (i = MAX_TESTVAL - 1; i >= 1; i--) 50 for (i = MAX_TESTVAL - 1; i >= 1; i--)
51 { 51 {
52 for (j = i - 1; j >= 0; j--) 52 for (j = i - 1; j >= 0; j--)
53 if (ptrs[i][j] != (char) --k) 53 if (ptrs[i][j] != (char)--k)
54 return 1; 54 return 1;
55 GNUNET_free (ptrs[i]); 55 GNUNET_free(ptrs[i]);
56 } 56 }
57 57
58 /* GNUNET_free_non_null test */ 58 /* GNUNET_free_non_null test */
59 GNUNET_free_non_null (NULL); 59 GNUNET_free_non_null(NULL);
60 GNUNET_free_non_null (GNUNET_malloc (4)); 60 GNUNET_free_non_null(GNUNET_malloc(4));
61 61
62 /* GNUNET_strdup tests */ 62 /* GNUNET_strdup tests */
63 ptrs[0] = GNUNET_strdup ("bar"); 63 ptrs[0] = GNUNET_strdup("bar");
64 if (0 != strcmp (ptrs[0], "bar")) 64 if (0 != strcmp(ptrs[0], "bar"))
65 return 3; 65 return 3;
66 /* now realloc */ 66 /* now realloc */
67 ptrs[0] = GNUNET_realloc (ptrs[0], 12); 67 ptrs[0] = GNUNET_realloc(ptrs[0], 12);
68 strcpy (ptrs[0], "Hello World"); 68 strcpy(ptrs[0], "Hello World");
69 69
70 GNUNET_free (ptrs[0]); 70 GNUNET_free(ptrs[0]);
71 GNUNET_asprintf (&ptrs[0], "%s %s", "Hello", "World"); 71 GNUNET_asprintf(&ptrs[0], "%s %s", "Hello", "World");
72 GNUNET_assert (strlen (ptrs[0]) == 11); 72 GNUNET_assert(strlen(ptrs[0]) == 11);
73 GNUNET_free (ptrs[0]); 73 GNUNET_free(ptrs[0]);
74 74
75 /* GNUNET_array_grow tests */ 75 /* GNUNET_array_grow tests */
76 ptrs[0] = NULL; 76 ptrs[0] = NULL;
77 ui = 0; 77 ui = 0;
78 GNUNET_array_grow (ptrs[0], ui, 42); 78 GNUNET_array_grow(ptrs[0], ui, 42);
79 if (ui != 42) 79 if (ui != 42)
80 return 4; 80 return 4;
81 GNUNET_array_grow (ptrs[0], ui, 22); 81 GNUNET_array_grow(ptrs[0], ui, 22);
82 if (ui != 22) 82 if (ui != 22)
83 return 5; 83 return 5;
84 for (j = 0; j < 22; j++) 84 for (j = 0; j < 22; j++)
85 ptrs[0][j] = j; 85 ptrs[0][j] = j;
86 GNUNET_array_grow (ptrs[0], ui, 32); 86 GNUNET_array_grow(ptrs[0], ui, 32);
87 for (j = 0; j < 22; j++) 87 for (j = 0; j < 22; j++)
88 if (ptrs[0][j] != j) 88 if (ptrs[0][j] != j)
89 return 6; 89 return 6;
90 for (j = 22; j < 32; j++) 90 for (j = 22; j < 32; j++)
91 if (ptrs[0][j] != 0) 91 if (ptrs[0][j] != 0)
92 return 7; 92 return 7;
93 GNUNET_array_grow (ptrs[0], ui, 0); 93 GNUNET_array_grow(ptrs[0], ui, 0);
94 if (i != 0) 94 if (i != 0)
95 return 8; 95 return 8;
96 if (ptrs[0] != NULL) 96 if (ptrs[0] != NULL)
97 return 9; 97 return 9;
98 98
99 /* GNUNET_new_array_2d tests */ 99 /* GNUNET_new_array_2d tests */
100 a2 = GNUNET_new_array_2d (17, 22, unsigned int); 100 a2 = GNUNET_new_array_2d(17, 22, unsigned int);
101 for (i = 0; i < 17; i++) 101 for (i = 0; i < 17; i++)
102 {
103 for (j = 0; j < 22; j++)
104 { 102 {
105 if (0 != a2[i][j]) 103 for (j = 0; j < 22; j++)
106 { 104 {
107 GNUNET_free (a2); 105 if (0 != a2[i][j])
108 return 10; 106 {
109 } 107 GNUNET_free(a2);
110 a2[i][j] = i * 100 + j; 108 return 10;
109 }
110 a2[i][j] = i * 100 + j;
111 }
111 } 112 }
112 } 113 GNUNET_free(a2);
113 GNUNET_free (a2);
114 114
115 /* GNUNET_new_array_3d tests */ 115 /* GNUNET_new_array_3d tests */
116 a3 = GNUNET_new_array_3d (2, 3, 4, char); 116 a3 = GNUNET_new_array_3d(2, 3, 4, char);
117 for (i = 0; i < 2; i++) 117 for (i = 0; i < 2; i++)
118 {
119 for (j = 0; j < 3; j++)
120 { 118 {
121 for (k = 0; k < 4; k++) 119 for (j = 0; j < 3; j++)
122 {
123 if (0 != a3[i][j][k])
124 { 120 {
125 GNUNET_free (a3); 121 for (k = 0; k < 4; k++)
126 return 11; 122 {
123 if (0 != a3[i][j][k])
124 {
125 GNUNET_free(a3);
126 return 11;
127 }
128 a3[i][j][k] = i * 100 + j * 10 + k;
129 }
127 } 130 }
128 a3[i][j][k] = i * 100 + j * 10 + k;
129 }
130 } 131 }
131 } 132 GNUNET_free(a3);
132 GNUNET_free (a3);
133 return 0; 133 return 0;
134} 134}
135 135
136 136
137int 137int
138main (int argc, char *argv[]) 138main(int argc, char *argv[])
139{ 139{
140 int ret; 140 int ret;
141 141
142 GNUNET_log_setup ("test-common-allocation", 142 GNUNET_log_setup("test-common-allocation",
143 "WARNING", 143 "WARNING",
144 NULL); 144 NULL);
145 ret = check (); 145 ret = check();
146 if (ret != 0) 146 if (ret != 0)
147 fprintf (stderr, 147 fprintf(stderr,
148 "ERROR %d.\n", 148 "ERROR %d.\n",
149 ret); 149 ret);
150 return ret; 150 return ret;
151} 151}
152 152
diff --git a/src/util/test_common_endian.c b/src/util/test_common_endian.c
index 6e08b4f07..02de4b5c6 100644
--- a/src/util/test_common_endian.c
+++ b/src/util/test_common_endian.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_common_endian.c 21 * @file util/test_common_endian.c
22 * @brief testcase for common_endian.c 22 * @brief testcase for common_endian.c
@@ -27,14 +27,14 @@
27#define CHECK(n) if (n != GNUNET_htonll(GNUNET_ntohll(n))) return 1; 27#define CHECK(n) if (n != GNUNET_htonll(GNUNET_ntohll(n))) return 1;
28 28
29int 29int
30main (int argc, char *argv[]) 30main(int argc, char *argv[])
31{ 31{
32 GNUNET_log_setup ("test-common-endian", "WARNING", NULL); 32 GNUNET_log_setup("test-common-endian", "WARNING", NULL);
33 CHECK (1); 33 CHECK(1);
34 CHECK (0x12345678); 34 CHECK(0x12345678);
35 CHECK (123456789012345LL); 35 CHECK(123456789012345LL);
36 if ((0x1234567890ABCDEFLL != GNUNET_htonll (0xEFCDAB9078563412LL)) && 36 if ((0x1234567890ABCDEFLL != GNUNET_htonll(0xEFCDAB9078563412LL)) &&
37 42 != htonl (42)) 37 42 != htonl(42))
38 return 1; 38 return 1;
39 return 0; 39 return 0;
40} 40}
diff --git a/src/util/test_common_logging.c b/src/util/test_common_logging.c
index 6ae50b36b..8492d3c35 100644
--- a/src/util/test_common_logging.c
+++ b/src/util/test_common_logging.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_common_logging.c 22 * @file util/test_common_logging.c
@@ -27,8 +27,8 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29static void 29static void
30my_log (void *ctx, enum GNUNET_ErrorType kind, const char *component, 30my_log(void *ctx, enum GNUNET_ErrorType kind, const char *component,
31 const char *date, const char *msg) 31 const char *date, const char *msg)
32{ 32{
33 unsigned int *c = ctx; 33 unsigned int *c = ctx;
34 34
@@ -38,61 +38,61 @@ my_log (void *ctx, enum GNUNET_ErrorType kind, const char *component,
38 38
39 39
40int 40int
41main (int argc, char *argv[]) 41main(int argc, char *argv[])
42{ 42{
43 unsigned int failureCount = 0; 43 unsigned int failureCount = 0;
44 unsigned int logs = 0; 44 unsigned int logs = 0;
45 45
46 if (0 != putenv ("GNUNET_FORCE_LOG=")) 46 if (0 != putenv("GNUNET_FORCE_LOG="))
47 fprintf (stderr, "Failed to putenv: %s\n", strerror (errno)); 47 fprintf(stderr, "Failed to putenv: %s\n", strerror(errno));
48 GNUNET_log_setup ("test-common-logging", "DEBUG", "/dev/null"); 48 GNUNET_log_setup("test-common-logging", "DEBUG", "/dev/null");
49 GNUNET_logger_add (&my_log, &logs); 49 GNUNET_logger_add(&my_log, &logs);
50 GNUNET_logger_add (&my_log, &logs); 50 GNUNET_logger_add(&my_log, &logs);
51 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 51 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
52 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 52 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
53 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 53 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
54 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 54 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
55 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 55 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
56 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Testing...\n"); 56 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Testing...\n");
57 GNUNET_logger_remove (&my_log, &logs); 57 GNUNET_logger_remove(&my_log, &logs);
58 GNUNET_log (GNUNET_ERROR_TYPE_BULK, "Flusher...\n"); 58 GNUNET_log(GNUNET_ERROR_TYPE_BULK, "Flusher...\n");
59 /* the last 6 calls should be merged (repated bulk messages!) */ 59 /* the last 6 calls should be merged (repated bulk messages!) */
60 GNUNET_logger_remove (&my_log, &logs); 60 GNUNET_logger_remove(&my_log, &logs);
61 if (logs != 4) 61 if (logs != 4)
62 { 62 {
63 fprintf (stdout, "Expected 4 log calls, got %u\n", logs); 63 fprintf(stdout, "Expected 4 log calls, got %u\n", logs);
64 failureCount++; 64 failureCount++;
65 } 65 }
66 GNUNET_break (0 == 66 GNUNET_break(0 ==
67 strcmp (_("ERROR"), 67 strcmp(_("ERROR"),
68 GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_ERROR))); 68 GNUNET_error_type_to_string(GNUNET_ERROR_TYPE_ERROR)));
69 GNUNET_break (0 == 69 GNUNET_break(0 ==
70 strcmp (_("WARNING"), 70 strcmp(_("WARNING"),
71 GNUNET_error_type_to_string 71 GNUNET_error_type_to_string
72 (GNUNET_ERROR_TYPE_WARNING))); 72 (GNUNET_ERROR_TYPE_WARNING)));
73 GNUNET_break (0 == 73 GNUNET_break(0 ==
74 strcmp (_("INFO"), 74 strcmp(_("INFO"),
75 GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_INFO))); 75 GNUNET_error_type_to_string(GNUNET_ERROR_TYPE_INFO)));
76 GNUNET_break (0 == 76 GNUNET_break(0 ==
77 strcmp (_("DEBUG"), 77 strcmp(_("DEBUG"),
78 GNUNET_error_type_to_string (GNUNET_ERROR_TYPE_DEBUG))); 78 GNUNET_error_type_to_string(GNUNET_ERROR_TYPE_DEBUG)));
79 GNUNET_log_setup ("test_common_logging", "WARNING", "/dev/null"); 79 GNUNET_log_setup("test_common_logging", "WARNING", "/dev/null");
80 logs = 0; 80 logs = 0;
81 GNUNET_logger_add (&my_log, &logs); 81 GNUNET_logger_add(&my_log, &logs);
82 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Checker...\n"); 82 GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Checker...\n");
83 GNUNET_log (GNUNET_ERROR_TYPE_INFO, "Drop me...\n"); 83 GNUNET_log(GNUNET_ERROR_TYPE_INFO, "Drop me...\n");
84 GNUNET_logger_remove (&my_log, &logs); 84 GNUNET_logger_remove(&my_log, &logs);
85 if (logs != 1) 85 if (logs != 1)
86 { 86 {
87 fprintf (stdout, "Expected 1 log call, got %u\n", logs); 87 fprintf(stdout, "Expected 1 log call, got %u\n", logs);
88 failureCount++; 88 failureCount++;
89 } 89 }
90 90
91 if (failureCount != 0) 91 if (failureCount != 0)
92 { 92 {
93 fprintf (stdout, "%u TESTS FAILED!\n", failureCount); 93 fprintf(stdout, "%u TESTS FAILED!\n", failureCount);
94 return -1; 94 return -1;
95 } 95 }
96 return 0; 96 return 0;
97} /* end of main */ 97} /* end of main */
98 98
diff --git a/src/util/test_common_logging_dummy.c b/src/util/test_common_logging_dummy.c
index d3c6e3452..dc80eeccd 100644
--- a/src/util/test_common_logging_dummy.c
+++ b/src/util/test_common_logging_dummy.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_common_logging_dummy.c 22 * @file util/test_common_logging_dummy.c
@@ -36,31 +36,31 @@
36 * on a slow machine for a non-skipped one. 36 * on a slow machine for a non-skipped one.
37 */ 37 */
38#define OUTPUT_DELAY \ 38#define OUTPUT_DELAY \
39 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, 1000) 39 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MICROSECONDS, 1000)
40 40
41static void 41static void
42my_log (void *ctx, 42my_log(void *ctx,
43 enum GNUNET_ErrorType kind, 43 enum GNUNET_ErrorType kind,
44 const char *component, 44 const char *component,
45 const char *date, 45 const char *date,
46 const char *msg) 46 const char *msg)
47{ 47{
48 (void) ctx; 48 (void)ctx;
49 (void) kind; 49 (void)kind;
50 (void) component; 50 (void)component;
51 (void) date; 51 (void)date;
52 if (strncmp ("test-common-logging-dummy", component, 25) != 0) 52 if (strncmp("test-common-logging-dummy", component, 25) != 0)
53 return; 53 return;
54 fprintf (stdout, "%s", msg); 54 fprintf(stdout, "%s", msg);
55 fflush (stdout); 55 fflush(stdout);
56} 56}
57 57
58 58
59#if ! defined(GNUNET_CULL_LOGGING) 59#if !defined(GNUNET_CULL_LOGGING)
60static int 60static int
61expensive_func () 61expensive_func()
62{ 62{
63 return GNUNET_NETWORK_socket_select (NULL, NULL, NULL, OUTPUT_DELAY); 63 return GNUNET_NETWORK_socket_select(NULL, NULL, NULL, OUTPUT_DELAY);
64} 64}
65#endif 65#endif
66 66
@@ -68,51 +68,51 @@ expensive_func ()
68#define pr(kind, lvl) \ 68#define pr(kind, lvl) \
69 { \ 69 { \
70 struct GNUNET_TIME_Absolute t1, t2; \ 70 struct GNUNET_TIME_Absolute t1, t2; \
71 t1 = GNUNET_TIME_absolute_get (); \ 71 t1 = GNUNET_TIME_absolute_get(); \
72 GNUNET_log (kind, "L%s %d\n", lvl, expensive_func ()); \ 72 GNUNET_log(kind, "L%s %d\n", lvl, expensive_func()); \
73 t2 = GNUNET_TIME_absolute_get (); \ 73 t2 = GNUNET_TIME_absolute_get(); \
74 printf ("1%s %llu\n", \ 74 printf("1%s %llu\n", \
75 lvl, \ 75 lvl, \
76 (unsigned long long) GNUNET_TIME_absolute_get_difference (t1, t2) \ 76 (unsigned long long)GNUNET_TIME_absolute_get_difference(t1, t2) \
77 .rel_value_us); \ 77 .rel_value_us); \
78 } 78 }
79 79
80#define pr2(kind, lvl) \ 80#define pr2(kind, lvl) \
81 { \ 81 { \
82 struct GNUNET_TIME_Absolute t1, t2; \ 82 struct GNUNET_TIME_Absolute t1, t2; \
83 t1 = GNUNET_TIME_absolute_get (); \ 83 t1 = GNUNET_TIME_absolute_get(); \
84 GNUNET_log (kind, "L%s %d\n", lvl, expensive_func ()); \ 84 GNUNET_log(kind, "L%s %d\n", lvl, expensive_func()); \
85 t2 = GNUNET_TIME_absolute_get (); \ 85 t2 = GNUNET_TIME_absolute_get(); \
86 printf ("2%s %llu\n", \ 86 printf("2%s %llu\n", \
87 lvl, \ 87 lvl, \
88 (unsigned long long) GNUNET_TIME_absolute_get_difference (t1, t2) \ 88 (unsigned long long)GNUNET_TIME_absolute_get_difference(t1, t2) \
89 .rel_value_us); \ 89 .rel_value_us); \
90 } 90 }
91 91
92 92
93int 93int
94main (int argc, char *argv[]) 94main(int argc, char *argv[])
95{ 95{
96 (void) argc; 96 (void)argc;
97 (void) argv; 97 (void)argv;
98 /* We set up logging with NULL level - will be overrided by 98 /* We set up logging with NULL level - will be overrided by
99 * GNUNET_LOG or GNUNET_FORCE_LOG at runtime. 99 * GNUNET_LOG or GNUNET_FORCE_LOG at runtime.
100 */ 100 */
101 GNUNET_log_setup ("test-common-logging-dummy", NULL, "/dev/null"); 101 GNUNET_log_setup("test-common-logging-dummy", NULL, "/dev/null");
102 GNUNET_logger_add (&my_log, NULL); 102 GNUNET_logger_add(&my_log, NULL);
103 pr (GNUNET_ERROR_TYPE_ERROR, "ERROR"); 103 pr(GNUNET_ERROR_TYPE_ERROR, "ERROR");
104 pr (GNUNET_ERROR_TYPE_WARNING, "WARNING"); 104 pr(GNUNET_ERROR_TYPE_WARNING, "WARNING");
105 pr (GNUNET_ERROR_TYPE_INFO, "INFO"); 105 pr(GNUNET_ERROR_TYPE_INFO, "INFO");
106 pr (GNUNET_ERROR_TYPE_DEBUG, "DEBUG"); 106 pr(GNUNET_ERROR_TYPE_DEBUG, "DEBUG");
107 107
108 /* We set up logging with WARNING level - will onle be overrided by 108 /* We set up logging with WARNING level - will onle be overrided by
109 * GNUNET_FORCE_LOG at runtime. 109 * GNUNET_FORCE_LOG at runtime.
110 */ 110 */
111 GNUNET_log_setup ("test-common-logging-dummy", "WARNING", "/dev/null"); 111 GNUNET_log_setup("test-common-logging-dummy", "WARNING", "/dev/null");
112 pr2 (GNUNET_ERROR_TYPE_ERROR, "ERROR"); 112 pr2(GNUNET_ERROR_TYPE_ERROR, "ERROR");
113 pr2 (GNUNET_ERROR_TYPE_WARNING, "WARNING"); 113 pr2(GNUNET_ERROR_TYPE_WARNING, "WARNING");
114 pr2 (GNUNET_ERROR_TYPE_INFO, "INFO"); 114 pr2(GNUNET_ERROR_TYPE_INFO, "INFO");
115 pr2 (GNUNET_ERROR_TYPE_DEBUG, "DEBUG"); 115 pr2(GNUNET_ERROR_TYPE_DEBUG, "DEBUG");
116 return 0; 116 return 0;
117} /* end of main */ 117} /* end of main */
118 118
diff --git a/src/util/test_common_logging_runtime_loglevels.c b/src/util/test_common_logging_runtime_loglevels.c
index 8da808760..f46776c8f 100644
--- a/src/util/test_common_logging_runtime_loglevels.c
+++ b/src/util/test_common_logging_runtime_loglevels.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_common_logging_runtime_loglevels.c 22 * @file util/test_common_logging_runtime_loglevels.c
@@ -32,13 +32,13 @@
32 * How much time the child is allowed to waste on skipped log calls, at most. 32 * How much time the child is allowed to waste on skipped log calls, at most.
33 * Raspberry Pi takes 113 microseconds tops, this is 3x that value. 33 * Raspberry Pi takes 113 microseconds tops, this is 3x that value.
34 */ 34 */
35#define MAX_SKIP_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, 400).rel_value_us 35#define MAX_SKIP_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MICROSECONDS, 400).rel_value_us
36 36
37/** 37/**
38 * How much time non-skipped log call should take, at least. 38 * How much time non-skipped log call should take, at least.
39 * Keep in sync with the value in the dummy! 39 * Keep in sync with the value in the dummy!
40 */ 40 */
41#define OUTPUT_DELAY GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, 1000).rel_value_us 41#define OUTPUT_DELAY GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MICROSECONDS, 1000).rel_value_us
42 42
43static int ok; 43static int ok;
44 44
@@ -54,51 +54,51 @@ static struct GNUNET_SCHEDULER_Task * die_task;
54static struct GNUNET_SCHEDULER_Task * read_task; 54static struct GNUNET_SCHEDULER_Task * read_task;
55 55
56static void 56static void
57runone (void); 57runone(void);
58 58
59 59
60static void 60static void
61end_task (void *cls) 61end_task(void *cls)
62{ 62{
63 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Ending phase %d, ok is %d\n", phase, 63 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Ending phase %d, ok is %d\n", phase,
64 ok); 64 ok);
65 if (NULL != proc) 65 if (NULL != proc)
66 {
67 if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG))
68 { 66 {
69 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); 67 if (0 != GNUNET_OS_process_kill(proc, GNUNET_TERM_SIG))
68 {
69 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
70 }
71 GNUNET_OS_process_wait(proc);
72 GNUNET_OS_process_destroy(proc);
73 proc = NULL;
70 } 74 }
71 GNUNET_OS_process_wait (proc);
72 GNUNET_OS_process_destroy (proc);
73 proc = NULL;
74 }
75 if (NULL != read_task) 75 if (NULL != read_task)
76 { 76 {
77 GNUNET_SCHEDULER_cancel (read_task); 77 GNUNET_SCHEDULER_cancel(read_task);
78 read_task = NULL; 78 read_task = NULL;
79 } 79 }
80 GNUNET_DISK_pipe_close (pipe_stdout); 80 GNUNET_DISK_pipe_close(pipe_stdout);
81 if (ok == 1) 81 if (ok == 1)
82 {
83 if (phase < 9)
84 { 82 {
85 phase += 1; 83 if (phase < 9)
86 runone (); 84 {
85 phase += 1;
86 runone();
87 }
88 else
89 ok = 0;
87 } 90 }
88 else
89 ok = 0;
90 }
91 else 91 else
92 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "failing\n"); 92 GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "failing\n");
93} 93}
94 94
95 95
96static char * 96static char *
97read_output_line (int phase_from1, int phase_to1, int phase_from2, 97read_output_line(int phase_from1, int phase_to1, int phase_from2,
98 int phase_to2, char c, const char *expect_level, 98 int phase_to2, char c, const char *expect_level,
99 long delay_morethan, long delay_lessthan, int phase, 99 long delay_morethan, long delay_lessthan, int phase,
100 char *p, 100 char *p,
101 int *len, long *delay, char level[8]) 101 int *len, long *delay, char level[8])
102{ 102{
103 char *r = p; 103 char *r = p;
104 char t[7]; 104 char t[7];
@@ -115,61 +115,63 @@ read_output_line (int phase_from1, int phase_to1, int phase_from2,
115 !(phase >= phase_from2 && phase <= phase_to2)) 115 !(phase >= phase_from2 && phase <= phase_to2))
116 return p; 116 return p;
117#if 0 117#if 0
118 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 118 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
119 "Trying to match '%c%s \\d\\r\\n' on %s\n", c, expect_level, p); 119 "Trying to match '%c%s \\d\\r\\n' on %s\n", c, expect_level, p);
120#endif 120#endif
121 for (i = 0; i < *len && !stop; i++) 121 for (i = 0; i < *len && !stop; i++)
122 {
123 switch (stage)
124 { 122 {
125 case 0: /* read first char */ 123 switch (stage)
126 if (r[i] != c) 124 {
127 { 125 case 0: /* read first char */
128 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, "Expected '%c', but got '%c'\n", c, 126 if (r[i] != c)
129 r[i]); 127 {
130 GNUNET_break (0); 128 GNUNET_log(GNUNET_ERROR_TYPE_ERROR, "Expected '%c', but got '%c'\n", c,
131 return NULL; 129 r[i]);
132 } 130 GNUNET_break(0);
133 stage += 1; 131 return NULL;
134 break; 132 }
135 case 1: /* read at most 7 char-long error level string, finished by ' ' */ 133 stage += 1;
136 if (r[i] == ' ') 134 break;
137 { 135
138 level[j] = '\0'; 136 case 1: /* read at most 7 char-long error level string, finished by ' ' */
139 stage += 1; 137 if (r[i] == ' ')
140 j = 0; 138 {
141 } 139 level[j] = '\0';
142 else if (i == 8) 140 stage += 1;
143 { 141 j = 0;
144 GNUNET_break (0); 142 }
145 ok = 2; 143 else if (i == 8)
146 return NULL; 144 {
147 } 145 GNUNET_break(0);
148 else 146 ok = 2;
149 level[j++] = r[i]; 147 return NULL;
150 break; 148 }
151 case 2: /* read the delay, finished by '\n' */ 149 else
152 t[j++] = r[i]; 150 level[j++] = r[i];
151 break;
152
153 case 2: /* read the delay, finished by '\n' */
154 t[j++] = r[i];
153#if WINDOWS 155#if WINDOWS
154 if (r[i] == '\r' && r[i + 1] == '\n') 156 if (r[i] == '\r' && r[i + 1] == '\n')
155 { 157 {
156 i += 1; 158 i += 1;
157 t[j - 1] = '\0'; 159 t[j - 1] = '\0';
158 *delay = strtol (t, NULL, 10); 160 *delay = strtol(t, NULL, 10);
159 stop = 1; 161 stop = 1;
160 } 162 }
161#else 163#else
162 if (r[i] == '\n') 164 if (r[i] == '\n')
163 { 165 {
164 t[j - 1] = '\0'; 166 t[j - 1] = '\0';
165 *delay = strtol (t, NULL, 10); 167 *delay = strtol(t, NULL, 10);
166 stop = 1; 168 stop = 1;
167 } 169 }
168#endif 170#endif
169 break; 171 break;
172 }
170 } 173 }
171 } 174 level_matches = (strcmp(expect_level, level) == 0);
172 level_matches = (strcmp (expect_level, level) == 0);
173 delay_is_sane = (*delay >= 0) && (*delay <= 1000000); 175 delay_is_sane = (*delay >= 0) && (*delay <= 1000000);
174 delay_is_a_dummy = (c == 'L'); 176 delay_is_a_dummy = (c == 'L');
175 /* Delay must be either less than 'lessthan' (log call is skipped) 177 /* Delay must be either less than 'lessthan' (log call is skipped)
@@ -179,22 +181,22 @@ read_output_line (int phase_from1, int phase_to1, int phase_from2,
179 if (delay_is_a_dummy) 181 if (delay_is_a_dummy)
180 delay_outside_of_range = 1; 182 delay_outside_of_range = 1;
181 183
182 if (! stop) 184 if (!stop)
183 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 185 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
184 "Wrong log format?\n"); 186 "Wrong log format?\n");
185 if (! level_matches) 187 if (!level_matches)
186 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 188 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
187 "Wrong log level\n"); 189 "Wrong log level\n");
188 if (! delay_is_sane) 190 if (!delay_is_sane)
189 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 191 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
190 "Delay %ld is insane\n", 192 "Delay %ld is insane\n",
191 *delay); 193 *delay);
192 if (! delay_outside_of_range) 194 if (!delay_outside_of_range)
193 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 195 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
194 "Delay %ld is not outside of range (%ld ; %ld)\n", 196 "Delay %ld is not outside of range (%ld ; %ld)\n",
195 *delay, 197 *delay,
196 delay_lessthan, 198 delay_lessthan,
197 delay_morethan); 199 delay_morethan);
198 if (!stop || !level_matches || !delay_is_sane || !delay_outside_of_range) 200 if (!stop || !level_matches || !delay_is_sane || !delay_outside_of_range)
199 return NULL; 201 return NULL;
200 *len = *len - i; 202 *len = *len - i;
@@ -221,7 +223,7 @@ static int bytes;
221 223
222 224
223static void 225static void
224read_call (void *cls) 226read_call(void *cls)
225{ 227{
226 const struct GNUNET_DISK_FileHandle *stdout_read_handle = cls; 228 const struct GNUNET_DISK_FileHandle *stdout_read_handle = cls;
227 char level[8]; 229 char level[8];
@@ -230,24 +232,24 @@ read_call (void *cls)
230 int rd; 232 int rd;
231 233
232 read_task = NULL; 234 read_task = NULL;
233 rd = GNUNET_DISK_file_read (stdout_read_handle, buf_ptr, 235 rd = GNUNET_DISK_file_read(stdout_read_handle, buf_ptr,
234 sizeof (buf) - bytes); 236 sizeof(buf) - bytes);
235 if (rd > 0) 237 if (rd > 0)
236 { 238 {
237 buf_ptr += rd; 239 buf_ptr += rd;
238 bytes += rd; 240 bytes += rd;
239#if VERBOSE 241#if VERBOSE
240 fprintf (stderr, "got %d bytes, reading more\n", rd); 242 fprintf(stderr, "got %d bytes, reading more\n", rd);
241#endif 243#endif
242 read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 244 read_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
243 stdout_read_handle, 245 stdout_read_handle,
244 &read_call, 246 &read_call,
245 (void*) stdout_read_handle); 247 (void*)stdout_read_handle);
246 return; 248 return;
247 } 249 }
248 250
249#if VERBOSE 251#if VERBOSE
250 fprintf (stderr, "bytes is %d:%s\n", bytes, buf); 252 fprintf(stderr, "bytes is %d:%s\n", bytes, buf);
251#endif 253#endif
252 254
253 /* +------CHILD OUTPUT-- 255 /* +------CHILD OUTPUT--
@@ -269,186 +271,195 @@ read_call (void *cls)
269 271
270 if (bytes == LOG_BUFFER_SIZE || 272 if (bytes == LOG_BUFFER_SIZE ||
271 !(p = 273 !(p =
272 read_output_line (0, 3, 4, 9, 'L', "ERROR", -1, 274 read_output_line(0, 3, 4, 9, 'L', "ERROR", -1,
273 1, phase, p, 275 1, phase, p,
274 &bytes, &delay, level)) || 276 &bytes, &delay, level)) ||
275 !(p = 277 !(p =
276 read_output_line (0, 3, 4, 9, '1', "ERROR", OUTPUT_DELAY, 278 read_output_line(0, 3, 4, 9, '1', "ERROR", OUTPUT_DELAY,
277 MAX_SKIP_DELAY, phase, p, 279 MAX_SKIP_DELAY, phase, p,
278 &bytes, &delays[0], level)) || 280 &bytes, &delays[0], level)) ||
279 !(p = 281 !(p =
280 read_output_line (1, 3, 5, 9, 'L', "WARNING", -1, 282 read_output_line(1, 3, 5, 9, 'L', "WARNING", -1,
281 1, phase, p, 283 1, phase, p,
282 &bytes, &delay, level)) || 284 &bytes, &delay, level)) ||
283 !(p = 285 !(p =
284 read_output_line (0, 3, 4, 9, '1', "WARNING", OUTPUT_DELAY, 286 read_output_line(0, 3, 4, 9, '1', "WARNING", OUTPUT_DELAY,
285 MAX_SKIP_DELAY, phase, p, 287 MAX_SKIP_DELAY, phase, p,
286 &bytes, &delays[1], level)) || 288 &bytes, &delays[1], level)) ||
287 !(p = 289 !(p =
288 read_output_line (2, 3, 6, 7, 'L', "INFO", -1, 290 read_output_line(2, 3, 6, 7, 'L', "INFO", -1,
289 1, phase, p, 291 1, phase, p,
290 &bytes, &delay, level)) || 292 &bytes, &delay, level)) ||
291 !(p = 293 !(p =
292 read_output_line (0, 3, 4, 9, '1', "INFO", OUTPUT_DELAY, 294 read_output_line(0, 3, 4, 9, '1', "INFO", OUTPUT_DELAY,
293 MAX_SKIP_DELAY, phase, p, 295 MAX_SKIP_DELAY, phase, p,
294 &bytes, &delays[2], level)) || 296 &bytes, &delays[2], level)) ||
295 !(p = 297 !(p =
296 read_output_line (3, 3, 7, 7, 'L', "DEBUG", -1, 298 read_output_line(3, 3, 7, 7, 'L', "DEBUG", -1,
297 1, phase, p, 299 1, phase, p,
298 &bytes, &delay, level)) || 300 &bytes, &delay, level)) ||
299 !(p = 301 !(p =
300 read_output_line (0, 3, 4, 9, '1', "DEBUG", OUTPUT_DELAY, 302 read_output_line(0, 3, 4, 9, '1', "DEBUG", OUTPUT_DELAY,
301 MAX_SKIP_DELAY, phase, p, 303 MAX_SKIP_DELAY, phase, p,
302 &bytes, &delays[3], level)) || 304 &bytes, &delays[3], level)) ||
303 !(p = 305 !(p =
304 read_output_line (0, 3, 4, 9, 'L', "ERROR", -1, 306 read_output_line(0, 3, 4, 9, 'L', "ERROR", -1,
305 1, phase, p, 307 1, phase, p,
306 &bytes, &delay, level)) || 308 &bytes, &delay, level)) ||
307 !(p = 309 !(p =
308 read_output_line (0, 3, 4, 9, '2', "ERROR", OUTPUT_DELAY, 310 read_output_line(0, 3, 4, 9, '2', "ERROR", OUTPUT_DELAY,
309 MAX_SKIP_DELAY, phase, p, 311 MAX_SKIP_DELAY, phase, p,
310 &bytes, &delays[4], level)) || 312 &bytes, &delays[4], level)) ||
311 !(p = 313 !(p =
312 read_output_line (0, 3, 5, 9, 'L', "WARNING", -1, 314 read_output_line(0, 3, 5, 9, 'L', "WARNING", -1,
313 1, phase, p, 315 1, phase, p,
314 &bytes, &delay, level)) || 316 &bytes, &delay, level)) ||
315 !(p = 317 !(p =
316 read_output_line (0, 3, 4, 9, '2', "WARNING", OUTPUT_DELAY, 318 read_output_line(0, 3, 4, 9, '2', "WARNING", OUTPUT_DELAY,
317 MAX_SKIP_DELAY, phase, p, 319 MAX_SKIP_DELAY, phase, p,
318 &bytes, &delays[5], level)) || 320 &bytes, &delays[5], level)) ||
319 !(p = 321 !(p =
320 read_output_line (-1, -1, 6, 7, 'L', "INFO", -1, 322 read_output_line(-1, -1, 6, 7, 'L', "INFO", -1,
321 1, phase, p, 323 1, phase, p,
322 &bytes, &delay, level)) || 324 &bytes, &delay, level)) ||
323 !(p = 325 !(p =
324 read_output_line (0, 3, 4, 9, '2', "INFO", OUTPUT_DELAY, 326 read_output_line(0, 3, 4, 9, '2', "INFO", OUTPUT_DELAY,
325 MAX_SKIP_DELAY, phase, p, 327 MAX_SKIP_DELAY, phase, p,
326 &bytes, &delays[6], level)) || 328 &bytes, &delays[6], level)) ||
327 !(p = 329 !(p =
328 read_output_line (-1, -1, 7, 7, 'L', "DEBUG", -1, 330 read_output_line(-1, -1, 7, 7, 'L', "DEBUG", -1,
329 1, phase, p, 331 1, phase, p,
330 &bytes, &delay, level)) || 332 &bytes, &delay, level)) ||
331 !(p = 333 !(p =
332 read_output_line (0, 3, 4, 9, '2', "DEBUG", OUTPUT_DELAY, 334 read_output_line(0, 3, 4, 9, '2', "DEBUG", OUTPUT_DELAY,
333 MAX_SKIP_DELAY, phase, p, 335 MAX_SKIP_DELAY, phase, p,
334 &bytes, &delays[7], level))) 336 &bytes, &delays[7], level)))
335 { 337 {
336 if (bytes == LOG_BUFFER_SIZE) 338 if (bytes == LOG_BUFFER_SIZE)
337 fprintf (stderr, "%s", "Ran out of buffer space!\n"); 339 fprintf(stderr, "%s", "Ran out of buffer space!\n");
338 GNUNET_break (0); 340 GNUNET_break(0);
339 ok = 2; 341 ok = 2;
340 GNUNET_SCHEDULER_cancel (die_task); 342 GNUNET_SCHEDULER_cancel(die_task);
341 GNUNET_SCHEDULER_add_now (&end_task, NULL); 343 GNUNET_SCHEDULER_add_now(&end_task, NULL);
342 return; 344 return;
343 } 345 }
344 346
345 GNUNET_SCHEDULER_cancel (die_task); 347 GNUNET_SCHEDULER_cancel(die_task);
346 GNUNET_SCHEDULER_add_now (&end_task, NULL); 348 GNUNET_SCHEDULER_add_now(&end_task, NULL);
347} 349}
348 350
349 351
350static void 352static void
351runone () 353runone()
352{ 354{
353 const struct GNUNET_DISK_FileHandle *stdout_read_handle; 355 const struct GNUNET_DISK_FileHandle *stdout_read_handle;
354 356
355 pipe_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 357 pipe_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
356 358
357 if (pipe_stdout == NULL) 359 if (pipe_stdout == NULL)
358 { 360 {
359 GNUNET_break (0); 361 GNUNET_break(0);
360 ok = 2; 362 ok = 2;
361 return; 363 return;
362 } 364 }
363 365
364 putenv ("GNUNET_LOG="); 366 putenv("GNUNET_LOG=");
365 putenv ("GNUNET_FORCE_LOG="); 367 putenv("GNUNET_FORCE_LOG=");
366 putenv ("GNUNET_FORCE_LOGFILE="); 368 putenv("GNUNET_FORCE_LOGFILE=");
367 switch (phase) 369 switch (phase)
368 { 370 {
369 case 0: 371 case 0:
370 putenv ("GNUNET_LOG=;;;;ERROR"); 372 putenv("GNUNET_LOG=;;;;ERROR");
371 break; 373 break;
372 case 1: 374
373 putenv ("GNUNET_LOG=;;;;WARNING"); 375 case 1:
374 break; 376 putenv("GNUNET_LOG=;;;;WARNING");
375 case 2: 377 break;
376 putenv ("GNUNET_LOG=;;;;INFO"); 378
377 break; 379 case 2:
378 case 3: 380 putenv("GNUNET_LOG=;;;;INFO");
379 putenv ("GNUNET_LOG=;;;;DEBUG"); 381 break;
380 break; 382
381 case 4: 383 case 3:
382 putenv ("GNUNET_FORCE_LOG=;;;;ERROR"); 384 putenv("GNUNET_LOG=;;;;DEBUG");
383 break; 385 break;
384 case 5: 386
385 putenv ("GNUNET_FORCE_LOG=;;;;WARNING"); 387 case 4:
386 break; 388 putenv("GNUNET_FORCE_LOG=;;;;ERROR");
387 case 6: 389 break;
388 putenv ("GNUNET_FORCE_LOG=;;;;INFO"); 390
389 break; 391 case 5:
390 case 7: 392 putenv("GNUNET_FORCE_LOG=;;;;WARNING");
391 putenv ("GNUNET_FORCE_LOG=;;;;DEBUG"); 393 break;
392 break; 394
393 case 8: 395 case 6:
394 putenv ("GNUNET_LOG=blah;;;;ERROR"); 396 putenv("GNUNET_FORCE_LOG=;;;;INFO");
395 break; 397 break;
396 case 9: 398
397 putenv ("GNUNET_FORCE_LOG=blah;;;;ERROR"); 399 case 7:
398 break; 400 putenv("GNUNET_FORCE_LOG=;;;;DEBUG");
399 } 401 break;
400 402
401 proc = GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR, 403 case 8:
402 NULL, pipe_stdout, NULL, 404 putenv("GNUNET_LOG=blah;;;;ERROR");
405 break;
406
407 case 9:
408 putenv("GNUNET_FORCE_LOG=blah;;;;ERROR");
409 break;
410 }
411
412 proc = GNUNET_OS_start_process(GNUNET_NO, GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
413 NULL, pipe_stdout, NULL,
403#if MINGW 414#if MINGW
404 "test_common_logging_dummy", 415 "test_common_logging_dummy",
405#else 416#else
406 "./test_common_logging_dummy", 417 "./test_common_logging_dummy",
407#endif 418#endif
408 "test_common_logging_dummy", NULL); 419 "test_common_logging_dummy", NULL);
409 GNUNET_assert (NULL != proc); 420 GNUNET_assert(NULL != proc);
410 putenv ("GNUNET_FORCE_LOG="); 421 putenv("GNUNET_FORCE_LOG=");
411 putenv ("GNUNET_LOG="); 422 putenv("GNUNET_LOG=");
412 423
413 /* Close the write end of the read pipe */ 424 /* Close the write end of the read pipe */
414 GNUNET_DISK_pipe_close_end (pipe_stdout, GNUNET_DISK_PIPE_END_WRITE); 425 GNUNET_DISK_pipe_close_end(pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
415 426
416 stdout_read_handle = 427 stdout_read_handle =
417 GNUNET_DISK_pipe_handle (pipe_stdout, GNUNET_DISK_PIPE_END_READ); 428 GNUNET_DISK_pipe_handle(pipe_stdout, GNUNET_DISK_PIPE_END_READ);
418 429
419 die_task = 430 die_task =
420 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply 431 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply
421 (GNUNET_TIME_UNIT_SECONDS, 10), 432 (GNUNET_TIME_UNIT_SECONDS, 10),
422 &end_task, 433 &end_task,
423 NULL); 434 NULL);
424 435
425 bytes = 0; 436 bytes = 0;
426 buf_ptr = buf; 437 buf_ptr = buf;
427 memset (&buf, 0, sizeof (buf)); 438 memset(&buf, 0, sizeof(buf));
428 439
429 read_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 440 read_task = GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
430 stdout_read_handle, 441 stdout_read_handle,
431 &read_call, 442 &read_call,
432 (void*) stdout_read_handle); 443 (void*)stdout_read_handle);
433} 444}
434 445
435 446
436static void 447static void
437task (void *cls) 448task(void *cls)
438{ 449{
439 phase = 0; 450 phase = 0;
440 runone (); 451 runone();
441} 452}
442 453
443 454
444int 455int
445main (int argc, char *argv[]) 456main(int argc, char *argv[])
446{ 457{
447 GNUNET_log_setup ("test-common-logging-runtime-loglevels", 458 GNUNET_log_setup("test-common-logging-runtime-loglevels",
448 "WARNING", 459 "WARNING",
449 NULL); 460 NULL);
450 ok = 1; 461 ok = 1;
451 GNUNET_SCHEDULER_run (&task, &ok); 462 GNUNET_SCHEDULER_run(&task, &ok);
452 return ok; 463 return ok;
453} 464}
454 465
diff --git a/src/util/test_configuration.c b/src/util/test_configuration.c
index 67e532f40..71a1ae5bd 100644
--- a/src/util/test_configuration.c
+++ b/src/util/test_configuration.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_configuration.c 21 * @file util/test_configuration.c
22 * @brief Test that the configuration module works. 22 * @brief Test that the configuration module works.
@@ -28,8 +28,7 @@
28 28
29 29
30/* Test Configuration Diffs Options */ 30/* Test Configuration Diffs Options */
31enum 31enum {
32{
33 EDIT_NOTHING, 32 EDIT_NOTHING,
34 EDIT_SECTION, 33 EDIT_SECTION,
35 EDIT_ALL, 34 EDIT_ALL,
@@ -44,8 +43,7 @@ enum
44static struct GNUNET_CONFIGURATION_Handle *cfg; 43static struct GNUNET_CONFIGURATION_Handle *cfg;
45static struct GNUNET_CONFIGURATION_Handle *cfg_default; 44static struct GNUNET_CONFIGURATION_Handle *cfg_default;
46 45
47struct DiffsCBData 46struct DiffsCBData {
48{
49 struct GNUNET_CONFIGURATION_Handle *cfg; 47 struct GNUNET_CONFIGURATION_Handle *cfg;
50 struct GNUNET_CONFIGURATION_Handle *cfgDiffs; 48 struct GNUNET_CONFIGURATION_Handle *cfgDiffs;
51 const char *section; 49 const char *section;
@@ -55,7 +53,7 @@ struct DiffsCBData
55 53
56 54
57static void 55static void
58initDiffsCBData (struct DiffsCBData *cbData) 56initDiffsCBData(struct DiffsCBData *cbData)
59{ 57{
60 cbData->section = NULL; 58 cbData->section = NULL;
61 cbData->cfg = NULL; 59 cbData->cfg = NULL;
@@ -68,129 +66,138 @@ initDiffsCBData (struct DiffsCBData *cbData)
68/** 66/**
69 * callback function for modifying 67 * callback function for modifying
70 * and comparing configuration 68 * and comparing configuration
71*/ 69 */
72static void 70static void
73diffsCallBack (void *cls, const char *section, const char *option, 71diffsCallBack(void *cls, const char *section, const char *option,
74 const char *value) 72 const char *value)
75{ 73{
76 struct DiffsCBData *cbData = cls; 74 struct DiffsCBData *cbData = cls;
77 int cbOption = cbData->callBackOption; 75 int cbOption = cbData->callBackOption;
78 76
79 switch (cbOption) 77 switch (cbOption)
80 {
81 case EDIT_SECTION:
82 if (NULL == cbData->section)
83 cbData->section = section;
84 if (strcmp (cbData->section, section) == 0)
85 {
86 GNUNET_CONFIGURATION_set_value_string (cbData->cfg, section, option,
87 "new-value");
88 GNUNET_CONFIGURATION_set_value_string (cbData->cfgDiffs, section, option,
89 "new-value");
90 }
91 break;
92 case EDIT_ALL:
93 GNUNET_CONFIGURATION_set_value_string (cbData->cfg, section, option,
94 "new-value");
95 GNUNET_CONFIGURATION_set_value_string (cbData->cfgDiffs, section, option,
96 "new-value");
97 break;
98 case ADD_NEW_ENTRY:
99 {
100 static int hit = 0;
101
102 if (hit == 0)
103 {
104 hit = 1;
105 GNUNET_CONFIGURATION_set_value_string (cbData->cfg, section, "new-key",
106 "new-value");
107 GNUNET_CONFIGURATION_set_value_string (cbData->cfgDiffs, section,
108 "new-key", "new-value");
109 }
110 break;
111 }
112 case COMPARE:
113 {
114 int ret;
115 char *diffValue;
116
117 diffValue = NULL;
118 ret =
119 GNUNET_CONFIGURATION_get_value_string (cbData->cfgDiffs, section,
120 option, &diffValue);
121 if (NULL != diffValue)
122 {
123 if (ret == GNUNET_SYSERR || strcmp (diffValue, value) != 0)
124 cbData->status = 1;
125 }
126 else
127 cbData->status = 1;
128 GNUNET_free_non_null (diffValue);
129 break;
130 }
131#if 0
132 case PRINT:
133 if (NULL == cbData->section)
134 { 78 {
135 cbData->section = section; 79 case EDIT_SECTION:
136 printf ("\nSection: %s\n", section); 80 if (NULL == cbData->section)
81 cbData->section = section;
82 if (strcmp(cbData->section, section) == 0)
83 {
84 GNUNET_CONFIGURATION_set_value_string(cbData->cfg, section, option,
85 "new-value");
86 GNUNET_CONFIGURATION_set_value_string(cbData->cfgDiffs, section, option,
87 "new-value");
88 }
89 break;
90
91 case EDIT_ALL:
92 GNUNET_CONFIGURATION_set_value_string(cbData->cfg, section, option,
93 "new-value");
94 GNUNET_CONFIGURATION_set_value_string(cbData->cfgDiffs, section, option,
95 "new-value");
96 break;
97
98 case ADD_NEW_ENTRY:
99 {
100 static int hit = 0;
101
102 if (hit == 0)
103 {
104 hit = 1;
105 GNUNET_CONFIGURATION_set_value_string(cbData->cfg, section, "new-key",
106 "new-value");
107 GNUNET_CONFIGURATION_set_value_string(cbData->cfgDiffs, section,
108 "new-key", "new-value");
109 }
110 break;
137 } 111 }
138 else if (strcmp (cbData->section, section) != 0) 112
113 case COMPARE:
139 { 114 {
140 cbData->section = section; 115 int ret;
141 printf ("\nSection: %s\n", section); 116 char *diffValue;
117
118 diffValue = NULL;
119 ret =
120 GNUNET_CONFIGURATION_get_value_string(cbData->cfgDiffs, section,
121 option, &diffValue);
122 if (NULL != diffValue)
123 {
124 if (ret == GNUNET_SYSERR || strcmp(diffValue, value) != 0)
125 cbData->status = 1;
126 }
127 else
128 cbData->status = 1;
129 GNUNET_free_non_null(diffValue);
130 break;
142 } 131 }
143 printf ("%s = %s\n", option, value); 132
133#if 0
134 case PRINT:
135 if (NULL == cbData->section)
136 {
137 cbData->section = section;
138 printf("\nSection: %s\n", section);
139 }
140 else if (strcmp(cbData->section, section) != 0)
141 {
142 cbData->section = section;
143 printf("\nSection: %s\n", section);
144 }
145 printf("%s = %s\n", option, value);
144#endif 146#endif
145 default: 147 default:
146 break; 148 break;
147 } 149 }
148} 150}
149 151
150 152
151static struct GNUNET_CONFIGURATION_Handle * 153static struct GNUNET_CONFIGURATION_Handle *
152editConfiguration (struct GNUNET_CONFIGURATION_Handle *cfg, int option) 154editConfiguration(struct GNUNET_CONFIGURATION_Handle *cfg, int option)
153{ 155{
154 struct DiffsCBData diffsCB; 156 struct DiffsCBData diffsCB;
155 157
156 initDiffsCBData (&diffsCB); 158 initDiffsCBData(&diffsCB);
157 diffsCB.cfgDiffs = GNUNET_CONFIGURATION_create (); 159 diffsCB.cfgDiffs = GNUNET_CONFIGURATION_create();
158 160
159 switch (option) 161 switch (option)
160 { 162 {
161 case EDIT_SECTION: 163 case EDIT_SECTION:
162 case EDIT_ALL: 164 case EDIT_ALL:
163 case ADD_NEW_ENTRY: 165 case ADD_NEW_ENTRY:
164 diffsCB.callBackOption = option; 166 diffsCB.callBackOption = option;
165 diffsCB.cfg = cfg; 167 diffsCB.cfg = cfg;
166 GNUNET_CONFIGURATION_iterate (cfg, diffsCallBack, &diffsCB); 168 GNUNET_CONFIGURATION_iterate(cfg, diffsCallBack, &diffsCB);
167 break; 169 break;
168 case EDIT_NOTHING: 170
169 /* Do nothing */ 171 case EDIT_NOTHING:
170 break; 172 /* Do nothing */
171 case ADD_NEW_SECTION: 173 break;
172 { 174
173 int i; 175 case ADD_NEW_SECTION:
174 char *key; 176 {
175 177 int i;
176 for (i = 0; i < 5; i++) 178 char *key;
177 { 179
178 GNUNET_asprintf (&key, "key%d", i); 180 for (i = 0; i < 5; i++)
179 GNUNET_CONFIGURATION_set_value_string (cfg, "new-section", key, 181 {
180 "new-value"); 182 GNUNET_asprintf(&key, "key%d", i);
181 GNUNET_CONFIGURATION_set_value_string (diffsCB.cfgDiffs, "new-section", 183 GNUNET_CONFIGURATION_set_value_string(cfg, "new-section", key,
182 key, "new-value"); 184 "new-value");
183 GNUNET_free (key); 185 GNUNET_CONFIGURATION_set_value_string(diffsCB.cfgDiffs, "new-section",
184 } 186 key, "new-value");
185 break; 187 GNUNET_free(key);
186 } 188 }
187 case REMOVE_SECTION: 189 break;
188 break; 190 }
189 case REMOVE_ENTRY: 191
190 break; 192 case REMOVE_SECTION:
191 default: 193 break;
192 break; 194
193 } 195 case REMOVE_ENTRY:
196 break;
197
198 default:
199 break;
200 }
194 201
195 return diffsCB.cfgDiffs; 202 return diffsCB.cfgDiffs;
196} 203}
@@ -199,7 +206,7 @@ editConfiguration (struct GNUNET_CONFIGURATION_Handle *cfg, int option)
199 * Checking configuration diffs 206 * Checking configuration diffs
200 */ 207 */
201static int 208static int
202checkDiffs (struct GNUNET_CONFIGURATION_Handle *cfg_default, int option) 209checkDiffs(struct GNUNET_CONFIGURATION_Handle *cfg_default, int option)
203{ 210{
204 struct GNUNET_CONFIGURATION_Handle *cfg; 211 struct GNUNET_CONFIGURATION_Handle *cfg;
205 struct GNUNET_CONFIGURATION_Handle *cfgDiffs; 212 struct GNUNET_CONFIGURATION_Handle *cfgDiffs;
@@ -207,139 +214,139 @@ checkDiffs (struct GNUNET_CONFIGURATION_Handle *cfg_default, int option)
207 int ret; 214 int ret;
208 char *diffsFileName; 215 char *diffsFileName;
209 216
210 initDiffsCBData (&cbData); 217 initDiffsCBData(&cbData);
211 218
212 cfg = GNUNET_CONFIGURATION_create (); 219 cfg = GNUNET_CONFIGURATION_create();
213 /* load defaults */ 220 /* load defaults */
214 GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_load (cfg, NULL)); 221 GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_load(cfg, NULL));
215 222
216 /* Modify configuration and save it */ 223 /* Modify configuration and save it */
217 cfgDiffs = editConfiguration (cfg, option); 224 cfgDiffs = editConfiguration(cfg, option);
218 diffsFileName = GNUNET_DISK_mktemp ("gnunet-test-configurations-diffs.conf"); 225 diffsFileName = GNUNET_DISK_mktemp("gnunet-test-configurations-diffs.conf");
219 if (diffsFileName == NULL) 226 if (diffsFileName == NULL)
220 { 227 {
221 GNUNET_break (0); 228 GNUNET_break(0);
222 GNUNET_CONFIGURATION_destroy (cfg); 229 GNUNET_CONFIGURATION_destroy(cfg);
223 GNUNET_CONFIGURATION_destroy (cfgDiffs); 230 GNUNET_CONFIGURATION_destroy(cfgDiffs);
224 return 1; 231 return 1;
225 } 232 }
226 GNUNET_CONFIGURATION_write_diffs (cfg_default, cfg, diffsFileName); 233 GNUNET_CONFIGURATION_write_diffs(cfg_default, cfg, diffsFileName);
227 GNUNET_CONFIGURATION_destroy (cfg); 234 GNUNET_CONFIGURATION_destroy(cfg);
228 235
229 /* Compare the dumped configuration with modifications done */ 236 /* Compare the dumped configuration with modifications done */
230 cfg = GNUNET_CONFIGURATION_create (); 237 cfg = GNUNET_CONFIGURATION_create();
231 GNUNET_assert (GNUNET_OK == GNUNET_CONFIGURATION_parse (cfg, diffsFileName)); 238 GNUNET_assert(GNUNET_OK == GNUNET_CONFIGURATION_parse(cfg, diffsFileName));
232 if (0 != remove (diffsFileName)) 239 if (0 != remove(diffsFileName))
233 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING, "remove", diffsFileName); 240 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_WARNING, "remove", diffsFileName);
234 cbData.callBackOption = COMPARE; 241 cbData.callBackOption = COMPARE;
235 cbData.cfgDiffs = cfgDiffs; 242 cbData.cfgDiffs = cfgDiffs;
236 GNUNET_CONFIGURATION_iterate (cfg, diffsCallBack, &cbData); 243 GNUNET_CONFIGURATION_iterate(cfg, diffsCallBack, &cbData);
237 if (1 == (ret = cbData.status)) 244 if (1 == (ret = cbData.status))
238 { 245 {
239 fprintf (stderr, "%s", 246 fprintf(stderr, "%s",
240 "Incorrect Configuration Diffs: Diffs may contain data not actually edited\n"); 247 "Incorrect Configuration Diffs: Diffs may contain data not actually edited\n");
241 goto housekeeping; 248 goto housekeeping;
242 } 249 }
243 cbData.cfgDiffs = cfg; 250 cbData.cfgDiffs = cfg;
244 GNUNET_CONFIGURATION_iterate (cfgDiffs, diffsCallBack, &cbData); 251 GNUNET_CONFIGURATION_iterate(cfgDiffs, diffsCallBack, &cbData);
245 if ((ret = cbData.status) == 1) 252 if ((ret = cbData.status) == 1)
246 fprintf (stderr, "%s", 253 fprintf(stderr, "%s",
247 "Incorrect Configuration Diffs: Data may be missing in diffs\n"); 254 "Incorrect Configuration Diffs: Data may be missing in diffs\n");
248 255
249housekeeping: 256housekeeping:
250#if 0 257#if 0
251 cbData.section = NULL; 258 cbData.section = NULL;
252 cbData.callBackOption = PRINT; 259 cbData.callBackOption = PRINT;
253 printf ("\nExpected Diffs:\n"); 260 printf("\nExpected Diffs:\n");
254 GNUNET_CONFIGURATION_iterate (cfgDiffs, diffsCallBack, &cbData); 261 GNUNET_CONFIGURATION_iterate(cfgDiffs, diffsCallBack, &cbData);
255 cbData.section = NULL; 262 cbData.section = NULL;
256 printf ("\nActual Diffs:\n"); 263 printf("\nActual Diffs:\n");
257 GNUNET_CONFIGURATION_iterate (cfg, diffsCallBack, &cbData); 264 GNUNET_CONFIGURATION_iterate(cfg, diffsCallBack, &cbData);
258#endif 265#endif
259 GNUNET_CONFIGURATION_destroy (cfg); 266 GNUNET_CONFIGURATION_destroy(cfg);
260 GNUNET_CONFIGURATION_destroy (cfgDiffs); 267 GNUNET_CONFIGURATION_destroy(cfgDiffs);
261 GNUNET_free (diffsFileName); 268 GNUNET_free(diffsFileName);
262 return ret; 269 return ret;
263} 270}
264 271
265 272
266static int 273static int
267testConfig () 274testConfig()
268{ 275{
269 char *c; 276 char *c;
270 unsigned long long l; 277 unsigned long long l;
271 278
272 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "test", "b", &c)) 279 if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string(cfg, "test", "b", &c))
273 return 1; 280 return 1;
274 if (0 != strcmp ("b", c)) 281 if (0 != strcmp("b", c))
275 { 282 {
276 fprintf (stderr, "Got `%s'\n", c); 283 fprintf(stderr, "Got `%s'\n", c);
277 GNUNET_free (c); 284 GNUNET_free(c);
278 return 2; 285 return 2;
279 } 286 }
280 GNUNET_free (c); 287 GNUNET_free(c);
281 if (GNUNET_OK != 288 if (GNUNET_OK !=
282 GNUNET_CONFIGURATION_get_value_number (cfg, "test", "five", &l)) 289 GNUNET_CONFIGURATION_get_value_number(cfg, "test", "five", &l))
283 { 290 {
284 GNUNET_break (0); 291 GNUNET_break(0);
285 return 3; 292 return 3;
286 } 293 }
287 if (5 != l) 294 if (5 != l)
288 { 295 {
289 GNUNET_break (0); 296 GNUNET_break(0);
290 return 4; 297 return 4;
291 } 298 }
292 GNUNET_CONFIGURATION_set_value_string (cfg, "more", "c", "YES"); 299 GNUNET_CONFIGURATION_set_value_string(cfg, "more", "c", "YES");
293 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_yesno (cfg, "more", "c")) 300 if (GNUNET_NO == GNUNET_CONFIGURATION_get_value_yesno(cfg, "more", "c"))
294 { 301 {
295 GNUNET_break (0); 302 GNUNET_break(0);
296 return 5; 303 return 5;
297 } 304 }
298 GNUNET_CONFIGURATION_set_value_number (cfg, "NUMBERS", "TEN", 10); 305 GNUNET_CONFIGURATION_set_value_number(cfg, "NUMBERS", "TEN", 10);
299 if (GNUNET_OK != 306 if (GNUNET_OK !=
300 GNUNET_CONFIGURATION_get_value_string (cfg, "NUMBERS", "TEN", &c)) 307 GNUNET_CONFIGURATION_get_value_string(cfg, "NUMBERS", "TEN", &c))
301 { 308 {
302 GNUNET_break (0); 309 GNUNET_break(0);
303 return 6; 310 return 6;
304 } 311 }
305 if (0 != strcmp (c, "10")) 312 if (0 != strcmp(c, "10"))
306 { 313 {
307 GNUNET_free (c); 314 GNUNET_free(c);
308 GNUNET_break (0); 315 GNUNET_break(0);
309 return 7; 316 return 7;
310 } 317 }
311 GNUNET_free (c); 318 GNUNET_free(c);
312 319
313 if (GNUNET_OK != 320 if (GNUNET_OK !=
314 GNUNET_CONFIGURATION_get_value_filename (cfg, "last", "test", &c)) 321 GNUNET_CONFIGURATION_get_value_filename(cfg, "last", "test", &c))
315 { 322 {
316 GNUNET_break (0); 323 GNUNET_break(0);
317 return 8; 324 return 8;
318 } 325 }
319#ifndef MINGW 326#ifndef MINGW
320 if (0 != strcmp (c, "/hello/world")) 327 if (0 != strcmp(c, "/hello/world"))
321#else 328#else
322#define HI "\\hello\\world" 329#define HI "\\hello\\world"
323 if (strstr (c, HI) != c + strlen (c) - strlen (HI)) 330 if (strstr(c, HI) != c + strlen(c) - strlen(HI))
324#endif 331#endif
325 { 332 {
326 GNUNET_break (0); 333 GNUNET_break(0);
327 GNUNET_free (c); 334 GNUNET_free(c);
328 return 9; 335 return 9;
329 } 336 }
330 GNUNET_free (c); 337 GNUNET_free(c);
331 338
332 if (GNUNET_OK != 339 if (GNUNET_OK !=
333 GNUNET_CONFIGURATION_get_value_size (cfg, "last", "size", &l)) 340 GNUNET_CONFIGURATION_get_value_size(cfg, "last", "size", &l))
334 { 341 {
335 GNUNET_break (0); 342 GNUNET_break(0);
336 return 10; 343 return 10;
337 } 344 }
338 if (l != 512 * 1024) 345 if (l != 512 * 1024)
339 { 346 {
340 GNUNET_break (0); 347 GNUNET_break(0);
341 return 11; 348 return 11;
342 } 349 }
343 return 0; 350 return 0;
344} 351}
345 352
@@ -352,198 +359,198 @@ static const char *want[] = {
352}; 359};
353 360
354static int 361static int
355check (void *data, const char *fn) 362check(void *data, const char *fn)
356{ 363{
357 int *idx = data; 364 int *idx = data;
358 365
359 if (0 == strcmp (want[*idx], fn)) 366 if (0 == strcmp(want[*idx], fn))
360 { 367 {
361 (*idx)++; 368 (*idx)++;
362 return GNUNET_OK; 369 return GNUNET_OK;
363 } 370 }
364 GNUNET_break (0); 371 GNUNET_break(0);
365 return GNUNET_SYSERR; 372 return GNUNET_SYSERR;
366} 373}
367 374
368static int 375static int
369testConfigFilenames () 376testConfigFilenames()
370{ 377{
371 int idx; 378 int idx;
372 379
373 idx = 0; 380 idx = 0;
374 if (3 != 381 if (3 !=
375 GNUNET_CONFIGURATION_iterate_value_filenames (cfg, "FILENAMES", "test", 382 GNUNET_CONFIGURATION_iterate_value_filenames(cfg, "FILENAMES", "test",
376 &check, &idx)) 383 &check, &idx))
377 { 384 {
378 GNUNET_break (0); 385 GNUNET_break(0);
379 return 8; 386 return 8;
380 } 387 }
381 if (idx != 3) 388 if (idx != 3)
382 return 16; 389 return 16;
383 if (GNUNET_OK != 390 if (GNUNET_OK !=
384 GNUNET_CONFIGURATION_remove_value_filename (cfg, "FILENAMES", "test", 391 GNUNET_CONFIGURATION_remove_value_filename(cfg, "FILENAMES", "test",
385 "/File Name")) 392 "/File Name"))
386 { 393 {
387 GNUNET_break (0); 394 GNUNET_break(0);
388 return 24; 395 return 24;
389 } 396 }
390 397
391 if (GNUNET_NO != 398 if (GNUNET_NO !=
392 GNUNET_CONFIGURATION_remove_value_filename (cfg, "FILENAMES", "test", 399 GNUNET_CONFIGURATION_remove_value_filename(cfg, "FILENAMES", "test",
393 "/File Name")) 400 "/File Name"))
394 { 401 {
395 GNUNET_break (0); 402 GNUNET_break(0);
396 return 32; 403 return 32;
397 } 404 }
398 if (GNUNET_NO != 405 if (GNUNET_NO !=
399 GNUNET_CONFIGURATION_remove_value_filename (cfg, "FILENAMES", "test", 406 GNUNET_CONFIGURATION_remove_value_filename(cfg, "FILENAMES", "test",
400 "Stuff")) 407 "Stuff"))
401 { 408 {
402 GNUNET_break (0); 409 GNUNET_break(0);
403 return 40; 410 return 40;
404 } 411 }
405 412
406 if (GNUNET_NO != 413 if (GNUNET_NO !=
407 GNUNET_CONFIGURATION_append_value_filename (cfg, "FILENAMES", "test", 414 GNUNET_CONFIGURATION_append_value_filename(cfg, "FILENAMES", "test",
408 "/Hello")) 415 "/Hello"))
409 { 416 {
410 GNUNET_break (0); 417 GNUNET_break(0);
411 return 48; 418 return 48;
412 } 419 }
413 if (GNUNET_NO != 420 if (GNUNET_NO !=
414 GNUNET_CONFIGURATION_append_value_filename (cfg, "FILENAMES", "test", 421 GNUNET_CONFIGURATION_append_value_filename(cfg, "FILENAMES", "test",
415 "/World")) 422 "/World"))
416 { 423 {
417 GNUNET_break (0); 424 GNUNET_break(0);
418 return 56; 425 return 56;
419 } 426 }
420 427
421 if (GNUNET_YES != 428 if (GNUNET_YES !=
422 GNUNET_CONFIGURATION_append_value_filename (cfg, "FILENAMES", "test", 429 GNUNET_CONFIGURATION_append_value_filename(cfg, "FILENAMES", "test",
423 "/File 1")) 430 "/File 1"))
424 { 431 {
425 GNUNET_break (0); 432 GNUNET_break(0);
426 return 64; 433 return 64;
427 } 434 }
428 435
429 if (GNUNET_YES != 436 if (GNUNET_YES !=
430 GNUNET_CONFIGURATION_append_value_filename (cfg, "FILENAMES", "test", 437 GNUNET_CONFIGURATION_append_value_filename(cfg, "FILENAMES", "test",
431 "/File 2")) 438 "/File 2"))
432 { 439 {
433 GNUNET_break (0); 440 GNUNET_break(0);
434 return 72; 441 return 72;
435 } 442 }
436 443
437 idx = 0; 444 idx = 0;
438 want[1] = "/World"; 445 want[1] = "/World";
439 want[2] = "/File 1"; 446 want[2] = "/File 1";
440 want[3] = "/File 2"; 447 want[3] = "/File 2";
441 if (4 != 448 if (4 !=
442 GNUNET_CONFIGURATION_iterate_value_filenames (cfg, "FILENAMES", "test", 449 GNUNET_CONFIGURATION_iterate_value_filenames(cfg, "FILENAMES", "test",
443 &check, &idx)) 450 &check, &idx))
444 { 451 {
445 GNUNET_break (0); 452 GNUNET_break(0);
446 return 80; 453 return 80;
447 } 454 }
448 if (idx != 4) 455 if (idx != 4)
449 { 456 {
450 GNUNET_break (0); 457 GNUNET_break(0);
451 return 88; 458 return 88;
452 } 459 }
453 return 0; 460 return 0;
454} 461}
455 462
456 463
457int 464int
458main (int argc, char *argv[]) 465main(int argc, char *argv[])
459{ 466{
460 int failureCount = 0; 467 int failureCount = 0;
461 char *c; 468 char *c;
462 469
463 GNUNET_log_setup ("test_configuration", "WARNING", NULL); 470 GNUNET_log_setup("test_configuration", "WARNING", NULL);
464 cfg = GNUNET_CONFIGURATION_create (); 471 cfg = GNUNET_CONFIGURATION_create();
465 GNUNET_assert (cfg != NULL); 472 GNUNET_assert(cfg != NULL);
466 if (GNUNET_OK != 473 if (GNUNET_OK !=
467 GNUNET_CONFIGURATION_parse (cfg, "test_configuration_data.conf")) 474 GNUNET_CONFIGURATION_parse(cfg, "test_configuration_data.conf"))
468 { 475 {
469 fprintf (stderr, "%s", "Failed to parse configuration file\n"); 476 fprintf(stderr, "%s", "Failed to parse configuration file\n");
470 GNUNET_CONFIGURATION_destroy (cfg); 477 GNUNET_CONFIGURATION_destroy(cfg);
471 return 1; 478 return 1;
472 } 479 }
473 failureCount += testConfig (); 480 failureCount += testConfig();
474 if (failureCount > 0) 481 if (failureCount > 0)
475 goto error; 482 goto error;
476 483
477 failureCount = testConfigFilenames (); 484 failureCount = testConfigFilenames();
478 if (failureCount > 0) 485 if (failureCount > 0)
479 goto error; 486 goto error;
480 487
481 if (GNUNET_OK != GNUNET_CONFIGURATION_write (cfg, "/tmp/gnunet-test.conf")) 488 if (GNUNET_OK != GNUNET_CONFIGURATION_write(cfg, "/tmp/gnunet-test.conf"))
482 { 489 {
483 fprintf (stderr, "%s", "Failed to write configuration file\n"); 490 fprintf(stderr, "%s", "Failed to write configuration file\n");
484 GNUNET_CONFIGURATION_destroy (cfg); 491 GNUNET_CONFIGURATION_destroy(cfg);
485 return 1; 492 return 1;
486 } 493 }
487 GNUNET_CONFIGURATION_destroy (cfg); 494 GNUNET_CONFIGURATION_destroy(cfg);
488 GNUNET_assert (0 == unlink ("/tmp/gnunet-test.conf")); 495 GNUNET_assert(0 == unlink("/tmp/gnunet-test.conf"));
489 496
490 cfg = GNUNET_CONFIGURATION_create (); 497 cfg = GNUNET_CONFIGURATION_create();
491 if (GNUNET_OK != 498 if (GNUNET_OK !=
492 GNUNET_CONFIGURATION_load (cfg, "test_configuration_data.conf")) 499 GNUNET_CONFIGURATION_load(cfg, "test_configuration_data.conf"))
493 { 500 {
494 GNUNET_break (0); 501 GNUNET_break(0);
495 GNUNET_CONFIGURATION_destroy (cfg); 502 GNUNET_CONFIGURATION_destroy(cfg);
496 return 1; 503 return 1;
497 } 504 }
498 if (GNUNET_OK != 505 if (GNUNET_OK !=
499 GNUNET_CONFIGURATION_get_value_string (cfg, "TESTING", "WEAKRANDOM", &c)) 506 GNUNET_CONFIGURATION_get_value_string(cfg, "TESTING", "WEAKRANDOM", &c))
500 { 507 {
501 GNUNET_break (0); 508 GNUNET_break(0);
502 GNUNET_CONFIGURATION_destroy (cfg); 509 GNUNET_CONFIGURATION_destroy(cfg);
503 return 1; 510 return 1;
504 } 511 }
505 if (0 != strcmp (c, "YES")) 512 if (0 != strcmp(c, "YES"))
506 { 513 {
507 GNUNET_break (0); 514 GNUNET_break(0);
508 GNUNET_free (c); 515 GNUNET_free(c);
509 GNUNET_CONFIGURATION_destroy (cfg); 516 GNUNET_CONFIGURATION_destroy(cfg);
510 return 1; 517 return 1;
511 } 518 }
512 519
513 GNUNET_free (c); 520 GNUNET_free(c);
514 GNUNET_CONFIGURATION_destroy (cfg); 521 GNUNET_CONFIGURATION_destroy(cfg);
515 522
516 /* Testing configuration diffs */ 523 /* Testing configuration diffs */
517 cfg_default = GNUNET_CONFIGURATION_create (); 524 cfg_default = GNUNET_CONFIGURATION_create();
518 if (GNUNET_OK != GNUNET_CONFIGURATION_load (cfg_default, NULL)) 525 if (GNUNET_OK != GNUNET_CONFIGURATION_load(cfg_default, NULL))
519 { 526 {
520 GNUNET_break (0); 527 GNUNET_break(0);
521 GNUNET_CONFIGURATION_destroy (cfg_default); 528 GNUNET_CONFIGURATION_destroy(cfg_default);
522 return 1; 529 return 1;
523 } 530 }
524 531
525 /* Nothing changed in the new configuration */ 532 /* Nothing changed in the new configuration */
526 failureCount += checkDiffs (cfg_default, EDIT_NOTHING); 533 failureCount += checkDiffs(cfg_default, EDIT_NOTHING);
527 534
528 /* Modify all entries of the last section */ 535 /* Modify all entries of the last section */
529 failureCount += checkDiffs (cfg_default, EDIT_SECTION); 536 failureCount += checkDiffs(cfg_default, EDIT_SECTION);
530 537
531 /* Add a new section */ 538 /* Add a new section */
532 failureCount += checkDiffs (cfg_default, ADD_NEW_SECTION); 539 failureCount += checkDiffs(cfg_default, ADD_NEW_SECTION);
533 540
534 /* Add a new entry to the last section */ 541 /* Add a new entry to the last section */
535 failureCount += checkDiffs (cfg_default, ADD_NEW_ENTRY); 542 failureCount += checkDiffs(cfg_default, ADD_NEW_ENTRY);
536 543
537 /* Modify all entries in the configuration */ 544 /* Modify all entries in the configuration */
538 failureCount += checkDiffs (cfg_default, EDIT_ALL); 545 failureCount += checkDiffs(cfg_default, EDIT_ALL);
539 546
540 GNUNET_CONFIGURATION_destroy (cfg_default); 547 GNUNET_CONFIGURATION_destroy(cfg_default);
541 548
542error: 549error:
543 if (failureCount != 0) 550 if (failureCount != 0)
544 { 551 {
545 fprintf (stderr, "Test failed: %u\n", failureCount); 552 fprintf(stderr, "Test failed: %u\n", failureCount);
546 return 1; 553 return 1;
547 } 554 }
548 return 0; 555 return 0;
549} 556}
diff --git a/src/util/test_container_bloomfilter.c b/src/util/test_container_bloomfilter.c
index 043eacafd..d295f465b 100644
--- a/src/util/test_container_bloomfilter.c
+++ b/src/util/test_container_bloomfilter.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_container_bloomfilter.c 21 * @file util/test_container_bloomfilter.c
22 * @brief Testcase for the bloomfilter. 22 * @brief Testcase for the bloomfilter.
@@ -35,26 +35,26 @@
35 * Generate a random hashcode. 35 * Generate a random hashcode.
36 */ 36 */
37static void 37static void
38nextHC (struct GNUNET_HashCode *hc) 38nextHC(struct GNUNET_HashCode *hc)
39{ 39{
40 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, hc); 40 GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, hc);
41} 41}
42 42
43static int 43static int
44add_iterator (void *cls, struct GNUNET_HashCode *next) 44add_iterator(void *cls, struct GNUNET_HashCode *next)
45{ 45{
46 int *ret = cls; 46 int *ret = cls;
47 struct GNUNET_HashCode pos; 47 struct GNUNET_HashCode pos;
48 48
49 if (0 == (*ret)--) 49 if (0 == (*ret)--)
50 return GNUNET_NO; 50 return GNUNET_NO;
51 nextHC (&pos); 51 nextHC(&pos);
52 *next = pos; 52 *next = pos;
53 return GNUNET_YES; 53 return GNUNET_YES;
54} 54}
55 55
56int 56int
57main (int argc, char *argv[]) 57main(int argc, char *argv[])
58{ 58{
59 struct GNUNET_CONTAINER_BloomFilter *bf; 59 struct GNUNET_CONTAINER_BloomFilter *bf;
60 struct GNUNET_CONTAINER_BloomFilter *bfi; 60 struct GNUNET_CONTAINER_BloomFilter *bfi;
@@ -66,186 +66,186 @@ main (int argc, char *argv[])
66 char buf[SIZE]; 66 char buf[SIZE];
67 struct stat sbuf; 67 struct stat sbuf;
68 68
69 GNUNET_log_setup ("test-container-bloomfilter", "WARNING", NULL); 69 GNUNET_log_setup("test-container-bloomfilter", "WARNING", NULL);
70 GNUNET_CRYPTO_seed_weak_random (1); 70 GNUNET_CRYPTO_seed_weak_random(1);
71 if (0 == stat (TESTFILE, &sbuf)) 71 if (0 == stat(TESTFILE, &sbuf))
72 if (0 != unlink (TESTFILE)) 72 if (0 != unlink(TESTFILE))
73 GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_ERROR, "unlink", TESTFILE); 73 GNUNET_log_strerror_file(GNUNET_ERROR_TYPE_ERROR, "unlink", TESTFILE);
74 bf = GNUNET_CONTAINER_bloomfilter_load (TESTFILE, SIZE, K); 74 bf = GNUNET_CONTAINER_bloomfilter_load(TESTFILE, SIZE, K);
75 75
76 for (i = 0; i < 200; i++) 76 for (i = 0; i < 200; i++)
77 { 77 {
78 nextHC (&tmp); 78 nextHC(&tmp);
79 GNUNET_CONTAINER_bloomfilter_add (bf, &tmp); 79 GNUNET_CONTAINER_bloomfilter_add(bf, &tmp);
80 } 80 }
81 GNUNET_CRYPTO_seed_weak_random (1); 81 GNUNET_CRYPTO_seed_weak_random(1);
82 ok1 = 0; 82 ok1 = 0;
83 for (i = 0; i < 200; i++) 83 for (i = 0; i < 200; i++)
84 { 84 {
85 nextHC (&tmp); 85 nextHC(&tmp);
86 if (GNUNET_CONTAINER_bloomfilter_test (bf, &tmp) == GNUNET_YES) 86 if (GNUNET_CONTAINER_bloomfilter_test(bf, &tmp) == GNUNET_YES)
87 ok1++; 87 ok1++;
88 } 88 }
89 if (ok1 != 200) 89 if (ok1 != 200)
90 { 90 {
91 printf ("Got %d elements out of" 91 printf("Got %d elements out of"
92 "200 expected after insertion.\n", 92 "200 expected after insertion.\n",
93 ok1); 93 ok1);
94 GNUNET_CONTAINER_bloomfilter_free (bf); 94 GNUNET_CONTAINER_bloomfilter_free(bf);
95 return -1; 95 return -1;
96 } 96 }
97 if (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_get_raw_data (bf, buf, SIZE)) 97 if (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_get_raw_data(bf, buf, SIZE))
98 { 98 {
99 GNUNET_CONTAINER_bloomfilter_free (bf); 99 GNUNET_CONTAINER_bloomfilter_free(bf);
100 return -1; 100 return -1;
101 } 101 }
102 102
103 GNUNET_CONTAINER_bloomfilter_free (bf); 103 GNUNET_CONTAINER_bloomfilter_free(bf);
104 104
105 bf = GNUNET_CONTAINER_bloomfilter_load (TESTFILE, SIZE, K); 105 bf = GNUNET_CONTAINER_bloomfilter_load(TESTFILE, SIZE, K);
106 GNUNET_assert (bf != NULL); 106 GNUNET_assert(bf != NULL);
107 bfi = GNUNET_CONTAINER_bloomfilter_init (buf, SIZE, K); 107 bfi = GNUNET_CONTAINER_bloomfilter_init(buf, SIZE, K);
108 GNUNET_assert (bfi != NULL); 108 GNUNET_assert(bfi != NULL);
109 109
110 GNUNET_CRYPTO_seed_weak_random (1); 110 GNUNET_CRYPTO_seed_weak_random(1);
111 ok1 = 0; 111 ok1 = 0;
112 ok2 = 0; 112 ok2 = 0;
113 for (i = 0; i < 200; i++) 113 for (i = 0; i < 200; i++)
114 { 114 {
115 nextHC (&tmp); 115 nextHC(&tmp);
116 if (GNUNET_CONTAINER_bloomfilter_test (bf, &tmp) == GNUNET_YES) 116 if (GNUNET_CONTAINER_bloomfilter_test(bf, &tmp) == GNUNET_YES)
117 ok1++; 117 ok1++;
118 if (GNUNET_CONTAINER_bloomfilter_test (bfi, &tmp) == GNUNET_YES) 118 if (GNUNET_CONTAINER_bloomfilter_test(bfi, &tmp) == GNUNET_YES)
119 ok2++; 119 ok2++;
120 } 120 }
121 if (ok1 != 200) 121 if (ok1 != 200)
122 { 122 {
123 printf ("Got %d elements out of 200 " 123 printf("Got %d elements out of 200 "
124 "expected after reloading.\n", 124 "expected after reloading.\n",
125 ok1); 125 ok1);
126 GNUNET_CONTAINER_bloomfilter_free (bf); 126 GNUNET_CONTAINER_bloomfilter_free(bf);
127 GNUNET_CONTAINER_bloomfilter_free (bfi); 127 GNUNET_CONTAINER_bloomfilter_free(bfi);
128 return -1; 128 return -1;
129 } 129 }
130 130
131 if (ok2 != 200) 131 if (ok2 != 200)
132 { 132 {
133 printf ("Got %d elements out of 200 " 133 printf("Got %d elements out of 200 "
134 "expected after initialization.\n", 134 "expected after initialization.\n",
135 ok2); 135 ok2);
136 GNUNET_CONTAINER_bloomfilter_free (bf); 136 GNUNET_CONTAINER_bloomfilter_free(bf);
137 GNUNET_CONTAINER_bloomfilter_free (bfi); 137 GNUNET_CONTAINER_bloomfilter_free(bfi);
138 return -1; 138 return -1;
139 } 139 }
140 140
141 GNUNET_CRYPTO_seed_weak_random (1); 141 GNUNET_CRYPTO_seed_weak_random(1);
142 for (i = 0; i < 100; i++) 142 for (i = 0; i < 100; i++)
143 { 143 {
144 nextHC (&tmp); 144 nextHC(&tmp);
145 GNUNET_CONTAINER_bloomfilter_remove (bf, &tmp); 145 GNUNET_CONTAINER_bloomfilter_remove(bf, &tmp);
146 GNUNET_CONTAINER_bloomfilter_remove (bfi, &tmp); 146 GNUNET_CONTAINER_bloomfilter_remove(bfi, &tmp);
147 } 147 }
148 148
149 GNUNET_CRYPTO_seed_weak_random (1); 149 GNUNET_CRYPTO_seed_weak_random(1);
150 150
151 ok1 = 0; 151 ok1 = 0;
152 ok2 = 0; 152 ok2 = 0;
153 for (i = 0; i < 200; i++) 153 for (i = 0; i < 200; i++)
154 { 154 {
155 nextHC (&tmp); 155 nextHC(&tmp);
156 if (GNUNET_CONTAINER_bloomfilter_test (bf, &tmp) == GNUNET_YES) 156 if (GNUNET_CONTAINER_bloomfilter_test(bf, &tmp) == GNUNET_YES)
157 ok1++; 157 ok1++;
158 if (GNUNET_CONTAINER_bloomfilter_test (bfi, &tmp) == GNUNET_YES) 158 if (GNUNET_CONTAINER_bloomfilter_test(bfi, &tmp) == GNUNET_YES)
159 ok2++; 159 ok2++;
160 } 160 }
161 161
162 if (ok1 != 100) 162 if (ok1 != 100)
163 { 163 {
164 printf ("Expected 100 elements in loaded filter" 164 printf("Expected 100 elements in loaded filter"
165 " after adding 200 and deleting 100, got %d\n", 165 " after adding 200 and deleting 100, got %d\n",
166 ok1); 166 ok1);
167 GNUNET_CONTAINER_bloomfilter_free (bf); 167 GNUNET_CONTAINER_bloomfilter_free(bf);
168 GNUNET_CONTAINER_bloomfilter_free (bfi); 168 GNUNET_CONTAINER_bloomfilter_free(bfi);
169 return -1; 169 return -1;
170 } 170 }
171 if (ok2 != 200) 171 if (ok2 != 200)
172 { 172 {
173 printf ("Expected 200 elements in initialized filter" 173 printf("Expected 200 elements in initialized filter"
174 " after adding 200 and deleting 100 " 174 " after adding 200 and deleting 100 "
175 "(which should do nothing for a filter not backed by a file), got %d\n", 175 "(which should do nothing for a filter not backed by a file), got %d\n",
176 ok2); 176 ok2);
177 GNUNET_CONTAINER_bloomfilter_free (bf); 177 GNUNET_CONTAINER_bloomfilter_free(bf);
178 GNUNET_CONTAINER_bloomfilter_free (bfi); 178 GNUNET_CONTAINER_bloomfilter_free(bfi);
179 return -1; 179 return -1;
180 } 180 }
181 181
182 GNUNET_CRYPTO_seed_weak_random (3); 182 GNUNET_CRYPTO_seed_weak_random(3);
183 183
184 GNUNET_CONTAINER_bloomfilter_clear (bf); 184 GNUNET_CONTAINER_bloomfilter_clear(bf);
185 falseok = 0; 185 falseok = 0;
186 for (i = 0; i < 1000; i++) 186 for (i = 0; i < 1000; i++)
187 { 187 {
188 nextHC (&tmp); 188 nextHC(&tmp);
189 if (GNUNET_CONTAINER_bloomfilter_test (bf, &tmp) == GNUNET_YES) 189 if (GNUNET_CONTAINER_bloomfilter_test(bf, &tmp) == GNUNET_YES)
190 falseok++; 190 falseok++;
191 } 191 }
192 if (falseok > 0) 192 if (falseok > 0)
193 { 193 {
194 GNUNET_CONTAINER_bloomfilter_free (bf); 194 GNUNET_CONTAINER_bloomfilter_free(bf);
195 GNUNET_CONTAINER_bloomfilter_free (bfi); 195 GNUNET_CONTAINER_bloomfilter_free(bfi);
196 return -1; 196 return -1;
197 } 197 }
198 198
199 if (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_or (bf, buf, SIZE)) 199 if (GNUNET_OK != GNUNET_CONTAINER_bloomfilter_or(bf, buf, SIZE))
200 { 200 {
201 GNUNET_CONTAINER_bloomfilter_free (bf); 201 GNUNET_CONTAINER_bloomfilter_free(bf);
202 GNUNET_CONTAINER_bloomfilter_free (bfi); 202 GNUNET_CONTAINER_bloomfilter_free(bfi);
203 return -1; 203 return -1;
204 } 204 }
205 205
206 GNUNET_CRYPTO_seed_weak_random (2); 206 GNUNET_CRYPTO_seed_weak_random(2);
207 i = 20; 207 i = 20;
208 GNUNET_CONTAINER_bloomfilter_resize (bfi, &add_iterator, &i, SIZE * 2, K); 208 GNUNET_CONTAINER_bloomfilter_resize(bfi, &add_iterator, &i, SIZE * 2, K);
209 209
210 GNUNET_CRYPTO_seed_weak_random (2); 210 GNUNET_CRYPTO_seed_weak_random(2);
211 i = 20; 211 i = 20;
212 GNUNET_CONTAINER_bloomfilter_resize (bf, &add_iterator, &i, SIZE * 2, K); 212 GNUNET_CONTAINER_bloomfilter_resize(bf, &add_iterator, &i, SIZE * 2, K);
213 GNUNET_CRYPTO_seed_weak_random (2); 213 GNUNET_CRYPTO_seed_weak_random(2);
214 214
215 ok1 = 0; 215 ok1 = 0;
216 ok2 = 0; 216 ok2 = 0;
217 for (i = 0; i < 20; i++) 217 for (i = 0; i < 20; i++)
218 { 218 {
219 nextHC (&tmp); 219 nextHC(&tmp);
220 if (GNUNET_CONTAINER_bloomfilter_test (bf, &tmp) == GNUNET_YES) 220 if (GNUNET_CONTAINER_bloomfilter_test(bf, &tmp) == GNUNET_YES)
221 ok1++; 221 ok1++;
222 if (GNUNET_CONTAINER_bloomfilter_test (bfi, &tmp) == GNUNET_YES) 222 if (GNUNET_CONTAINER_bloomfilter_test(bfi, &tmp) == GNUNET_YES)
223 ok2++; 223 ok2++;
224 } 224 }
225 225
226 if (ok1 != 20) 226 if (ok1 != 20)
227 { 227 {
228 printf ("Expected 20 elements in resized file-backed filter" 228 printf("Expected 20 elements in resized file-backed filter"
229 " after adding 20, got %d\n", 229 " after adding 20, got %d\n",
230 ok1); 230 ok1);
231 GNUNET_CONTAINER_bloomfilter_free (bf); 231 GNUNET_CONTAINER_bloomfilter_free(bf);
232 GNUNET_CONTAINER_bloomfilter_free (bfi); 232 GNUNET_CONTAINER_bloomfilter_free(bfi);
233 return -1; 233 return -1;
234 } 234 }
235 if (ok2 != 20) 235 if (ok2 != 20)
236 { 236 {
237 printf ("Expected 20 elements in resized filter" 237 printf("Expected 20 elements in resized filter"
238 " after adding 20, got %d\n", 238 " after adding 20, got %d\n",
239 ok2); 239 ok2);
240 GNUNET_CONTAINER_bloomfilter_free (bf); 240 GNUNET_CONTAINER_bloomfilter_free(bf);
241 GNUNET_CONTAINER_bloomfilter_free (bfi); 241 GNUNET_CONTAINER_bloomfilter_free(bfi);
242 return -1; 242 return -1;
243 } 243 }
244 244
245 245
246 GNUNET_CONTAINER_bloomfilter_free (bf); 246 GNUNET_CONTAINER_bloomfilter_free(bf);
247 GNUNET_CONTAINER_bloomfilter_free (bfi); 247 GNUNET_CONTAINER_bloomfilter_free(bfi);
248 248
249 GNUNET_break (0 == unlink (TESTFILE)); 249 GNUNET_break(0 == unlink(TESTFILE));
250 return 0; 250 return 0;
251} 251}
diff --git a/src/util/test_container_dll.c b/src/util/test_container_dll.c
index f1c0e9446..7203cde22 100644
--- a/src/util/test_container_dll.c
+++ b/src/util/test_container_dll.c
@@ -1,19 +1,19 @@
1/* 1/*
2 This file is part of GNUnet. 2 This file is part of GNUnet.
3 Copyright (C) 2017 GNUnet e.V. 3 Copyright (C) 2017 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 */ 19 */
@@ -30,8 +30,7 @@
30/** 30/**
31 * Element in the DLL. 31 * Element in the DLL.
32 */ 32 */
33struct Element 33struct Element {
34{
35 /** 34 /**
36 * Required pointer to previous element. 35 * Required pointer to previous element.
37 */ 36 */
@@ -58,9 +57,9 @@ struct Element
58 * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO 57 * @return #GNUNET_YES if @e1 < @e2, otherwise #GNUNET_NO
59 */ 58 */
60static int 59static int
61cmp_elem (void *cls, 60cmp_elem(void *cls,
62 struct Element *e1, 61 struct Element *e1,
63 struct Element *e2) 62 struct Element *e2)
64{ 63{
65 if (e1->value == e2->value) 64 if (e1->value == e2->value)
66 return 0; 65 return 0;
@@ -69,7 +68,7 @@ cmp_elem (void *cls,
69 68
70 69
71int 70int
72main (int argc, char **argv) 71main(int argc, char **argv)
73{ 72{
74 unsigned int values[] = { 73 unsigned int values[] = {
75 4, 5, 8, 6, 9, 3, 7, 2, 1, 0 74 4, 5, 8, 6, 9, 3, 7, 2, 1, 0
@@ -79,33 +78,33 @@ main (int argc, char **argv)
79 struct Element *e; 78 struct Element *e;
80 unsigned int want; 79 unsigned int want;
81 80
82 GNUNET_log_setup ("test-container-dll", 81 GNUNET_log_setup("test-container-dll",
83 "WARNING", 82 "WARNING",
84 NULL); 83 NULL);
85 for (unsigned int off=0; 84 for (unsigned int off = 0;
86 0 != values[off]; 85 0 != values[off];
87 off++) 86 off++)
88 { 87 {
89 e = GNUNET_new (struct Element); 88 e = GNUNET_new(struct Element);
90 e->value = values[off]; 89 e->value = values[off];
91 GNUNET_CONTAINER_DLL_insert_sorted (struct Element, 90 GNUNET_CONTAINER_DLL_insert_sorted(struct Element,
92 cmp_elem, 91 cmp_elem,
93 NULL, 92 NULL,
94 head, 93 head,
95 tail, 94 tail,
96 e); 95 e);
97 } 96 }
98 97
99 want = 1; 98 want = 1;
100 while (NULL != (e = head)) 99 while (NULL != (e = head))
101 { 100 {
102 GNUNET_assert (e->value == want); 101 GNUNET_assert(e->value == want);
103 GNUNET_CONTAINER_DLL_remove (head, 102 GNUNET_CONTAINER_DLL_remove(head,
104 tail, 103 tail,
105 e); 104 e);
106 GNUNET_free (e); 105 GNUNET_free(e);
107 want++; 106 want++;
108 } 107 }
109 return 0; 108 return 0;
110} 109}
111 110
diff --git a/src/util/test_container_heap.c b/src/util/test_container_heap.c
index f95032ca0..8df6553b6 100644
--- a/src/util/test_container_heap.c
+++ b/src/util/test_container_heap.c
@@ -1,19 +1,19 @@
1/* 1/*
2 This file is part of GNUnet. 2 This file is part of GNUnet.
3 Copyright (C) 2008 GNUnet e.V. 3 Copyright (C) 2008 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 */ 19 */
@@ -28,23 +28,23 @@
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30static int 30static int
31iterator_callback (void *cls, 31iterator_callback(void *cls,
32 struct GNUNET_CONTAINER_HeapNode *node, 32 struct GNUNET_CONTAINER_HeapNode *node,
33 void *element, GNUNET_CONTAINER_HeapCostType cost) 33 void *element, GNUNET_CONTAINER_HeapCostType cost)
34{ 34{
35 return GNUNET_OK; 35 return GNUNET_OK;
36} 36}
37 37
38static int 38static int
39nstrcmp (const char *a, const char *b) 39nstrcmp(const char *a, const char *b)
40{ 40{
41 GNUNET_assert (a != NULL); 41 GNUNET_assert(a != NULL);
42 GNUNET_assert (b != NULL); 42 GNUNET_assert(b != NULL);
43 return strcmp (a, b); 43 return strcmp(a, b);
44} 44}
45 45
46static int 46static int
47check () 47check()
48{ 48{
49 struct GNUNET_CONTAINER_Heap *myHeap; 49 struct GNUNET_CONTAINER_Heap *myHeap;
50 struct GNUNET_CONTAINER_HeapNode *n1; 50 struct GNUNET_CONTAINER_HeapNode *n1;
@@ -57,234 +57,234 @@ check ()
57 struct GNUNET_CONTAINER_HeapNode *n8; 57 struct GNUNET_CONTAINER_HeapNode *n8;
58 const char *r; 58 const char *r;
59 59
60 myHeap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 60 myHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
61 61
62 // GNUNET_CONTAINER_heap_remove_root heap empty, taking if-branch 62 // GNUNET_CONTAINER_heap_remove_root heap empty, taking if-branch
63 n1 = GNUNET_CONTAINER_heap_remove_root (myHeap); 63 n1 = GNUNET_CONTAINER_heap_remove_root(myHeap);
64 GNUNET_assert (NULL == n1); 64 GNUNET_assert(NULL == n1);
65 65
66 // GNUNET_CONTAINER_heap_peek heap empty, taking if-branch 66 // GNUNET_CONTAINER_heap_peek heap empty, taking if-branch
67 n1 = GNUNET_CONTAINER_heap_peek (myHeap); 67 n1 = GNUNET_CONTAINER_heap_peek(myHeap);
68 GNUNET_assert (NULL == n1); 68 GNUNET_assert(NULL == n1);
69 69
70 // GNUNET_CONTAINER_heap_walk_get_next: heap empty, taking if-branch 70 // GNUNET_CONTAINER_heap_walk_get_next: heap empty, taking if-branch
71 n1 = GNUNET_CONTAINER_heap_walk_get_next (myHeap); 71 n1 = GNUNET_CONTAINER_heap_walk_get_next(myHeap);
72 GNUNET_assert (NULL == n1); 72 GNUNET_assert(NULL == n1);
73 73
74 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "11", 11); 74 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "11", 11);
75 GNUNET_assert (NULL != n1); 75 GNUNET_assert(NULL != n1);
76 76
77 77
78 // GNUNET_CONTAINER_heap_peek not empty, taking if-branch 78 // GNUNET_CONTAINER_heap_peek not empty, taking if-branch
79 n2 = NULL; 79 n2 = NULL;
80 n2 = GNUNET_CONTAINER_heap_peek (myHeap); 80 n2 = GNUNET_CONTAINER_heap_peek(myHeap);
81 GNUNET_assert (NULL != n2); 81 GNUNET_assert(NULL != n2);
82 82
83 // GNUNET_CONTAINER_heap_walk_get_next: 1 element 83 // GNUNET_CONTAINER_heap_walk_get_next: 1 element
84 n1 = NULL; 84 n1 = NULL;
85 n1 = GNUNET_CONTAINER_heap_walk_get_next (myHeap); 85 n1 = GNUNET_CONTAINER_heap_walk_get_next(myHeap);
86 GNUNET_assert (NULL != n1); 86 GNUNET_assert(NULL != n1);
87 87
88 GNUNET_CONTAINER_heap_iterate (myHeap, &iterator_callback, NULL); 88 GNUNET_CONTAINER_heap_iterate(myHeap, &iterator_callback, NULL);
89 GNUNET_assert (1 == GNUNET_CONTAINER_heap_get_size (myHeap)); 89 GNUNET_assert(1 == GNUNET_CONTAINER_heap_get_size(myHeap));
90 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "78", 78); 90 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "78", 78);
91 GNUNET_assert (2 == GNUNET_CONTAINER_heap_get_size (myHeap)); 91 GNUNET_assert(2 == GNUNET_CONTAINER_heap_get_size(myHeap));
92 GNUNET_assert (0 == strcmp ("78", GNUNET_CONTAINER_heap_remove_node (n2))); 92 GNUNET_assert(0 == strcmp("78", GNUNET_CONTAINER_heap_remove_node(n2)));
93 GNUNET_assert (1 == GNUNET_CONTAINER_heap_get_size (myHeap)); 93 GNUNET_assert(1 == GNUNET_CONTAINER_heap_get_size(myHeap));
94 GNUNET_CONTAINER_heap_iterate (myHeap, &iterator_callback, NULL); 94 GNUNET_CONTAINER_heap_iterate(myHeap, &iterator_callback, NULL);
95 95
96 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "15", 5); 96 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "15", 5);
97 GNUNET_CONTAINER_heap_update_cost (n3, 15); 97 GNUNET_CONTAINER_heap_update_cost(n3, 15);
98 GNUNET_assert (2 == GNUNET_CONTAINER_heap_get_size (myHeap)); 98 GNUNET_assert(2 == GNUNET_CONTAINER_heap_get_size(myHeap));
99 GNUNET_CONTAINER_heap_iterate (myHeap, &iterator_callback, NULL); 99 GNUNET_CONTAINER_heap_iterate(myHeap, &iterator_callback, NULL);
100 100
101 n4 = GNUNET_CONTAINER_heap_insert (myHeap, "50", 50); 101 n4 = GNUNET_CONTAINER_heap_insert(myHeap, "50", 50);
102 GNUNET_CONTAINER_heap_update_cost (n4, 50); 102 GNUNET_CONTAINER_heap_update_cost(n4, 50);
103 GNUNET_assert (3 == GNUNET_CONTAINER_heap_get_size (myHeap)); 103 GNUNET_assert(3 == GNUNET_CONTAINER_heap_get_size(myHeap));
104 GNUNET_CONTAINER_heap_iterate (myHeap, &iterator_callback, NULL); 104 GNUNET_CONTAINER_heap_iterate(myHeap, &iterator_callback, NULL);
105 105
106 n5 = GNUNET_CONTAINER_heap_insert (myHeap, "100", 100); 106 n5 = GNUNET_CONTAINER_heap_insert(myHeap, "100", 100);
107 n6 = GNUNET_CONTAINER_heap_insert (myHeap, "30/200", 30); 107 n6 = GNUNET_CONTAINER_heap_insert(myHeap, "30/200", 30);
108 GNUNET_assert (5 == GNUNET_CONTAINER_heap_get_size (myHeap)); 108 GNUNET_assert(5 == GNUNET_CONTAINER_heap_get_size(myHeap));
109 GNUNET_CONTAINER_heap_remove_node (n5); 109 GNUNET_CONTAINER_heap_remove_node(n5);
110 r = GNUNET_CONTAINER_heap_remove_root (myHeap); /* n1 */ 110 r = GNUNET_CONTAINER_heap_remove_root(myHeap); /* n1 */
111 GNUNET_assert (NULL != r); 111 GNUNET_assert(NULL != r);
112 GNUNET_assert (0 == strcmp ("11", r)); 112 GNUNET_assert(0 == strcmp("11", r));
113 GNUNET_CONTAINER_heap_update_cost (n6, 200); 113 GNUNET_CONTAINER_heap_update_cost(n6, 200);
114 GNUNET_CONTAINER_heap_remove_node (n3); 114 GNUNET_CONTAINER_heap_remove_node(n3);
115 r = GNUNET_CONTAINER_heap_remove_root (myHeap); /* n4 */ 115 r = GNUNET_CONTAINER_heap_remove_root(myHeap); /* n4 */
116 GNUNET_assert (NULL != r); 116 GNUNET_assert(NULL != r);
117 GNUNET_assert (0 == strcmp ("50", r)); 117 GNUNET_assert(0 == strcmp("50", r));
118 r = GNUNET_CONTAINER_heap_remove_root (myHeap); /* n6 */ 118 r = GNUNET_CONTAINER_heap_remove_root(myHeap); /* n6 */
119 GNUNET_assert (NULL != r); 119 GNUNET_assert(NULL != r);
120 GNUNET_assert (0 == strcmp ("30/200", r)); 120 GNUNET_assert(0 == strcmp("30/200", r));
121 GNUNET_assert (0 == GNUNET_CONTAINER_heap_get_size (myHeap)); 121 GNUNET_assert(0 == GNUNET_CONTAINER_heap_get_size(myHeap));
122 122
123 GNUNET_CONTAINER_heap_destroy (myHeap); 123 GNUNET_CONTAINER_heap_destroy(myHeap);
124 124
125 // My additions to a complete testcase 125 // My additions to a complete testcase
126 // Testing a GNUNET_CONTAINER_HEAP_ORDER_MIN 126 // Testing a GNUNET_CONTAINER_HEAP_ORDER_MIN
127 // Testing remove_node 127 // Testing remove_node
128 128
129 myHeap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MIN); 129 myHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MIN);
130 130
131 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 131 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
132 GNUNET_CONTAINER_heap_update_cost (n1, 15); 132 GNUNET_CONTAINER_heap_update_cost(n1, 15);
133 133
134 r = GNUNET_CONTAINER_heap_remove_node (n1); 134 r = GNUNET_CONTAINER_heap_remove_node(n1);
135 GNUNET_assert (NULL != r); 135 GNUNET_assert(NULL != r);
136 GNUNET_assert (0 == strcmp ("10", r)); 136 GNUNET_assert(0 == strcmp("10", r));
137 137
138 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 138 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
139 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 139 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
140 140
141 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 141 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
142 r = GNUNET_CONTAINER_heap_remove_node (n2); 142 r = GNUNET_CONTAINER_heap_remove_node(n2);
143 GNUNET_assert (NULL != r); 143 GNUNET_assert(NULL != r);
144 GNUNET_assert (0 == strcmp ("20", r)); 144 GNUNET_assert(0 == strcmp("20", r));
145 r = GNUNET_CONTAINER_heap_remove_node (n1); 145 r = GNUNET_CONTAINER_heap_remove_node(n1);
146 GNUNET_assert (NULL != r); 146 GNUNET_assert(NULL != r);
147 GNUNET_assert (0 == strcmp ("10", r)); 147 GNUNET_assert(0 == strcmp("10", r));
148 148
149 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 149 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
150 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 150 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
151 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 10); 151 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 10);
152 152
153 GNUNET_CONTAINER_heap_remove_node (n2); 153 GNUNET_CONTAINER_heap_remove_node(n2);
154 GNUNET_CONTAINER_heap_remove_node (n1); 154 GNUNET_CONTAINER_heap_remove_node(n1);
155 r = GNUNET_CONTAINER_heap_remove_root (myHeap); 155 r = GNUNET_CONTAINER_heap_remove_root(myHeap);
156 GNUNET_assert (NULL != r); 156 GNUNET_assert(NULL != r);
157 GNUNET_assert (0 == strcmp ("30", r)); 157 GNUNET_assert(0 == strcmp("30", r));
158 158
159 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 159 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
160 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 160 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
161 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 10); 161 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 10);
162 162
163 GNUNET_CONTAINER_heap_remove_node (n2); 163 GNUNET_CONTAINER_heap_remove_node(n2);
164 GNUNET_CONTAINER_heap_remove_node (n1); 164 GNUNET_CONTAINER_heap_remove_node(n1);
165 r = GNUNET_CONTAINER_heap_remove_node (n3); 165 r = GNUNET_CONTAINER_heap_remove_node(n3);
166 GNUNET_assert (NULL != r); 166 GNUNET_assert(NULL != r);
167 GNUNET_assert (0 == strcmp ("30", r)); 167 GNUNET_assert(0 == strcmp("30", r));
168 168
169 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 169 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
170 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 20); 170 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 20);
171 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 30); 171 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 30);
172 172
173 GNUNET_assert (0 == nstrcmp ("20", GNUNET_CONTAINER_heap_remove_node (n2))); 173 GNUNET_assert(0 == nstrcmp("20", GNUNET_CONTAINER_heap_remove_node(n2)));
174 GNUNET_assert (0 == 174 GNUNET_assert(0 ==
175 nstrcmp ("10", GNUNET_CONTAINER_heap_remove_root (myHeap))); 175 nstrcmp("10", GNUNET_CONTAINER_heap_remove_root(myHeap)));
176 GNUNET_assert (0 == 176 GNUNET_assert(0 ==
177 nstrcmp ("30", GNUNET_CONTAINER_heap_remove_root (myHeap))); 177 nstrcmp("30", GNUNET_CONTAINER_heap_remove_root(myHeap)));
178 178
179 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 179 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
180 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 20); 180 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 20);
181 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 30); 181 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 30);
182 n4 = GNUNET_CONTAINER_heap_insert (myHeap, "40", 40); 182 n4 = GNUNET_CONTAINER_heap_insert(myHeap, "40", 40);
183 n5 = GNUNET_CONTAINER_heap_insert (myHeap, "50", 50); 183 n5 = GNUNET_CONTAINER_heap_insert(myHeap, "50", 50);
184 n6 = GNUNET_CONTAINER_heap_insert (myHeap, "60", 60); 184 n6 = GNUNET_CONTAINER_heap_insert(myHeap, "60", 60);
185 185
186 // Inserting nodes deeper in the tree with lower costs 186 // Inserting nodes deeper in the tree with lower costs
187 n7 = GNUNET_CONTAINER_heap_insert (myHeap, "70", 10); 187 n7 = GNUNET_CONTAINER_heap_insert(myHeap, "70", 10);
188 n8 = GNUNET_CONTAINER_heap_insert (myHeap, "80", 10); 188 n8 = GNUNET_CONTAINER_heap_insert(myHeap, "80", 10);
189 189
190 GNUNET_assert (0 == nstrcmp ("30", GNUNET_CONTAINER_heap_remove_node (n3))); 190 GNUNET_assert(0 == nstrcmp("30", GNUNET_CONTAINER_heap_remove_node(n3)));
191 191
192 // Cleaning up... 192 // Cleaning up...
193 GNUNET_assert (0 == nstrcmp ("60", GNUNET_CONTAINER_heap_remove_node (n6))); 193 GNUNET_assert(0 == nstrcmp("60", GNUNET_CONTAINER_heap_remove_node(n6)));
194 GNUNET_assert (0 == nstrcmp ("50", GNUNET_CONTAINER_heap_remove_node (n5))); 194 GNUNET_assert(0 == nstrcmp("50", GNUNET_CONTAINER_heap_remove_node(n5)));
195 195
196 // Testing heap_walk_get_next 196 // Testing heap_walk_get_next
197 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 197 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
198 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 198 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
199 GNUNET_CONTAINER_heap_walk_get_next (myHeap);; 199 GNUNET_CONTAINER_heap_walk_get_next(myHeap);;
200 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 200 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
201 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 201 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
202 202
203 GNUNET_assert (0 == nstrcmp ("10", GNUNET_CONTAINER_heap_remove_node (n1))); 203 GNUNET_assert(0 == nstrcmp("10", GNUNET_CONTAINER_heap_remove_node(n1)));
204 GNUNET_assert (0 == nstrcmp ("20", GNUNET_CONTAINER_heap_remove_node (n2))); 204 GNUNET_assert(0 == nstrcmp("20", GNUNET_CONTAINER_heap_remove_node(n2)));
205 GNUNET_assert (0 == nstrcmp ("40", GNUNET_CONTAINER_heap_remove_node (n4))); 205 GNUNET_assert(0 == nstrcmp("40", GNUNET_CONTAINER_heap_remove_node(n4)));
206 GNUNET_assert (0 == nstrcmp ("70", GNUNET_CONTAINER_heap_remove_node (n7))); 206 GNUNET_assert(0 == nstrcmp("70", GNUNET_CONTAINER_heap_remove_node(n7)));
207 GNUNET_assert (0 == nstrcmp ("80", GNUNET_CONTAINER_heap_remove_node (n8))); 207 GNUNET_assert(0 == nstrcmp("80", GNUNET_CONTAINER_heap_remove_node(n8)));
208 208
209 // End Testing remove_node 209 // End Testing remove_node
210 210
211 // Testing a GNUNET_CONTAINER_HEAP_ORDER_MAX 211 // Testing a GNUNET_CONTAINER_HEAP_ORDER_MAX
212 GNUNET_CONTAINER_heap_destroy (myHeap); 212 GNUNET_CONTAINER_heap_destroy(myHeap);
213 213
214 myHeap = GNUNET_CONTAINER_heap_create (GNUNET_CONTAINER_HEAP_ORDER_MAX); 214 myHeap = GNUNET_CONTAINER_heap_create(GNUNET_CONTAINER_HEAP_ORDER_MAX);
215 215
216 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 216 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
217 GNUNET_CONTAINER_heap_update_cost (n1, 15); 217 GNUNET_CONTAINER_heap_update_cost(n1, 15);
218 218
219 GNUNET_assert (0 == nstrcmp ("10", GNUNET_CONTAINER_heap_remove_node (n1))); 219 GNUNET_assert(0 == nstrcmp("10", GNUNET_CONTAINER_heap_remove_node(n1)));
220 220
221 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 221 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
222 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 222 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
223 223
224 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 224 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
225 GNUNET_assert (0 == nstrcmp ("20", GNUNET_CONTAINER_heap_remove_node (n2))); 225 GNUNET_assert(0 == nstrcmp("20", GNUNET_CONTAINER_heap_remove_node(n2)));
226 GNUNET_assert (0 == nstrcmp ("10", GNUNET_CONTAINER_heap_remove_node (n1))); 226 GNUNET_assert(0 == nstrcmp("10", GNUNET_CONTAINER_heap_remove_node(n1)));
227 227
228 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 228 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
229 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 229 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
230 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 10); 230 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 10);
231 231
232 GNUNET_CONTAINER_heap_remove_node (n2); 232 GNUNET_CONTAINER_heap_remove_node(n2);
233 GNUNET_CONTAINER_heap_remove_node (n1); 233 GNUNET_CONTAINER_heap_remove_node(n1);
234 GNUNET_assert (0 == 234 GNUNET_assert(0 ==
235 nstrcmp ("30", GNUNET_CONTAINER_heap_remove_root (myHeap))); 235 nstrcmp("30", GNUNET_CONTAINER_heap_remove_root(myHeap)));
236 236
237 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 237 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
238 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 10); 238 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 10);
239 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 10); 239 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 10);
240 240
241 GNUNET_CONTAINER_heap_remove_node (n2); 241 GNUNET_CONTAINER_heap_remove_node(n2);
242 GNUNET_CONTAINER_heap_remove_node (n1); 242 GNUNET_CONTAINER_heap_remove_node(n1);
243 GNUNET_assert (0 == nstrcmp ("30", GNUNET_CONTAINER_heap_remove_node (n3))); 243 GNUNET_assert(0 == nstrcmp("30", GNUNET_CONTAINER_heap_remove_node(n3)));
244 244
245 n1 = GNUNET_CONTAINER_heap_insert (myHeap, "10", 10); 245 n1 = GNUNET_CONTAINER_heap_insert(myHeap, "10", 10);
246 n2 = GNUNET_CONTAINER_heap_insert (myHeap, "20", 20); 246 n2 = GNUNET_CONTAINER_heap_insert(myHeap, "20", 20);
247 n3 = GNUNET_CONTAINER_heap_insert (myHeap, "30", 30); 247 n3 = GNUNET_CONTAINER_heap_insert(myHeap, "30", 30);
248 n4 = GNUNET_CONTAINER_heap_insert (myHeap, "40", 40); 248 n4 = GNUNET_CONTAINER_heap_insert(myHeap, "40", 40);
249 n5 = GNUNET_CONTAINER_heap_insert (myHeap, "50", 50); 249 n5 = GNUNET_CONTAINER_heap_insert(myHeap, "50", 50);
250 n6 = GNUNET_CONTAINER_heap_insert (myHeap, "60", 60); 250 n6 = GNUNET_CONTAINER_heap_insert(myHeap, "60", 60);
251 251
252 // Inserting nodes deeper in the tree with lower costs 252 // Inserting nodes deeper in the tree with lower costs
253 n7 = GNUNET_CONTAINER_heap_insert (myHeap, "70", 10); 253 n7 = GNUNET_CONTAINER_heap_insert(myHeap, "70", 10);
254 n8 = GNUNET_CONTAINER_heap_insert (myHeap, "80", 10); 254 n8 = GNUNET_CONTAINER_heap_insert(myHeap, "80", 10);
255 255
256 GNUNET_assert (0 == nstrcmp ("30", GNUNET_CONTAINER_heap_remove_node (n3))); 256 GNUNET_assert(0 == nstrcmp("30", GNUNET_CONTAINER_heap_remove_node(n3)));
257 257
258 // Cleaning up... 258 // Cleaning up...
259 GNUNET_assert (0 == nstrcmp ("60", GNUNET_CONTAINER_heap_remove_node (n6))); 259 GNUNET_assert(0 == nstrcmp("60", GNUNET_CONTAINER_heap_remove_node(n6)));
260 GNUNET_assert (0 == nstrcmp ("50", GNUNET_CONTAINER_heap_remove_node (n5))); 260 GNUNET_assert(0 == nstrcmp("50", GNUNET_CONTAINER_heap_remove_node(n5)));
261 261
262 // Testing heap_walk_get_next 262 // Testing heap_walk_get_next
263 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 263 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
264 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 264 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
265 GNUNET_CONTAINER_heap_walk_get_next (myHeap);; 265 GNUNET_CONTAINER_heap_walk_get_next(myHeap);;
266 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 266 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
267 GNUNET_CONTAINER_heap_walk_get_next (myHeap); 267 GNUNET_CONTAINER_heap_walk_get_next(myHeap);
268 268
269 GNUNET_assert (0 == nstrcmp ("10", GNUNET_CONTAINER_heap_remove_node (n1))); 269 GNUNET_assert(0 == nstrcmp("10", GNUNET_CONTAINER_heap_remove_node(n1)));
270 GNUNET_assert (0 == nstrcmp ("20", GNUNET_CONTAINER_heap_remove_node (n2))); 270 GNUNET_assert(0 == nstrcmp("20", GNUNET_CONTAINER_heap_remove_node(n2)));
271 GNUNET_assert (0 == nstrcmp ("40", GNUNET_CONTAINER_heap_remove_node (n4))); 271 GNUNET_assert(0 == nstrcmp("40", GNUNET_CONTAINER_heap_remove_node(n4)));
272 GNUNET_assert (0 == nstrcmp ("70", GNUNET_CONTAINER_heap_remove_node (n7))); 272 GNUNET_assert(0 == nstrcmp("70", GNUNET_CONTAINER_heap_remove_node(n7)));
273 GNUNET_assert (0 == nstrcmp ("80", GNUNET_CONTAINER_heap_remove_node (n8))); 273 GNUNET_assert(0 == nstrcmp("80", GNUNET_CONTAINER_heap_remove_node(n8)));
274 274
275 // End Testing remove_node 275 // End Testing remove_node
276 276
277 GNUNET_CONTAINER_heap_destroy (myHeap); 277 GNUNET_CONTAINER_heap_destroy(myHeap);
278 278
279 return 0; 279 return 0;
280} 280}
281 281
282 282
283int 283int
284main (int argc, char **argv) 284main(int argc, char **argv)
285{ 285{
286 GNUNET_log_setup ("test-container-heap", "WARNING", NULL); 286 GNUNET_log_setup("test-container-heap", "WARNING", NULL);
287 return check (); 287 return check();
288} 288}
289 289
290/* end of test_container_heap.c */ 290/* end of test_container_heap.c */
diff --git a/src/util/test_container_meta_data.c b/src/util/test_container_meta_data.c
index 416ea7db9..854498f28 100644
--- a/src/util/test_container_meta_data.c
+++ b/src/util/test_container_meta_data.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_container_meta_data.c 22 * @file util/test_container_meta_data.c
@@ -27,11 +27,11 @@
27#include "platform.h" 27#include "platform.h"
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define ABORT(m) { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_meta_data_destroy(m); return 1; } 30#define ABORT(m) { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_meta_data_destroy (m); return 1; }
31 31
32 32
33static int 33static int
34testMeta (int i) 34testMeta(int i)
35{ 35{
36 struct GNUNET_CONTAINER_MetaData *m; 36 struct GNUNET_CONTAINER_MetaData *m;
37 char val[256]; 37 char val[256];
@@ -39,95 +39,95 @@ testMeta (int i)
39 int j; 39 int j;
40 unsigned int size; 40 unsigned int size;
41 41
42 m = GNUNET_CONTAINER_meta_data_create (); 42 m = GNUNET_CONTAINER_meta_data_create();
43 if (GNUNET_OK != 43 if (GNUNET_OK !=
44 GNUNET_CONTAINER_meta_data_insert (m, "<test>", EXTRACTOR_METATYPE_TITLE, 44 GNUNET_CONTAINER_meta_data_insert(m, "<test>", EXTRACTOR_METATYPE_TITLE,
45 EXTRACTOR_METAFORMAT_UTF8, 45 EXTRACTOR_METAFORMAT_UTF8,
46 "text/plain", "TestTitle", 46 "text/plain", "TestTitle",
47 strlen ("TestTitle") + 1)) 47 strlen("TestTitle") + 1))
48 ABORT (m); 48 ABORT(m);
49 if (GNUNET_OK != 49 if (GNUNET_OK !=
50 GNUNET_CONTAINER_meta_data_insert (m, "<test>", 50 GNUNET_CONTAINER_meta_data_insert(m, "<test>",
51 EXTRACTOR_METATYPE_AUTHOR_NAME, 51 EXTRACTOR_METATYPE_AUTHOR_NAME,
52 EXTRACTOR_METAFORMAT_UTF8, 52 EXTRACTOR_METAFORMAT_UTF8,
53 "text/plain", "TestTitle", 53 "text/plain", "TestTitle",
54 strlen ("TestTitle") + 1)) 54 strlen("TestTitle") + 1))
55 ABORT (m); 55 ABORT(m);
56 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_insert (m, "<test>", EXTRACTOR_METATYPE_TITLE, EXTRACTOR_METAFORMAT_UTF8, "text/plain", "TestTitle", strlen ("TestTitle") + 1)) /* dup! */ 56 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_insert(m, "<test>", EXTRACTOR_METATYPE_TITLE, EXTRACTOR_METAFORMAT_UTF8, "text/plain", "TestTitle", strlen("TestTitle") + 1)) /* dup! */
57 ABORT (m); 57 ABORT(m);
58 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_insert (m, "<test>", EXTRACTOR_METATYPE_AUTHOR_NAME, EXTRACTOR_METAFORMAT_UTF8, "text/plain", "TestTitle", strlen ("TestTitle") + 1)) /* dup! */ 58 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_insert(m, "<test>", EXTRACTOR_METATYPE_AUTHOR_NAME, EXTRACTOR_METAFORMAT_UTF8, "text/plain", "TestTitle", strlen("TestTitle") + 1)) /* dup! */
59 ABORT (m); 59 ABORT(m);
60 if (2 != GNUNET_CONTAINER_meta_data_iterate (m, NULL, NULL)) 60 if (2 != GNUNET_CONTAINER_meta_data_iterate(m, NULL, NULL))
61 ABORT (m); 61 ABORT(m);
62 if (GNUNET_OK != 62 if (GNUNET_OK !=
63 GNUNET_CONTAINER_meta_data_delete (m, EXTRACTOR_METATYPE_AUTHOR_NAME, 63 GNUNET_CONTAINER_meta_data_delete(m, EXTRACTOR_METATYPE_AUTHOR_NAME,
64 "TestTitle", strlen ("TestTitle") + 1)) 64 "TestTitle", strlen("TestTitle") + 1))
65 ABORT (m); 65 ABORT(m);
66 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_delete (m, EXTRACTOR_METATYPE_AUTHOR_NAME, "TestTitle", strlen ("TestTitle") + 1)) /* already gone */ 66 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_delete(m, EXTRACTOR_METATYPE_AUTHOR_NAME, "TestTitle", strlen("TestTitle") + 1)) /* already gone */
67 ABORT (m); 67 ABORT(m);
68 if (1 != GNUNET_CONTAINER_meta_data_iterate (m, NULL, NULL)) 68 if (1 != GNUNET_CONTAINER_meta_data_iterate(m, NULL, NULL))
69 ABORT (m); 69 ABORT(m);
70 if (GNUNET_OK != 70 if (GNUNET_OK !=
71 GNUNET_CONTAINER_meta_data_delete (m, EXTRACTOR_METATYPE_TITLE, 71 GNUNET_CONTAINER_meta_data_delete(m, EXTRACTOR_METATYPE_TITLE,
72 "TestTitle", strlen ("TestTitle") + 1)) 72 "TestTitle", strlen("TestTitle") + 1))
73 ABORT (m); 73 ABORT(m);
74 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_delete (m, EXTRACTOR_METATYPE_TITLE, "TestTitle", strlen ("TestTitle") + 1)) /* already gone */ 74 if (GNUNET_OK == GNUNET_CONTAINER_meta_data_delete(m, EXTRACTOR_METATYPE_TITLE, "TestTitle", strlen("TestTitle") + 1)) /* already gone */
75 ABORT (m); 75 ABORT(m);
76 if (0 != GNUNET_CONTAINER_meta_data_iterate (m, NULL, NULL)) 76 if (0 != GNUNET_CONTAINER_meta_data_iterate(m, NULL, NULL))
77 ABORT (m); 77 ABORT(m);
78 for (j = 0; j < i; j++) 78 for (j = 0; j < i; j++)
79 { 79 {
80 GNUNET_snprintf (val, sizeof (val), "%s.%d", 80 GNUNET_snprintf(val, sizeof(val), "%s.%d",
81 "A teststring that should compress well.", j); 81 "A teststring that should compress well.", j);
82 if (GNUNET_OK != 82 if (GNUNET_OK !=
83 GNUNET_CONTAINER_meta_data_insert (m, "<test>", 83 GNUNET_CONTAINER_meta_data_insert(m, "<test>",
84 EXTRACTOR_METATYPE_UNKNOWN, 84 EXTRACTOR_METATYPE_UNKNOWN,
85 EXTRACTOR_METAFORMAT_UTF8, 85 EXTRACTOR_METAFORMAT_UTF8,
86 "text/plain", val, strlen (val) + 1)) 86 "text/plain", val, strlen(val) + 1))
87 ABORT (m); 87 ABORT(m);
88 } 88 }
89 if (i != GNUNET_CONTAINER_meta_data_iterate (m, NULL, NULL)) 89 if (i != GNUNET_CONTAINER_meta_data_iterate(m, NULL, NULL))
90 ABORT (m); 90 ABORT(m);
91 91
92 size = GNUNET_CONTAINER_meta_data_get_serialized_size (m); 92 size = GNUNET_CONTAINER_meta_data_get_serialized_size(m);
93 sval = NULL; 93 sval = NULL;
94 if (size != 94 if (size !=
95 GNUNET_CONTAINER_meta_data_serialize (m, &sval, size, 95 GNUNET_CONTAINER_meta_data_serialize(m, &sval, size,
96 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL)) 96 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL))
97 { 97 {
98 GNUNET_free_non_null (sval); 98 GNUNET_free_non_null(sval);
99 ABORT (m); 99 ABORT(m);
100 } 100 }
101 GNUNET_CONTAINER_meta_data_destroy (m); 101 GNUNET_CONTAINER_meta_data_destroy(m);
102 m = GNUNET_CONTAINER_meta_data_deserialize (sval, size); 102 m = GNUNET_CONTAINER_meta_data_deserialize(sval, size);
103 GNUNET_free (sval); 103 GNUNET_free(sval);
104 if (m == NULL) 104 if (m == NULL)
105 ABORT (m); 105 ABORT(m);
106 for (j = 0; j < i; j++) 106 for (j = 0; j < i; j++)
107 {
108 GNUNET_snprintf (val,
109 sizeof (val),
110 "%s.%d",
111 "A teststring that should compress well.",
112 j);
113 if (GNUNET_OK !=
114 GNUNET_CONTAINER_meta_data_delete (m,
115 EXTRACTOR_METATYPE_UNKNOWN,
116 val,
117 strlen (val) + 1))
118 { 107 {
119 ABORT (m); 108 GNUNET_snprintf(val,
109 sizeof(val),
110 "%s.%d",
111 "A teststring that should compress well.",
112 j);
113 if (GNUNET_OK !=
114 GNUNET_CONTAINER_meta_data_delete(m,
115 EXTRACTOR_METATYPE_UNKNOWN,
116 val,
117 strlen(val) + 1))
118 {
119 ABORT(m);
120 }
120 } 121 }
121 } 122 if (0 != GNUNET_CONTAINER_meta_data_iterate(m, NULL, NULL))
122 if (0 != GNUNET_CONTAINER_meta_data_iterate (m, NULL, NULL)) 123 ABORT(m);
123 ABORT (m); 124 GNUNET_CONTAINER_meta_data_destroy(m);
124 GNUNET_CONTAINER_meta_data_destroy (m);
125 return 0; 125 return 0;
126} 126}
127 127
128 128
129static int 129static int
130testMetaMore (int i) 130testMetaMore(int i)
131{ 131{
132 struct GNUNET_CONTAINER_MetaData *meta; 132 struct GNUNET_CONTAINER_MetaData *meta;
133 int q; 133 int q;
@@ -135,68 +135,68 @@ testMetaMore (int i)
135 char *data; 135 char *data;
136 unsigned long long size; 136 unsigned long long size;
137 137
138 meta = GNUNET_CONTAINER_meta_data_create (); 138 meta = GNUNET_CONTAINER_meta_data_create();
139 for (q = 0; q <= i; q++) 139 for (q = 0; q <= i; q++)
140 { 140 {
141 GNUNET_snprintf (txt, 128, "%u -- %u\n", i, q); 141 GNUNET_snprintf(txt, 128, "%u -- %u\n", i, q);
142 GNUNET_CONTAINER_meta_data_insert (meta, "<test>", 142 GNUNET_CONTAINER_meta_data_insert(meta, "<test>",
143 q % 42 /* EXTRACTOR_metatype_get_max () */, 143 q % 42 /* EXTRACTOR_metatype_get_max () */,
144 EXTRACTOR_METAFORMAT_UTF8, "text/plain", 144 EXTRACTOR_METAFORMAT_UTF8, "text/plain",
145 txt, strlen (txt) + 1); 145 txt, strlen(txt) + 1);
146 } 146 }
147 size = GNUNET_CONTAINER_meta_data_get_serialized_size (meta); 147 size = GNUNET_CONTAINER_meta_data_get_serialized_size(meta);
148 data = GNUNET_malloc (size * 4); 148 data = GNUNET_malloc(size * 4);
149 if (size != 149 if (size !=
150 GNUNET_CONTAINER_meta_data_serialize (meta, &data, size * 4, 150 GNUNET_CONTAINER_meta_data_serialize(meta, &data, size * 4,
151 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL)) 151 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL))
152 { 152 {
153 GNUNET_free (data); 153 GNUNET_free(data);
154 ABORT (meta); 154 ABORT(meta);
155 } 155 }
156 GNUNET_CONTAINER_meta_data_destroy (meta); 156 GNUNET_CONTAINER_meta_data_destroy(meta);
157 GNUNET_free (data); 157 GNUNET_free(data);
158 return 0; 158 return 0;
159} 159}
160 160
161 161
162static int 162static int
163testMetaLink () 163testMetaLink()
164{ 164{
165 struct GNUNET_CONTAINER_MetaData *m; 165 struct GNUNET_CONTAINER_MetaData *m;
166 char *val; 166 char *val;
167 unsigned int size; 167 unsigned int size;
168 168
169 m = GNUNET_CONTAINER_meta_data_create (); 169 m = GNUNET_CONTAINER_meta_data_create();
170 if (GNUNET_OK != 170 if (GNUNET_OK !=
171 GNUNET_CONTAINER_meta_data_insert (m, "<test>", 171 GNUNET_CONTAINER_meta_data_insert(m, "<test>",
172 EXTRACTOR_METATYPE_UNKNOWN, 172 EXTRACTOR_METATYPE_UNKNOWN,
173 EXTRACTOR_METAFORMAT_UTF8, 173 EXTRACTOR_METAFORMAT_UTF8,
174 "text/plain", "link", 174 "text/plain", "link",
175 strlen ("link") + 1)) 175 strlen("link") + 1))
176 ABORT (m); 176 ABORT(m);
177 if (GNUNET_OK != 177 if (GNUNET_OK !=
178 GNUNET_CONTAINER_meta_data_insert (m, "<test>", 178 GNUNET_CONTAINER_meta_data_insert(m, "<test>",
179 EXTRACTOR_METATYPE_FILENAME, 179 EXTRACTOR_METATYPE_FILENAME,
180 EXTRACTOR_METAFORMAT_UTF8, 180 EXTRACTOR_METAFORMAT_UTF8,
181 "text/plain", "lib-link.m4", 181 "text/plain", "lib-link.m4",
182 strlen ("lib-link.m4") + 1)) 182 strlen("lib-link.m4") + 1))
183 ABORT (m); 183 ABORT(m);
184 val = NULL; 184 val = NULL;
185 size = 185 size =
186 GNUNET_CONTAINER_meta_data_serialize (m, &val, (size_t) - 1, 186 GNUNET_CONTAINER_meta_data_serialize(m, &val, (size_t)-1,
187 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL); 187 GNUNET_CONTAINER_META_DATA_SERIALIZE_FULL);
188 GNUNET_CONTAINER_meta_data_destroy (m); 188 GNUNET_CONTAINER_meta_data_destroy(m);
189 m = GNUNET_CONTAINER_meta_data_deserialize (val, size); 189 m = GNUNET_CONTAINER_meta_data_deserialize(val, size);
190 GNUNET_free (val); 190 GNUNET_free(val);
191 if (m == NULL) 191 if (m == NULL)
192 ABORT (m); 192 ABORT(m);
193 GNUNET_CONTAINER_meta_data_destroy (m); 193 GNUNET_CONTAINER_meta_data_destroy(m);
194 return 0; 194 return 0;
195} 195}
196 196
197 197
198static int 198static int
199check () 199check()
200{ 200{
201 struct GNUNET_CONTAINER_MetaData *meta; 201 struct GNUNET_CONTAINER_MetaData *meta;
202 struct GNUNET_CONTAINER_MetaData *meta2; 202 struct GNUNET_CONTAINER_MetaData *meta2;
@@ -206,143 +206,143 @@ check ()
206 char *str; 206 char *str;
207 unsigned char *thumb; 207 unsigned char *thumb;
208 208
209 meta = GNUNET_CONTAINER_meta_data_create (); 209 meta = GNUNET_CONTAINER_meta_data_create();
210 meta2 = GNUNET_CONTAINER_meta_data_create (); 210 meta2 = GNUNET_CONTAINER_meta_data_create();
211 for (q = 0; q <= i; q++) 211 for (q = 0; q <= i; q++)
212 { 212 {
213 GNUNET_snprintf (txt, 128, "%u -- %u\n", i, q); 213 GNUNET_snprintf(txt, 128, "%u -- %u\n", i, q);
214 GNUNET_CONTAINER_meta_data_insert (meta, "<test>", 214 GNUNET_CONTAINER_meta_data_insert(meta, "<test>",
215 EXTRACTOR_METATYPE_UNKNOWN, 215 EXTRACTOR_METATYPE_UNKNOWN,
216 EXTRACTOR_METAFORMAT_UTF8, "text/plain", 216 EXTRACTOR_METAFORMAT_UTF8, "text/plain",
217 "TestTitle", strlen ("TestTitle") + 1); 217 "TestTitle", strlen("TestTitle") + 1);
218 GNUNET_CONTAINER_meta_data_insert (meta2, "<test>", 218 GNUNET_CONTAINER_meta_data_insert(meta2, "<test>",
219 EXTRACTOR_METATYPE_UNKNOWN, 219 EXTRACTOR_METATYPE_UNKNOWN,
220 EXTRACTOR_METAFORMAT_UTF8, "text/plain", 220 EXTRACTOR_METAFORMAT_UTF8, "text/plain",
221 "TestTitle", strlen ("TestTitle") + 1); 221 "TestTitle", strlen("TestTitle") + 1);
222 } 222 }
223 223
224 //check meta_data_test_equal 224 //check meta_data_test_equal
225 if (GNUNET_YES != GNUNET_CONTAINER_meta_data_test_equal (meta, meta2)) 225 if (GNUNET_YES != GNUNET_CONTAINER_meta_data_test_equal(meta, meta2))
226 { 226 {
227 GNUNET_CONTAINER_meta_data_destroy (meta2); 227 GNUNET_CONTAINER_meta_data_destroy(meta2);
228 ABORT (meta); 228 ABORT(meta);
229 } 229 }
230 230
231 //check meta_data_clear 231 //check meta_data_clear
232 GNUNET_CONTAINER_meta_data_clear (meta2); 232 GNUNET_CONTAINER_meta_data_clear(meta2);
233 if (0 != GNUNET_CONTAINER_meta_data_iterate (meta2, NULL, NULL)) 233 if (0 != GNUNET_CONTAINER_meta_data_iterate(meta2, NULL, NULL))
234 { 234 {
235 GNUNET_CONTAINER_meta_data_destroy (meta2); 235 GNUNET_CONTAINER_meta_data_destroy(meta2);
236 ABORT (meta); 236 ABORT(meta);
237 } 237 }
238 // check equal branch in meta_data_test_equal 238 // check equal branch in meta_data_test_equal
239 if (GNUNET_YES != GNUNET_CONTAINER_meta_data_test_equal (meta, meta)) 239 if (GNUNET_YES != GNUNET_CONTAINER_meta_data_test_equal(meta, meta))
240 { 240 {
241 GNUNET_CONTAINER_meta_data_destroy (meta2); 241 GNUNET_CONTAINER_meta_data_destroy(meta2);
242 ABORT (meta); 242 ABORT(meta);
243 } 243 }
244 // check "count" branch in meta_data_test_equal 244 // check "count" branch in meta_data_test_equal
245 if (GNUNET_NO != GNUNET_CONTAINER_meta_data_test_equal (meta, meta2)) 245 if (GNUNET_NO != GNUNET_CONTAINER_meta_data_test_equal(meta, meta2))
246 { 246 {
247 GNUNET_CONTAINER_meta_data_destroy (meta2); 247 GNUNET_CONTAINER_meta_data_destroy(meta2);
248 ABORT (meta); 248 ABORT(meta);
249 } 249 }
250 250
251 // check meta_data_add_publication_date 251 // check meta_data_add_publication_date
252 GNUNET_CONTAINER_meta_data_add_publication_date (meta2); 252 GNUNET_CONTAINER_meta_data_add_publication_date(meta2);
253 253
254 // check meta_data_merge 254 // check meta_data_merge
255 GNUNET_CONTAINER_meta_data_clear (meta2); 255 GNUNET_CONTAINER_meta_data_clear(meta2);
256 GNUNET_CONTAINER_meta_data_merge (meta2, meta); 256 GNUNET_CONTAINER_meta_data_merge(meta2, meta);
257 if (100 == GNUNET_CONTAINER_meta_data_iterate (meta2, NULL, NULL)) 257 if (100 == GNUNET_CONTAINER_meta_data_iterate(meta2, NULL, NULL))
258 { 258 {
259 GNUNET_CONTAINER_meta_data_destroy (meta2); 259 GNUNET_CONTAINER_meta_data_destroy(meta2);
260 ABORT (meta); 260 ABORT(meta);
261 } 261 }
262 262
263 // check meta_data_get_by_type 263 // check meta_data_get_by_type
264 GNUNET_CONTAINER_meta_data_clear (meta2); 264 GNUNET_CONTAINER_meta_data_clear(meta2);
265 if (NULL != 265 if (NULL !=
266 (str = 266 (str =
267 GNUNET_CONTAINER_meta_data_get_by_type (meta2, 267 GNUNET_CONTAINER_meta_data_get_by_type(meta2,
268 EXTRACTOR_METATYPE_UNKNOWN))) 268 EXTRACTOR_METATYPE_UNKNOWN)))
269 { 269 {
270 GNUNET_CONTAINER_meta_data_destroy (meta2); 270 GNUNET_CONTAINER_meta_data_destroy(meta2);
271 GNUNET_free (str); 271 GNUNET_free(str);
272 ABORT (meta); 272 ABORT(meta);
273 } 273 }
274 274
275 str = 275 str =
276 GNUNET_CONTAINER_meta_data_get_by_type (meta, EXTRACTOR_METATYPE_UNKNOWN); 276 GNUNET_CONTAINER_meta_data_get_by_type(meta, EXTRACTOR_METATYPE_UNKNOWN);
277 GNUNET_assert (NULL != str); 277 GNUNET_assert(NULL != str);
278 if (str[0] != 'T') 278 if (str[0] != 'T')
279 { 279 {
280 GNUNET_CONTAINER_meta_data_destroy (meta2); 280 GNUNET_CONTAINER_meta_data_destroy(meta2);
281 GNUNET_free (str); 281 GNUNET_free(str);
282 ABORT (meta); 282 ABORT(meta);
283 } 283 }
284 GNUNET_free (str); 284 GNUNET_free(str);
285 285
286 // check branch 286 // check branch
287 if (NULL != 287 if (NULL !=
288 (str = 288 (str =
289 GNUNET_CONTAINER_meta_data_get_by_type (meta, 289 GNUNET_CONTAINER_meta_data_get_by_type(meta,
290 EXTRACTOR_METATYPE_PUBLICATION_DATE))) 290 EXTRACTOR_METATYPE_PUBLICATION_DATE)))
291 { 291 {
292 GNUNET_free (str); 292 GNUNET_free(str);
293 GNUNET_CONTAINER_meta_data_destroy (meta2); 293 GNUNET_CONTAINER_meta_data_destroy(meta2);
294 ABORT (meta); 294 ABORT(meta);
295 } 295 }
296 296
297 //check meta_data_get_first_by_types 297 //check meta_data_get_first_by_types
298 str = 298 str =
299 GNUNET_CONTAINER_meta_data_get_first_by_types (meta, 299 GNUNET_CONTAINER_meta_data_get_first_by_types(meta,
300 EXTRACTOR_METATYPE_UNKNOWN, 300 EXTRACTOR_METATYPE_UNKNOWN,
301 -1); 301 -1);
302 GNUNET_assert (NULL != str); 302 GNUNET_assert(NULL != str);
303 if (str[0] != 'T') 303 if (str[0] != 'T')
304 { 304 {
305 GNUNET_CONTAINER_meta_data_destroy (meta2); 305 GNUNET_CONTAINER_meta_data_destroy(meta2);
306 GNUNET_free (str); 306 GNUNET_free(str);
307 ABORT (meta); 307 ABORT(meta);
308 } 308 }
309 GNUNET_free (str); 309 GNUNET_free(str);
310 310
311 //check meta_data_get_thumbnail 311 //check meta_data_get_thumbnail
312 if (GNUNET_CONTAINER_meta_data_get_thumbnail (meta, &thumb) != 0) 312 if (GNUNET_CONTAINER_meta_data_get_thumbnail(meta, &thumb) != 0)
313 { 313 {
314 GNUNET_free (thumb); 314 GNUNET_free(thumb);
315 GNUNET_CONTAINER_meta_data_destroy (meta2); 315 GNUNET_CONTAINER_meta_data_destroy(meta2);
316 ABORT (meta); 316 ABORT(meta);
317 } 317 }
318 GNUNET_CONTAINER_meta_data_destroy (meta2); 318 GNUNET_CONTAINER_meta_data_destroy(meta2);
319 //check meta_data_duplicate 319 //check meta_data_duplicate
320 meta2 = GNUNET_CONTAINER_meta_data_duplicate (meta); 320 meta2 = GNUNET_CONTAINER_meta_data_duplicate(meta);
321 if (200 == GNUNET_CONTAINER_meta_data_iterate (meta2, NULL, NULL)) 321 if (200 == GNUNET_CONTAINER_meta_data_iterate(meta2, NULL, NULL))
322 { 322 {
323 GNUNET_CONTAINER_meta_data_destroy (meta2); 323 GNUNET_CONTAINER_meta_data_destroy(meta2);
324 ABORT (meta); 324 ABORT(meta);
325 } 325 }
326 GNUNET_CONTAINER_meta_data_destroy (meta2); 326 GNUNET_CONTAINER_meta_data_destroy(meta2);
327 GNUNET_CONTAINER_meta_data_destroy (meta); 327 GNUNET_CONTAINER_meta_data_destroy(meta);
328 return 0; 328 return 0;
329} 329}
330 330
331 331
332int 332int
333main (int argc, char *argv[]) 333main(int argc, char *argv[])
334{ 334{
335 int failureCount = 0; 335 int failureCount = 0;
336 int i; 336 int i;
337 337
338 GNUNET_log_setup ("test-container-meta-data", "WARNING", NULL); 338 GNUNET_log_setup("test-container-meta-data", "WARNING", NULL);
339 for (i = 0; i < 255; i++) 339 for (i = 0; i < 255; i++)
340 failureCount += testMeta (i); 340 failureCount += testMeta(i);
341 for (i = 1; i < 255; i++) 341 for (i = 1; i < 255; i++)
342 failureCount += testMetaMore (i); 342 failureCount += testMetaMore(i);
343 failureCount += testMetaLink (); 343 failureCount += testMetaLink();
344 344
345 int ret = check (); 345 int ret = check();
346 346
347 if (ret == 1) 347 if (ret == 1)
348 return 1; 348 return 1;
diff --git a/src/util/test_container_multihashmap.c b/src/util/test_container_multihashmap.c
index b83e90646..482bcb997 100644
--- a/src/util/test_container_multihashmap.c
+++ b/src/util/test_container_multihashmap.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_container_multihashmap.c 22 * @file util/test_container_multihashmap.c
@@ -27,11 +27,11 @@
27#include "platform.h" 27#include "platform.h"
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_multihashmap_destroy(m); if (NULL != iter) GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); return 1; } 30#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_multihashmap_destroy (m); if (NULL != iter) GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); return 1; }
31#define CHECK(c) { if (! (c)) ABORT(); } 31#define CHECK(c) { if (!(c)) ABORT (); }
32 32
33static int 33static int
34testMap (int i) 34testMap(int i)
35{ 35{
36 struct GNUNET_CONTAINER_MultiHashMap *m; 36 struct GNUNET_CONTAINER_MultiHashMap *m;
37 struct GNUNET_HashCode k1; 37 struct GNUNET_HashCode k1;
@@ -41,77 +41,77 @@ testMap (int i)
41 const char *ret; 41 const char *ret;
42 int j; 42 int j;
43 43
44 CHECK (NULL != (m = GNUNET_CONTAINER_multihashmap_create (i, GNUNET_NO))); 44 CHECK(NULL != (m = GNUNET_CONTAINER_multihashmap_create(i, GNUNET_NO)));
45 memset (&k1, 0, sizeof (k1)); 45 memset(&k1, 0, sizeof(k1));
46 memset (&k2, 1, sizeof (k2)); 46 memset(&k2, 1, sizeof(k2));
47 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (m, &k1)); 47 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(m, &k1));
48 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (m, &k2)); 48 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(m, &k2));
49 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove (m, &k1, NULL)); 49 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove(m, &k1, NULL));
50 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove (m, &k2, NULL)); 50 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_remove(m, &k2, NULL));
51 CHECK (NULL == GNUNET_CONTAINER_multihashmap_get (m, &k1)); 51 CHECK(NULL == GNUNET_CONTAINER_multihashmap_get(m, &k1));
52 CHECK (NULL == GNUNET_CONTAINER_multihashmap_get (m, &k2)); 52 CHECK(NULL == GNUNET_CONTAINER_multihashmap_get(m, &k2));
53 CHECK (0 == GNUNET_CONTAINER_multihashmap_remove_all (m, &k1)); 53 CHECK(0 == GNUNET_CONTAINER_multihashmap_remove_all(m, &k1));
54 CHECK (0 == GNUNET_CONTAINER_multihashmap_size (m)); 54 CHECK(0 == GNUNET_CONTAINER_multihashmap_size(m));
55 CHECK (0 == GNUNET_CONTAINER_multihashmap_iterate (m, NULL, NULL)); 55 CHECK(0 == GNUNET_CONTAINER_multihashmap_iterate(m, NULL, NULL));
56 CHECK (0 == GNUNET_CONTAINER_multihashmap_get_multiple (m, &k1, NULL, NULL)); 56 CHECK(0 == GNUNET_CONTAINER_multihashmap_get_multiple(m, &k1, NULL, NULL));
57 57
58 CHECK (GNUNET_OK == 58 CHECK(GNUNET_OK ==
59 GNUNET_CONTAINER_multihashmap_put (m, &k1, "v1", 59 GNUNET_CONTAINER_multihashmap_put(m, &k1, "v1",
60 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 60 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
61 CHECK (1 == GNUNET_CONTAINER_multihashmap_size (m)); 61 CHECK(1 == GNUNET_CONTAINER_multihashmap_size(m));
62 ret = GNUNET_CONTAINER_multihashmap_get (m, &k1); 62 ret = GNUNET_CONTAINER_multihashmap_get(m, &k1);
63 GNUNET_assert (ret != NULL); 63 GNUNET_assert(ret != NULL);
64 CHECK (0 == strcmp ("v1", ret)); 64 CHECK(0 == strcmp("v1", ret));
65 CHECK (GNUNET_NO == 65 CHECK(GNUNET_NO ==
66 GNUNET_CONTAINER_multihashmap_put (m, &k1, "v1", 66 GNUNET_CONTAINER_multihashmap_put(m, &k1, "v1",
67 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 67 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
68 CHECK (1 == GNUNET_CONTAINER_multihashmap_size (m)); 68 CHECK(1 == GNUNET_CONTAINER_multihashmap_size(m));
69 CHECK (GNUNET_OK == 69 CHECK(GNUNET_OK ==
70 GNUNET_CONTAINER_multihashmap_put (m, &k1, "v2", 70 GNUNET_CONTAINER_multihashmap_put(m, &k1, "v2",
71 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 71 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
72 CHECK (GNUNET_OK == 72 CHECK(GNUNET_OK ==
73 GNUNET_CONTAINER_multihashmap_put (m, &k1, "v3", 73 GNUNET_CONTAINER_multihashmap_put(m, &k1, "v3",
74 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 74 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
75 CHECK (3 == GNUNET_CONTAINER_multihashmap_size (m)); 75 CHECK(3 == GNUNET_CONTAINER_multihashmap_size(m));
76 CHECK (GNUNET_OK == GNUNET_CONTAINER_multihashmap_remove (m, &k1, "v3")); 76 CHECK(GNUNET_OK == GNUNET_CONTAINER_multihashmap_remove(m, &k1, "v3"));
77 CHECK (2 == GNUNET_CONTAINER_multihashmap_size (m)); 77 CHECK(2 == GNUNET_CONTAINER_multihashmap_size(m));
78 CHECK (GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains (m, &k1)); 78 CHECK(GNUNET_YES == GNUNET_CONTAINER_multihashmap_contains(m, &k1));
79 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains (m, &k2)); 79 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_contains(m, &k2));
80 CHECK (2 == GNUNET_CONTAINER_multihashmap_get_multiple (m, &k1, NULL, NULL)); 80 CHECK(2 == GNUNET_CONTAINER_multihashmap_get_multiple(m, &k1, NULL, NULL));
81 CHECK (0 == GNUNET_CONTAINER_multihashmap_get_multiple (m, &k2, NULL, NULL)); 81 CHECK(0 == GNUNET_CONTAINER_multihashmap_get_multiple(m, &k2, NULL, NULL));
82 CHECK (2 == GNUNET_CONTAINER_multihashmap_iterate (m, NULL, NULL)); 82 CHECK(2 == GNUNET_CONTAINER_multihashmap_iterate(m, NULL, NULL));
83 iter = GNUNET_CONTAINER_multihashmap_iterator_create (m); 83 iter = GNUNET_CONTAINER_multihashmap_iterator_create(m);
84 CHECK (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next (iter, &key_ret, (const void **)&ret)); 84 CHECK(GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next(iter, &key_ret, (const void **)&ret));
85 CHECK (0 == memcmp (&key_ret, &k1, sizeof (key_ret))); 85 CHECK(0 == memcmp(&key_ret, &k1, sizeof(key_ret)));
86 CHECK (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next (iter, &key_ret, (const void **)&ret)); 86 CHECK(GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next(iter, &key_ret, (const void **)&ret));
87 CHECK (0 == memcmp (&key_ret, &k1, sizeof (key_ret))); 87 CHECK(0 == memcmp(&key_ret, &k1, sizeof(key_ret)));
88 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, NULL)); 88 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_iterator_next(iter, NULL, NULL));
89 GNUNET_free (iter); 89 GNUNET_free(iter);
90 90
91 CHECK (2 == GNUNET_CONTAINER_multihashmap_remove_all (m, &k1)); 91 CHECK(2 == GNUNET_CONTAINER_multihashmap_remove_all(m, &k1));
92 for (j = 0; j < 1024; j++) 92 for (j = 0; j < 1024; j++)
93 CHECK (GNUNET_OK == 93 CHECK(GNUNET_OK ==
94 GNUNET_CONTAINER_multihashmap_put (m, &k1, "v2", 94 GNUNET_CONTAINER_multihashmap_put(m, &k1, "v2",
95 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 95 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
96 iter = GNUNET_CONTAINER_multihashmap_iterator_create (m); 96 iter = GNUNET_CONTAINER_multihashmap_iterator_create(m);
97 for (j = 0; j < GNUNET_CONTAINER_multihashmap_size (m); j++) 97 for (j = 0; j < GNUNET_CONTAINER_multihashmap_size(m); j++)
98 CHECK (GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, NULL)); 98 CHECK(GNUNET_YES == GNUNET_CONTAINER_multihashmap_iterator_next(iter, NULL, NULL));
99 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap_iterator_next (iter, NULL, NULL)); 99 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap_iterator_next(iter, NULL, NULL));
100 GNUNET_CONTAINER_multihashmap_iterator_destroy (iter); 100 GNUNET_CONTAINER_multihashmap_iterator_destroy(iter);
101 101
102 GNUNET_CONTAINER_multihashmap_destroy (m); 102 GNUNET_CONTAINER_multihashmap_destroy(m);
103 return 0; 103 return 0;
104} 104}
105 105
106int 106int
107main (int argc, char *argv[]) 107main(int argc, char *argv[])
108{ 108{
109 int failureCount = 0; 109 int failureCount = 0;
110 int i; 110 int i;
111 111
112 GNUNET_log_setup ("test-container-multihashmap", "WARNING", NULL); 112 GNUNET_log_setup("test-container-multihashmap", "WARNING", NULL);
113 for (i = 1; i < 255; i++) 113 for (i = 1; i < 255; i++)
114 failureCount += testMap (i); 114 failureCount += testMap(i);
115 if (failureCount != 0) 115 if (failureCount != 0)
116 return 1; 116 return 1;
117 return 0; 117 return 0;
diff --git a/src/util/test_container_multihashmap32.c b/src/util/test_container_multihashmap32.c
index e0e813716..d61dea782 100644
--- a/src/util/test_container_multihashmap32.c
+++ b/src/util/test_container_multihashmap32.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_container_multihashmap32.c 22 * @file util/test_container_multihashmap32.c
@@ -28,11 +28,11 @@
28#include "platform.h" 28#include "platform.h"
29#include "gnunet_util_lib.h" 29#include "gnunet_util_lib.h"
30 30
31#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_multihashmap32_destroy(m); return 1; } 31#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (m != NULL) GNUNET_CONTAINER_multihashmap32_destroy (m); return 1; }
32#define CHECK(c) { if (! (c)) ABORT(); } 32#define CHECK(c) { if (!(c)) ABORT (); }
33 33
34static int 34static int
35testMap (int i) 35testMap(int i)
36{ 36{
37 struct GNUNET_CONTAINER_MultiHashMap32 *m; 37 struct GNUNET_CONTAINER_MultiHashMap32 *m;
38 uint32_t k1; 38 uint32_t k1;
@@ -40,63 +40,63 @@ testMap (int i)
40 const char *ret; 40 const char *ret;
41 int j; 41 int j;
42 42
43 CHECK (NULL != (m = GNUNET_CONTAINER_multihashmap32_create (i))); 43 CHECK(NULL != (m = GNUNET_CONTAINER_multihashmap32_create(i)));
44 k1 = 0; 44 k1 = 0;
45 k2 = UINT32_MAX; 45 k2 = UINT32_MAX;
46 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains (m, k1)); 46 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains(m, k1));
47 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains (m, k2)); 47 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains(m, k2));
48 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap32_remove (m, k1, NULL)); 48 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap32_remove(m, k1, NULL));
49 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap32_remove (m, k2, NULL)); 49 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap32_remove(m, k2, NULL));
50 CHECK (NULL == GNUNET_CONTAINER_multihashmap32_get (m, k1)); 50 CHECK(NULL == GNUNET_CONTAINER_multihashmap32_get(m, k1));
51 CHECK (NULL == GNUNET_CONTAINER_multihashmap32_get (m, k2)); 51 CHECK(NULL == GNUNET_CONTAINER_multihashmap32_get(m, k2));
52 CHECK (0 == GNUNET_CONTAINER_multihashmap32_remove_all (m, k1)); 52 CHECK(0 == GNUNET_CONTAINER_multihashmap32_remove_all(m, k1));
53 CHECK (0 == GNUNET_CONTAINER_multihashmap32_size (m)); 53 CHECK(0 == GNUNET_CONTAINER_multihashmap32_size(m));
54 CHECK (0 == GNUNET_CONTAINER_multihashmap32_iterate (m, NULL, NULL)); 54 CHECK(0 == GNUNET_CONTAINER_multihashmap32_iterate(m, NULL, NULL));
55 CHECK (0 == GNUNET_CONTAINER_multihashmap32_get_multiple (m, k1, NULL, NULL)); 55 CHECK(0 == GNUNET_CONTAINER_multihashmap32_get_multiple(m, k1, NULL, NULL));
56 56
57 CHECK (GNUNET_OK == 57 CHECK(GNUNET_OK ==
58 GNUNET_CONTAINER_multihashmap32_put (m, k1, "v1", 58 GNUNET_CONTAINER_multihashmap32_put(m, k1, "v1",
59 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 59 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
60 CHECK (1 == GNUNET_CONTAINER_multihashmap32_size (m)); 60 CHECK(1 == GNUNET_CONTAINER_multihashmap32_size(m));
61 ret = GNUNET_CONTAINER_multihashmap32_get (m, k1); 61 ret = GNUNET_CONTAINER_multihashmap32_get(m, k1);
62 GNUNET_assert (ret != NULL); 62 GNUNET_assert(ret != NULL);
63 CHECK (0 == strcmp ("v1", ret)); 63 CHECK(0 == strcmp("v1", ret));
64 CHECK (GNUNET_NO == 64 CHECK(GNUNET_NO ==
65 GNUNET_CONTAINER_multihashmap32_put (m, k1, "v1", 65 GNUNET_CONTAINER_multihashmap32_put(m, k1, "v1",
66 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 66 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
67 CHECK (1 == GNUNET_CONTAINER_multihashmap32_size (m)); 67 CHECK(1 == GNUNET_CONTAINER_multihashmap32_size(m));
68 CHECK (GNUNET_OK == 68 CHECK(GNUNET_OK ==
69 GNUNET_CONTAINER_multihashmap32_put (m, k1, "v2", 69 GNUNET_CONTAINER_multihashmap32_put(m, k1, "v2",
70 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 70 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
71 CHECK (GNUNET_OK == 71 CHECK(GNUNET_OK ==
72 GNUNET_CONTAINER_multihashmap32_put (m, k1, "v3", 72 GNUNET_CONTAINER_multihashmap32_put(m, k1, "v3",
73 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 73 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
74 CHECK (3 == GNUNET_CONTAINER_multihashmap32_size (m)); 74 CHECK(3 == GNUNET_CONTAINER_multihashmap32_size(m));
75 CHECK (GNUNET_OK == GNUNET_CONTAINER_multihashmap32_remove (m, k1, "v3")); 75 CHECK(GNUNET_OK == GNUNET_CONTAINER_multihashmap32_remove(m, k1, "v3"));
76 CHECK (2 == GNUNET_CONTAINER_multihashmap32_size (m)); 76 CHECK(2 == GNUNET_CONTAINER_multihashmap32_size(m));
77 CHECK (GNUNET_YES == GNUNET_CONTAINER_multihashmap32_contains (m, k1)); 77 CHECK(GNUNET_YES == GNUNET_CONTAINER_multihashmap32_contains(m, k1));
78 CHECK (GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains (m, k2)); 78 CHECK(GNUNET_NO == GNUNET_CONTAINER_multihashmap32_contains(m, k2));
79 CHECK (2 == GNUNET_CONTAINER_multihashmap32_get_multiple (m, k1, NULL, NULL)); 79 CHECK(2 == GNUNET_CONTAINER_multihashmap32_get_multiple(m, k1, NULL, NULL));
80 CHECK (0 == GNUNET_CONTAINER_multihashmap32_get_multiple (m, k2, NULL, NULL)); 80 CHECK(0 == GNUNET_CONTAINER_multihashmap32_get_multiple(m, k2, NULL, NULL));
81 CHECK (2 == GNUNET_CONTAINER_multihashmap32_iterate (m, NULL, NULL)); 81 CHECK(2 == GNUNET_CONTAINER_multihashmap32_iterate(m, NULL, NULL));
82 CHECK (2 == GNUNET_CONTAINER_multihashmap32_remove_all (m, k1)); 82 CHECK(2 == GNUNET_CONTAINER_multihashmap32_remove_all(m, k1));
83 for (j = 0; j < 1024; j++) 83 for (j = 0; j < 1024; j++)
84 CHECK (GNUNET_OK == 84 CHECK(GNUNET_OK ==
85 GNUNET_CONTAINER_multihashmap32_put (m, k1, "v2", 85 GNUNET_CONTAINER_multihashmap32_put(m, k1, "v2",
86 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 86 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
87 GNUNET_CONTAINER_multihashmap32_destroy (m); 87 GNUNET_CONTAINER_multihashmap32_destroy(m);
88 return 0; 88 return 0;
89} 89}
90 90
91int 91int
92main (int argc, char *argv[]) 92main(int argc, char *argv[])
93{ 93{
94 int failureCount = 0; 94 int failureCount = 0;
95 int i; 95 int i;
96 96
97 GNUNET_log_setup ("test-container-multihashmap", "WARNING", NULL); 97 GNUNET_log_setup("test-container-multihashmap", "WARNING", NULL);
98 for (i = 1; i < 255; i++) 98 for (i = 1; i < 255; i++)
99 failureCount += testMap (i); 99 failureCount += testMap(i);
100 if (failureCount != 0) 100 if (failureCount != 0)
101 return 1; 101 return 1;
102 return 0; 102 return 0;
diff --git a/src/util/test_container_multipeermap.c b/src/util/test_container_multipeermap.c
index a8ec8b8f2..67bb5d3db 100644
--- a/src/util/test_container_multipeermap.c
+++ b/src/util/test_container_multipeermap.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_container_multipeermap.c 22 * @file util/test_container_multipeermap.c
@@ -27,11 +27,11 @@
27#include "platform.h" 27#include "platform.h"
28#include "gnunet_util_lib.h" 28#include "gnunet_util_lib.h"
29 29
30#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (NULL != m) GNUNET_CONTAINER_multipeermap_destroy(m); if (NULL != iter) GNUNET_CONTAINER_multipeermap_iterator_destroy (iter); return 1; } 30#define ABORT() { fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); if (NULL != m) GNUNET_CONTAINER_multipeermap_destroy (m); if (NULL != iter) GNUNET_CONTAINER_multipeermap_iterator_destroy (iter); return 1; }
31#define CHECK(c) { if (! (c)) ABORT(); } 31#define CHECK(c) { if (!(c)) ABORT (); }
32 32
33static int 33static int
34testMap (int i) 34testMap(int i)
35{ 35{
36 struct GNUNET_CONTAINER_MultiPeerMap *m; 36 struct GNUNET_CONTAINER_MultiPeerMap *m;
37 struct GNUNET_PeerIdentity k1; 37 struct GNUNET_PeerIdentity k1;
@@ -41,77 +41,77 @@ testMap (int i)
41 const char *ret; 41 const char *ret;
42 int j; 42 int j;
43 43
44 CHECK (NULL != (m = GNUNET_CONTAINER_multipeermap_create (i, GNUNET_NO))); 44 CHECK(NULL != (m = GNUNET_CONTAINER_multipeermap_create(i, GNUNET_NO)));
45 memset (&k1, 0, sizeof (k1)); 45 memset(&k1, 0, sizeof(k1));
46 memset (&k2, 1, sizeof (k2)); 46 memset(&k2, 1, sizeof(k2));
47 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (m, &k1)); 47 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(m, &k1));
48 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (m, &k2)); 48 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(m, &k2));
49 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove (m, &k1, NULL)); 49 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove(m, &k1, NULL));
50 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove (m, &k2, NULL)); 50 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_remove(m, &k2, NULL));
51 CHECK (NULL == GNUNET_CONTAINER_multipeermap_get (m, &k1)); 51 CHECK(NULL == GNUNET_CONTAINER_multipeermap_get(m, &k1));
52 CHECK (NULL == GNUNET_CONTAINER_multipeermap_get (m, &k2)); 52 CHECK(NULL == GNUNET_CONTAINER_multipeermap_get(m, &k2));
53 CHECK (0 == GNUNET_CONTAINER_multipeermap_remove_all (m, &k1)); 53 CHECK(0 == GNUNET_CONTAINER_multipeermap_remove_all(m, &k1));
54 CHECK (0 == GNUNET_CONTAINER_multipeermap_size (m)); 54 CHECK(0 == GNUNET_CONTAINER_multipeermap_size(m));
55 CHECK (0 == GNUNET_CONTAINER_multipeermap_iterate (m, NULL, NULL)); 55 CHECK(0 == GNUNET_CONTAINER_multipeermap_iterate(m, NULL, NULL));
56 CHECK (0 == GNUNET_CONTAINER_multipeermap_get_multiple (m, &k1, NULL, NULL)); 56 CHECK(0 == GNUNET_CONTAINER_multipeermap_get_multiple(m, &k1, NULL, NULL));
57 57
58 CHECK (GNUNET_OK == 58 CHECK(GNUNET_OK ==
59 GNUNET_CONTAINER_multipeermap_put (m, &k1, "v1", 59 GNUNET_CONTAINER_multipeermap_put(m, &k1, "v1",
60 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 60 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
61 CHECK (1 == GNUNET_CONTAINER_multipeermap_size (m)); 61 CHECK(1 == GNUNET_CONTAINER_multipeermap_size(m));
62 ret = GNUNET_CONTAINER_multipeermap_get (m, &k1); 62 ret = GNUNET_CONTAINER_multipeermap_get(m, &k1);
63 GNUNET_assert (ret != NULL); 63 GNUNET_assert(ret != NULL);
64 CHECK (0 == strcmp ("v1", ret)); 64 CHECK(0 == strcmp("v1", ret));
65 CHECK (GNUNET_NO == 65 CHECK(GNUNET_NO ==
66 GNUNET_CONTAINER_multipeermap_put (m, &k1, "v1", 66 GNUNET_CONTAINER_multipeermap_put(m, &k1, "v1",
67 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE)); 67 GNUNET_CONTAINER_MULTIHASHMAPOPTION_REPLACE));
68 CHECK (1 == GNUNET_CONTAINER_multipeermap_size (m)); 68 CHECK(1 == GNUNET_CONTAINER_multipeermap_size(m));
69 CHECK (GNUNET_OK == 69 CHECK(GNUNET_OK ==
70 GNUNET_CONTAINER_multipeermap_put (m, &k1, "v2", 70 GNUNET_CONTAINER_multipeermap_put(m, &k1, "v2",
71 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 71 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
72 CHECK (GNUNET_OK == 72 CHECK(GNUNET_OK ==
73 GNUNET_CONTAINER_multipeermap_put (m, &k1, "v3", 73 GNUNET_CONTAINER_multipeermap_put(m, &k1, "v3",
74 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 74 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
75 CHECK (3 == GNUNET_CONTAINER_multipeermap_size (m)); 75 CHECK(3 == GNUNET_CONTAINER_multipeermap_size(m));
76 CHECK (GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove (m, &k1, "v3")); 76 CHECK(GNUNET_OK == GNUNET_CONTAINER_multipeermap_remove(m, &k1, "v3"));
77 CHECK (2 == GNUNET_CONTAINER_multipeermap_size (m)); 77 CHECK(2 == GNUNET_CONTAINER_multipeermap_size(m));
78 CHECK (GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains (m, &k1)); 78 CHECK(GNUNET_YES == GNUNET_CONTAINER_multipeermap_contains(m, &k1));
79 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains (m, &k2)); 79 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_contains(m, &k2));
80 CHECK (2 == GNUNET_CONTAINER_multipeermap_get_multiple (m, &k1, NULL, NULL)); 80 CHECK(2 == GNUNET_CONTAINER_multipeermap_get_multiple(m, &k1, NULL, NULL));
81 CHECK (0 == GNUNET_CONTAINER_multipeermap_get_multiple (m, &k2, NULL, NULL)); 81 CHECK(0 == GNUNET_CONTAINER_multipeermap_get_multiple(m, &k2, NULL, NULL));
82 CHECK (2 == GNUNET_CONTAINER_multipeermap_iterate (m, NULL, NULL)); 82 CHECK(2 == GNUNET_CONTAINER_multipeermap_iterate(m, NULL, NULL));
83 iter = GNUNET_CONTAINER_multipeermap_iterator_create (m); 83 iter = GNUNET_CONTAINER_multipeermap_iterator_create(m);
84 CHECK (GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter, &key_ret, (const void **)&ret)); 84 CHECK(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(iter, &key_ret, (const void **)&ret));
85 CHECK (0 == memcmp (&key_ret, &k1, sizeof (key_ret))); 85 CHECK(0 == memcmp(&key_ret, &k1, sizeof(key_ret)));
86 CHECK (GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter, &key_ret, (const void **)&ret)); 86 CHECK(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(iter, &key_ret, (const void **)&ret));
87 CHECK (0 == memcmp (&key_ret, &k1, sizeof (key_ret))); 87 CHECK(0 == memcmp(&key_ret, &k1, sizeof(key_ret)));
88 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL)); 88 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_iterator_next(iter, NULL, NULL));
89 GNUNET_free (iter); 89 GNUNET_free(iter);
90 90
91 CHECK (2 == GNUNET_CONTAINER_multipeermap_remove_all (m, &k1)); 91 CHECK(2 == GNUNET_CONTAINER_multipeermap_remove_all(m, &k1));
92 for (j = 0; j < 1024; j++) 92 for (j = 0; j < 1024; j++)
93 CHECK (GNUNET_OK == 93 CHECK(GNUNET_OK ==
94 GNUNET_CONTAINER_multipeermap_put (m, &k1, "v2", 94 GNUNET_CONTAINER_multipeermap_put(m, &k1, "v2",
95 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE)); 95 GNUNET_CONTAINER_MULTIHASHMAPOPTION_MULTIPLE));
96 iter = GNUNET_CONTAINER_multipeermap_iterator_create (m); 96 iter = GNUNET_CONTAINER_multipeermap_iterator_create(m);
97 for (j = 0; j < GNUNET_CONTAINER_multipeermap_size (m); j++) 97 for (j = 0; j < GNUNET_CONTAINER_multipeermap_size(m); j++)
98 CHECK (GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL)); 98 CHECK(GNUNET_YES == GNUNET_CONTAINER_multipeermap_iterator_next(iter, NULL, NULL));
99 CHECK (GNUNET_NO == GNUNET_CONTAINER_multipeermap_iterator_next (iter, NULL, NULL)); 99 CHECK(GNUNET_NO == GNUNET_CONTAINER_multipeermap_iterator_next(iter, NULL, NULL));
100 GNUNET_CONTAINER_multipeermap_iterator_destroy (iter); 100 GNUNET_CONTAINER_multipeermap_iterator_destroy(iter);
101 101
102 GNUNET_CONTAINER_multipeermap_destroy (m); 102 GNUNET_CONTAINER_multipeermap_destroy(m);
103 return 0; 103 return 0;
104} 104}
105 105
106int 106int
107main (int argc, char *argv[]) 107main(int argc, char *argv[])
108{ 108{
109 int failureCount = 0; 109 int failureCount = 0;
110 int i; 110 int i;
111 111
112 GNUNET_log_setup ("test-container-multipeermap", "WARNING", NULL); 112 GNUNET_log_setup("test-container-multipeermap", "WARNING", NULL);
113 for (i = 1; i < 255; i++) 113 for (i = 1; i < 255; i++)
114 failureCount += testMap (i); 114 failureCount += testMap(i);
115 if (failureCount != 0) 115 if (failureCount != 0)
116 return 1; 116 return 1;
117 return 0; 117 return 0;
diff --git a/src/util/test_crypto_crc.c b/src/util/test_crypto_crc.c
index 838da5dbc..fb9d5361b 100644
--- a/src/util/test_crypto_crc.c
+++ b/src/util/test_crypto_crc.c
@@ -11,7 +11,7 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
@@ -20,7 +20,7 @@
20 For the actual CRC code: 20 For the actual CRC code:
21 Copyright abandoned; this code is in the public domain. 21 Copyright abandoned; this code is in the public domain.
22 Provided to GNUnet by peter@horizon.com 22 Provided to GNUnet by peter@horizon.com
23*/ 23 */
24 24
25/** 25/**
26 * @file util/test_crypto_crc.c 26 * @file util/test_crypto_crc.c
@@ -205,16 +205,16 @@ static int expected[] = {
205}; 205};
206 206
207int 207int
208main (int argc, char *argv[]) 208main(int argc, char *argv[])
209{ 209{
210 char buf[1024]; 210 char buf[1024];
211 int i; 211 int i;
212 212
213 GNUNET_log_setup ("test-crypto-crc", "WARNING", NULL); 213 GNUNET_log_setup("test-crypto-crc", "WARNING", NULL);
214 for (i = 0; i < 1024; i++) 214 for (i = 0; i < 1024; i++)
215 buf[i] = (char) i; 215 buf[i] = (char)i;
216 for (i = 0; i < 1024; i++) 216 for (i = 0; i < 1024; i++)
217 if (expected[i] != GNUNET_CRYPTO_crc32_n (&buf[i], 1024 - i)) 217 if (expected[i] != GNUNET_CRYPTO_crc32_n(&buf[i], 1024 - i))
218 return 1; 218 return 1;
219 return 0; 219 return 0;
220} 220}
diff --git a/src/util/test_crypto_ecc_dlog.c b/src/util/test_crypto_ecc_dlog.c
index c0828c354..1be7bb678 100644
--- a/src/util/test_crypto_ecc_dlog.c
+++ b/src/util/test_crypto_ecc_dlog.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_ecc_dlog.c 22 * @file util/test_crypto_ecc_dlog.c
23 * @brief testcase for ECC DLOG calculation 23 * @brief testcase for ECC DLOG calculation
@@ -48,12 +48,12 @@
48 48
49/** 49/**
50 * How many values do we test? 50 * How many values do we test?
51 */ 51 */
52#define TEST_ITER 10 52#define TEST_ITER 10
53 53
54/** 54/**
55 * Range of values to use for MATH tests. 55 * Range of values to use for MATH tests.
56 */ 56 */
57#define MATH_MAX 5 57#define MATH_MAX 5
58 58
59 59
@@ -63,7 +63,7 @@
63 * @param edc context for ECC operations 63 * @param edc context for ECC operations
64 */ 64 */
65static void 65static void
66test_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc) 66test_dlog(struct GNUNET_CRYPTO_EccDlogContext *edc)
67{ 67{
68 gcry_mpi_t fact; 68 gcry_mpi_t fact;
69 gcry_mpi_t n; 69 gcry_mpi_t n;
@@ -74,46 +74,46 @@ test_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc)
74 int x; 74 int x;
75 int iret; 75 int iret;
76 76
77 GNUNET_assert (0 == gcry_mpi_ec_new (&ctx, NULL, CURVE)); 77 GNUNET_assert(0 == gcry_mpi_ec_new(&ctx, NULL, CURVE));
78 g = gcry_mpi_ec_get_point ("g", ctx, 0); 78 g = gcry_mpi_ec_get_point("g", ctx, 0);
79 GNUNET_assert (NULL != g); 79 GNUNET_assert(NULL != g);
80 n = gcry_mpi_ec_get_mpi ("n", ctx, 0); 80 n = gcry_mpi_ec_get_mpi("n", ctx, 0);
81 q = gcry_mpi_point_new (0); 81 q = gcry_mpi_point_new(0);
82 fact = gcry_mpi_new (0); 82 fact = gcry_mpi_new(0);
83 for (i=0;i<TEST_ITER;i++) 83 for (i = 0; i < TEST_ITER; i++)
84 {
85 fprintf (stderr, ".");
86 x = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
87 MAX_FACT);
88 if (0 == GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
89 2))
90 {
91 gcry_mpi_set_ui (fact, x);
92 gcry_mpi_sub (fact, n, fact);
93 x = - x;
94 }
95 else
96 {
97 gcry_mpi_set_ui (fact, x);
98 }
99 gcry_mpi_ec_mul (q, fact, g, ctx);
100 if (x !=
101 (iret = GNUNET_CRYPTO_ecc_dlog (edc,
102 q)))
103 { 84 {
104 fprintf (stderr, 85 fprintf(stderr, ".");
105 "DLOG failed for value %d (%d)\n", 86 x = GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
106 x, 87 MAX_FACT);
107 iret); 88 if (0 == GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK,
108 GNUNET_assert (0); 89 2))
90 {
91 gcry_mpi_set_ui(fact, x);
92 gcry_mpi_sub(fact, n, fact);
93 x = -x;
94 }
95 else
96 {
97 gcry_mpi_set_ui(fact, x);
98 }
99 gcry_mpi_ec_mul(q, fact, g, ctx);
100 if (x !=
101 (iret = GNUNET_CRYPTO_ecc_dlog(edc,
102 q)))
103 {
104 fprintf(stderr,
105 "DLOG failed for value %d (%d)\n",
106 x,
107 iret);
108 GNUNET_assert(0);
109 }
109 } 110 }
110 } 111 gcry_mpi_release(fact);
111 gcry_mpi_release (fact); 112 gcry_mpi_release(n);
112 gcry_mpi_release (n); 113 gcry_mpi_point_release(g);
113 gcry_mpi_point_release (g); 114 gcry_mpi_point_release(q);
114 gcry_mpi_point_release (q); 115 gcry_ctx_release(ctx);
115 gcry_ctx_release (ctx); 116 fprintf(stderr, "\n");
116 fprintf (stderr, "\n");
117} 117}
118 118
119 119
@@ -123,7 +123,7 @@ test_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc)
123 * @param edc context for ECC operations 123 * @param edc context for ECC operations
124 */ 124 */
125static void 125static void
126test_math (struct GNUNET_CRYPTO_EccDlogContext *edc) 126test_math(struct GNUNET_CRYPTO_EccDlogContext *edc)
127{ 127{
128 int i; 128 int i;
129 int j; 129 int j;
@@ -135,59 +135,59 @@ test_math (struct GNUNET_CRYPTO_EccDlogContext *edc)
135 gcry_mpi_point_t r_inv; 135 gcry_mpi_point_t r_inv;
136 gcry_mpi_point_t sum; 136 gcry_mpi_point_t sum;
137 137
138 for (i=-MATH_MAX;i<MATH_MAX;i++) 138 for (i = -MATH_MAX; i < MATH_MAX; i++)
139 {
140 ip = GNUNET_CRYPTO_ecc_dexp (edc, i);
141 for (j=-MATH_MAX;j<MATH_MAX;j++)
142 { 139 {
143 fprintf (stderr, "."); 140 ip = GNUNET_CRYPTO_ecc_dexp(edc, i);
144 jp = GNUNET_CRYPTO_ecc_dexp (edc, j); 141 for (j = -MATH_MAX; j < MATH_MAX; j++)
145 GNUNET_CRYPTO_ecc_rnd (edc, 142 {
146 &r, 143 fprintf(stderr, ".");
147 &r_inv); 144 jp = GNUNET_CRYPTO_ecc_dexp(edc, j);
148 ir = GNUNET_CRYPTO_ecc_add (edc, ip, r); 145 GNUNET_CRYPTO_ecc_rnd(edc,
149 irj = GNUNET_CRYPTO_ecc_add (edc, ir, jp); 146 &r,
150 sum = GNUNET_CRYPTO_ecc_add (edc, irj, r_inv); 147 &r_inv);
151 GNUNET_assert (i + j == 148 ir = GNUNET_CRYPTO_ecc_add(edc, ip, r);
152 GNUNET_CRYPTO_ecc_dlog (edc, 149 irj = GNUNET_CRYPTO_ecc_add(edc, ir, jp);
153 sum)); 150 sum = GNUNET_CRYPTO_ecc_add(edc, irj, r_inv);
154 GNUNET_CRYPTO_ecc_free (jp); 151 GNUNET_assert(i + j ==
155 GNUNET_CRYPTO_ecc_free (ir); 152 GNUNET_CRYPTO_ecc_dlog(edc,
156 GNUNET_CRYPTO_ecc_free (irj); 153 sum));
157 GNUNET_CRYPTO_ecc_free (r); 154 GNUNET_CRYPTO_ecc_free(jp);
158 GNUNET_CRYPTO_ecc_free (r_inv); 155 GNUNET_CRYPTO_ecc_free(ir);
159 GNUNET_CRYPTO_ecc_free (sum); 156 GNUNET_CRYPTO_ecc_free(irj);
157 GNUNET_CRYPTO_ecc_free(r);
158 GNUNET_CRYPTO_ecc_free(r_inv);
159 GNUNET_CRYPTO_ecc_free(sum);
160 }
161 GNUNET_CRYPTO_ecc_free(ip);
160 } 162 }
161 GNUNET_CRYPTO_ecc_free (ip); 163 fprintf(stderr, "\n");
162 }
163 fprintf (stderr, "\n");
164} 164}
165 165
166 166
167 167
168int 168int
169main (int argc, char *argv[]) 169main(int argc, char *argv[])
170{ 170{
171 struct GNUNET_CRYPTO_EccDlogContext *edc; 171 struct GNUNET_CRYPTO_EccDlogContext *edc;
172 172
173 if (! gcry_check_version ("1.6.0")) 173 if (!gcry_check_version("1.6.0"))
174 { 174 {
175 fprintf (stderr, 175 fprintf(stderr,
176 _ 176 _
177 ("libgcrypt has not the expected version (version %s is required).\n"), 177 ("libgcrypt has not the expected version (version %s is required).\n"),
178 "1.6.0"); 178 "1.6.0");
179 return 0; 179 return 0;
180 } 180 }
181 if (getenv ("GNUNET_GCRYPT_DEBUG")) 181 if (getenv("GNUNET_GCRYPT_DEBUG"))
182 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); 182 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
183 GNUNET_log_setup ("test-crypto-ecc-dlog", 183 GNUNET_log_setup("test-crypto-ecc-dlog",
184 "WARNING", 184 "WARNING",
185 NULL); 185 NULL);
186 edc = GNUNET_CRYPTO_ecc_dlog_prepare (MAX_FACT, 186 edc = GNUNET_CRYPTO_ecc_dlog_prepare(MAX_FACT,
187 MAX_MEM); 187 MAX_MEM);
188 test_dlog (edc); 188 test_dlog(edc);
189 test_math (edc); 189 test_math(edc);
190 GNUNET_CRYPTO_ecc_dlog_release (edc); 190 GNUNET_CRYPTO_ecc_dlog_release(edc);
191 return 0; 191 return 0;
192} 192}
193 193
diff --git a/src/util/test_crypto_ecdh_eddsa.c b/src/util/test_crypto_ecdh_eddsa.c
index 00f85033e..5e2d930bc 100644
--- a/src/util/test_crypto_ecdh_eddsa.c
+++ b/src/util/test_crypto_ecdh_eddsa.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_ecdh_eddsa.c 22 * @file util/test_crypto_ecdh_eddsa.c
23 * @brief testcase for ECC DH key exchange with EdDSA private keys. 23 * @brief testcase for ECC DH key exchange with EdDSA private keys.
@@ -39,56 +39,56 @@ test_ecdh()
39 struct GNUNET_HashCode dh[2]; 39 struct GNUNET_HashCode dh[2];
40 40
41 /* Generate keys */ 41 /* Generate keys */
42 priv_dsa = GNUNET_CRYPTO_eddsa_key_create (); 42 priv_dsa = GNUNET_CRYPTO_eddsa_key_create();
43 GNUNET_CRYPTO_eddsa_key_get_public (priv_dsa, 43 GNUNET_CRYPTO_eddsa_key_get_public(priv_dsa,
44 &id1); 44 &id1);
45 for (unsigned int j=0;j<4;j++) 45 for (unsigned int j = 0; j < 4; j++)
46 { 46 {
47 fprintf (stderr, ","); 47 fprintf(stderr, ",");
48 priv_ecdh = GNUNET_CRYPTO_ecdhe_key_create (); 48 priv_ecdh = GNUNET_CRYPTO_ecdhe_key_create();
49 /* Extract public keys */ 49 /* Extract public keys */
50 GNUNET_CRYPTO_ecdhe_key_get_public (priv_ecdh, 50 GNUNET_CRYPTO_ecdhe_key_get_public(priv_ecdh,
51 &id2); 51 &id2);
52 /* Do ECDH */ 52 /* Do ECDH */
53 GNUNET_assert (GNUNET_OK == 53 GNUNET_assert(GNUNET_OK ==
54 GNUNET_CRYPTO_eddsa_ecdh (priv_dsa, 54 GNUNET_CRYPTO_eddsa_ecdh(priv_dsa,
55 &id2, 55 &id2,
56 &dh[0])); 56 &dh[0]));
57 GNUNET_assert (GNUNET_OK == 57 GNUNET_assert(GNUNET_OK ==
58 GNUNET_CRYPTO_ecdh_eddsa (priv_ecdh, 58 GNUNET_CRYPTO_ecdh_eddsa(priv_ecdh,
59 &id1, 59 &id1,
60 &dh[1])); 60 &dh[1]));
61 /* Check that both DH results are equal. */ 61 /* Check that both DH results are equal. */
62 GNUNET_assert (0 == memcmp (&dh[0], 62 GNUNET_assert(0 == memcmp(&dh[0],
63 &dh[1], 63 &dh[1],
64 sizeof (struct GNUNET_HashCode))); 64 sizeof(struct GNUNET_HashCode)));
65 GNUNET_free (priv_ecdh); 65 GNUNET_free(priv_ecdh);
66 } 66 }
67 GNUNET_free (priv_dsa); 67 GNUNET_free(priv_dsa);
68 return 0; 68 return 0;
69} 69}
70 70
71 71
72int 72int
73main (int argc, char *argv[]) 73main(int argc, char *argv[])
74{ 74{
75 if (! gcry_check_version ("1.6.0")) 75 if (!gcry_check_version("1.6.0"))
76 { 76 {
77 fprintf (stderr, 77 fprintf(stderr,
78 _("libgcrypt has not the expected version (version %s is required).\n"), 78 _("libgcrypt has not the expected version (version %s is required).\n"),
79 "1.6.0"); 79 "1.6.0");
80 return 0; 80 return 0;
81 } 81 }
82 if (getenv ("GNUNET_GCRYPT_DEBUG")) 82 if (getenv("GNUNET_GCRYPT_DEBUG"))
83 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u, 0); 83 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
84 GNUNET_log_setup ("test-crypto-ecdh-eddsa", "WARNING", NULL); 84 GNUNET_log_setup("test-crypto-ecdh-eddsa", "WARNING", NULL);
85 for (unsigned int i=0;i<4;i++) 85 for (unsigned int i = 0; i < 4; i++)
86 { 86 {
87 fprintf (stderr, 87 fprintf(stderr,
88 "."); 88 ".");
89 if (0 != test_ecdh()) 89 if (0 != test_ecdh())
90 return 1; 90 return 1;
91 } 91 }
92 return 0; 92 return 0;
93} 93}
94 94
diff --git a/src/util/test_crypto_ecdhe.c b/src/util/test_crypto_ecdhe.c
index 71fe9b570..d833abc1d 100644
--- a/src/util/test_crypto_ecdhe.c
+++ b/src/util/test_crypto_ecdhe.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_ecdhe.c 22 * @file util/test_crypto_ecdhe.c
23 * @brief testcase for ECC ECDHE public key crypto 23 * @brief testcase for ECC ECDHE public key crypto
@@ -29,7 +29,7 @@
29 29
30 30
31int 31int
32main (int argc, char *argv[]) 32main(int argc, char *argv[])
33{ 33{
34 struct GNUNET_CRYPTO_EcdhePrivateKey *priv1; 34 struct GNUNET_CRYPTO_EcdhePrivateKey *priv1;
35 struct GNUNET_CRYPTO_EcdhePrivateKey *priv2; 35 struct GNUNET_CRYPTO_EcdhePrivateKey *priv2;
@@ -38,33 +38,33 @@ main (int argc, char *argv[])
38 struct GNUNET_HashCode ecdh1; 38 struct GNUNET_HashCode ecdh1;
39 struct GNUNET_HashCode ecdh2; 39 struct GNUNET_HashCode ecdh2;
40 40
41 if (! gcry_check_version ("1.6.0")) 41 if (!gcry_check_version("1.6.0"))
42 { 42 {
43 fprintf (stderr, 43 fprintf(stderr,
44 _ 44 _
45 ("libgcrypt has not the expected version (version %s is required).\n"), 45 ("libgcrypt has not the expected version (version %s is required).\n"),
46 "1.6.0"); 46 "1.6.0");
47 return 0; 47 return 0;
48 } 48 }
49 if (getenv ("GNUNET_GCRYPT_DEBUG")) 49 if (getenv("GNUNET_GCRYPT_DEBUG"))
50 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); 50 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
51 GNUNET_log_setup ("test-crypto-ecdhe", "WARNING", NULL); 51 GNUNET_log_setup("test-crypto-ecdhe", "WARNING", NULL);
52 52
53 for (unsigned int i=0;i<100;i++) 53 for (unsigned int i = 0; i < 100; i++)
54 { 54 {
55 fprintf (stderr, 55 fprintf(stderr,
56 "."); 56 ".");
57 priv1 = GNUNET_CRYPTO_ecdhe_key_create (); 57 priv1 = GNUNET_CRYPTO_ecdhe_key_create();
58 priv2 = GNUNET_CRYPTO_ecdhe_key_create (); 58 priv2 = GNUNET_CRYPTO_ecdhe_key_create();
59 GNUNET_CRYPTO_ecdhe_key_get_public (priv1, &pub1); 59 GNUNET_CRYPTO_ecdhe_key_get_public(priv1, &pub1);
60 GNUNET_CRYPTO_ecdhe_key_get_public (priv2, &pub2); 60 GNUNET_CRYPTO_ecdhe_key_get_public(priv2, &pub2);
61 GNUNET_CRYPTO_ecc_ecdh (priv1, &pub2, &ecdh1); 61 GNUNET_CRYPTO_ecc_ecdh(priv1, &pub2, &ecdh1);
62 GNUNET_CRYPTO_ecc_ecdh (priv2, &pub1, &ecdh2); 62 GNUNET_CRYPTO_ecc_ecdh(priv2, &pub1, &ecdh2);
63 GNUNET_assert (0 == memcmp (&ecdh1, &ecdh2, 63 GNUNET_assert(0 == memcmp(&ecdh1, &ecdh2,
64 sizeof (struct GNUNET_HashCode))); 64 sizeof(struct GNUNET_HashCode)));
65 GNUNET_free (priv1); 65 GNUNET_free(priv1);
66 GNUNET_free (priv2); 66 GNUNET_free(priv2);
67 } 67 }
68 return 0; 68 return 0;
69} 69}
70 70
diff --git a/src/util/test_crypto_ecdsa.c b/src/util/test_crypto_ecdsa.c
index 00cc72af4..797d61285 100644
--- a/src/util/test_crypto_ecdsa.c
+++ b/src/util/test_crypto_ecdsa.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_ecdsa.c 22 * @file util/test_crypto_ecdsa.c
23 * @brief testcase for ECC ECDSA public key crypto 23 * @brief testcase for ECC ECDSA public key crypto
@@ -37,7 +37,7 @@ static struct GNUNET_CRYPTO_EcdsaPrivateKey *key;
37 37
38 38
39static int 39static int
40testSignVerify () 40testSignVerify()
41{ 41{
42 struct GNUNET_CRYPTO_EcdsaSignature sig; 42 struct GNUNET_CRYPTO_EcdsaSignature sig;
43 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 43 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
@@ -46,48 +46,48 @@ testSignVerify ()
46 struct GNUNET_TIME_Absolute start; 46 struct GNUNET_TIME_Absolute start;
47 int ok = GNUNET_OK; 47 int ok = GNUNET_OK;
48 48
49 fprintf (stderr, "%s", "W"); 49 fprintf(stderr, "%s", "W");
50 GNUNET_CRYPTO_ecdsa_key_get_public (key, &pkey); 50 GNUNET_CRYPTO_ecdsa_key_get_public(key, &pkey);
51 start = GNUNET_TIME_absolute_get (); 51 start = GNUNET_TIME_absolute_get();
52 purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); 52 purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose));
53 purp.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TEST); 53 purp.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TEST);
54 54
55 for (i = 0; i < ITER; i++) 55 for (i = 0; i < ITER; i++)
56 {
57 fprintf (stderr, "%s", "."); fflush (stderr);
58 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign (key, &purp, &sig))
59 {
60 fprintf (stderr,
61 "%s",
62 "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n");
63 ok = GNUNET_SYSERR;
64 continue;
65 }
66 if (GNUNET_SYSERR ==
67 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_TEST, &purp, &sig,
68 &pkey))
69 {
70 printf ("GNUNET_CRYPTO_ecdsa_verify failed!\n");
71 ok = GNUNET_SYSERR;
72 continue;
73 }
74 if (GNUNET_SYSERR !=
75 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
76 &purp, &sig, &pkey))
77 { 56 {
78 printf ("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n"); 57 fprintf(stderr, "%s", "."); fflush(stderr);
79 ok = GNUNET_SYSERR; 58 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign(key, &purp, &sig))
80 continue; 59 {
60 fprintf(stderr,
61 "%s",
62 "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n");
63 ok = GNUNET_SYSERR;
64 continue;
65 }
66 if (GNUNET_SYSERR ==
67 GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_TEST, &purp, &sig,
68 &pkey))
69 {
70 printf("GNUNET_CRYPTO_ecdsa_verify failed!\n");
71 ok = GNUNET_SYSERR;
72 continue;
73 }
74 if (GNUNET_SYSERR !=
75 GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
76 &purp, &sig, &pkey))
77 {
78 printf("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n");
79 ok = GNUNET_SYSERR;
80 continue;
81 }
81 } 82 }
82 } 83 printf("%d ECDSA sign/verify operations %s\n", ITER,
83 printf ("%d ECDSA sign/verify operations %s\n", ITER, 84 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES));
84 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES));
85 return ok; 85 return ok;
86} 86}
87 87
88 88
89static int 89static int
90testDeriveSignVerify () 90testDeriveSignVerify()
91{ 91{
92 struct GNUNET_CRYPTO_EcdsaSignature sig; 92 struct GNUNET_CRYPTO_EcdsaSignature sig;
93 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 93 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
@@ -95,52 +95,52 @@ testDeriveSignVerify ()
95 struct GNUNET_CRYPTO_EcdsaPublicKey pkey; 95 struct GNUNET_CRYPTO_EcdsaPublicKey pkey;
96 struct GNUNET_CRYPTO_EcdsaPublicKey dpub; 96 struct GNUNET_CRYPTO_EcdsaPublicKey dpub;
97 97
98 dpriv = GNUNET_CRYPTO_ecdsa_private_key_derive (key, "test-derive", "test-CTX"); 98 dpriv = GNUNET_CRYPTO_ecdsa_private_key_derive(key, "test-derive", "test-CTX");
99 GNUNET_CRYPTO_ecdsa_key_get_public (key, &pkey); 99 GNUNET_CRYPTO_ecdsa_key_get_public(key, &pkey);
100 GNUNET_CRYPTO_ecdsa_public_key_derive (&pkey, "test-derive", "test-CTX", &dpub); 100 GNUNET_CRYPTO_ecdsa_public_key_derive(&pkey, "test-derive", "test-CTX", &dpub);
101 purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); 101 purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose));
102 purp.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TEST); 102 purp.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TEST);
103 103
104 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign (dpriv, &purp, &sig)) 104 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign(dpriv, &purp, &sig))
105 { 105 {
106 fprintf (stderr, "%s", "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n"); 106 fprintf(stderr, "%s", "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n");
107 GNUNET_free (dpriv); 107 GNUNET_free(dpriv);
108 return GNUNET_SYSERR; 108 return GNUNET_SYSERR;
109 } 109 }
110 if (GNUNET_SYSERR == 110 if (GNUNET_SYSERR ==
111 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_TEST, 111 GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_TEST,
112 &purp, &sig, 112 &purp, &sig,
113 &dpub)) 113 &dpub))
114 { 114 {
115 printf ("GNUNET_CRYPTO_ecdsa_verify failed!\n"); 115 printf("GNUNET_CRYPTO_ecdsa_verify failed!\n");
116 GNUNET_free (dpriv); 116 GNUNET_free(dpriv);
117 return GNUNET_SYSERR; 117 return GNUNET_SYSERR;
118 } 118 }
119 if (GNUNET_SYSERR != 119 if (GNUNET_SYSERR !=
120 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_TEST, 120 GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_TEST,
121 &purp, &sig, 121 &purp, &sig,
122 &pkey)) 122 &pkey))
123 { 123 {
124 printf ("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n"); 124 printf("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n");
125 GNUNET_free (dpriv); 125 GNUNET_free(dpriv);
126 return GNUNET_SYSERR; 126 return GNUNET_SYSERR;
127 } 127 }
128 if (GNUNET_SYSERR != 128 if (GNUNET_SYSERR !=
129 GNUNET_CRYPTO_ecdsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN, 129 GNUNET_CRYPTO_ecdsa_verify(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
130 &purp, &sig, &dpub)) 130 &purp, &sig, &dpub))
131 { 131 {
132 printf ("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n"); 132 printf("GNUNET_CRYPTO_ecdsa_verify failed to fail!\n");
133 GNUNET_free (dpriv); 133 GNUNET_free(dpriv);
134 return GNUNET_SYSERR; 134 return GNUNET_SYSERR;
135 } 135 }
136 GNUNET_free (dpriv); 136 GNUNET_free(dpriv);
137 return GNUNET_OK; 137 return GNUNET_OK;
138} 138}
139 139
140 140
141#if PERF 141#if PERF
142static int 142static int
143testSignPerformance () 143testSignPerformance()
144{ 144{
145 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 145 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
146 struct GNUNET_CRYPTO_EcdsaSignature sig; 146 struct GNUNET_CRYPTO_EcdsaSignature sig;
@@ -149,93 +149,93 @@ testSignPerformance ()
149 struct GNUNET_TIME_Absolute start; 149 struct GNUNET_TIME_Absolute start;
150 int ok = GNUNET_OK; 150 int ok = GNUNET_OK;
151 151
152 purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); 152 purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose));
153 purp.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TEST); 153 purp.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TEST);
154 fprintf (stderr, "%s", "W"); 154 fprintf(stderr, "%s", "W");
155 GNUNET_CRYPTO_ecdsa_key_get_public (key, &pkey); 155 GNUNET_CRYPTO_ecdsa_key_get_public(key, &pkey);
156 start = GNUNET_TIME_absolute_get (); 156 start = GNUNET_TIME_absolute_get();
157 for (i = 0; i < ITER; i++) 157 for (i = 0; i < ITER; i++)
158 {
159 fprintf (stderr, "%s", "."); fflush (stderr);
160 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign (key, &purp, &sig))
161 { 158 {
162 fprintf (stderr, "%s", 159 fprintf(stderr, "%s", "."); fflush(stderr);
163 "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n"); 160 if (GNUNET_SYSERR == GNUNET_CRYPTO_ecdsa_sign(key, &purp, &sig))
164 ok = GNUNET_SYSERR; 161 {
165 continue; 162 fprintf(stderr, "%s",
163 "GNUNET_CRYPTO_ecdsa_sign returned SYSERR\n");
164 ok = GNUNET_SYSERR;
165 continue;
166 }
166 } 167 }
167 } 168 printf("%d ECC sign operations %s\n", ITER,
168 printf ("%d ECC sign operations %s\n", ITER, 169 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
169 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 170 GNUNET_YES));
170 GNUNET_YES));
171 return ok; 171 return ok;
172} 172}
173#endif 173#endif
174 174
175 175
176static void 176static void
177perf_keygen () 177perf_keygen()
178{ 178{
179 struct GNUNET_TIME_Absolute start; 179 struct GNUNET_TIME_Absolute start;
180 struct GNUNET_CRYPTO_EcdsaPrivateKey *pk; 180 struct GNUNET_CRYPTO_EcdsaPrivateKey *pk;
181 int i; 181 int i;
182 182
183 fprintf (stderr, "%s", "W"); 183 fprintf(stderr, "%s", "W");
184 start = GNUNET_TIME_absolute_get (); 184 start = GNUNET_TIME_absolute_get();
185 for (i=0;i<10;i++) 185 for (i = 0; i < 10; i++)
186 { 186 {
187 fprintf (stderr, "."); fflush (stderr); 187 fprintf(stderr, "."); fflush(stderr);
188 pk = GNUNET_CRYPTO_ecdsa_key_create (); 188 pk = GNUNET_CRYPTO_ecdsa_key_create();
189 GNUNET_free (pk); 189 GNUNET_free(pk);
190 } 190 }
191 for (;i<25;i++) 191 for (; i < 25; i++)
192 fprintf (stderr, "."); 192 fprintf(stderr, ".");
193 fflush (stderr); 193 fflush(stderr);
194 printf ("10 ECDSA keys created in %s\n", 194 printf("10 ECDSA keys created in %s\n",
195 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES)); 195 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES));
196} 196}
197 197
198 198
199int 199int
200main (int argc, char *argv[]) 200main(int argc, char *argv[])
201{ 201{
202 int failure_count = 0; 202 int failure_count = 0;
203 203
204 if (! gcry_check_version ("1.6.0")) 204 if (!gcry_check_version("1.6.0"))
205 { 205 {
206 fprintf (stderr, 206 fprintf(stderr,
207 _ 207 _
208 ("libgcrypt has not the expected version (version %s is required).\n"), 208 ("libgcrypt has not the expected version (version %s is required).\n"),
209 "1.6.0"); 209 "1.6.0");
210 return 0; 210 return 0;
211 } 211 }
212 if (getenv ("GNUNET_GCRYPT_DEBUG")) 212 if (getenv("GNUNET_GCRYPT_DEBUG"))
213 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); 213 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
214 GNUNET_log_setup ("test-crypto-ecc", "WARNING", NULL); 214 GNUNET_log_setup("test-crypto-ecc", "WARNING", NULL);
215 key = GNUNET_CRYPTO_ecdsa_key_create (); 215 key = GNUNET_CRYPTO_ecdsa_key_create();
216 if (GNUNET_OK != testDeriveSignVerify ()) 216 if (GNUNET_OK != testDeriveSignVerify())
217 { 217 {
218 failure_count++; 218 failure_count++;
219 fprintf (stderr, 219 fprintf(stderr,
220 "\n\n%d TESTS FAILED!\n\n", failure_count); 220 "\n\n%d TESTS FAILED!\n\n", failure_count);
221 return -1; 221 return -1;
222 } 222 }
223#if PERF 223#if PERF
224 if (GNUNET_OK != testSignPerformance ()) 224 if (GNUNET_OK != testSignPerformance())
225 failure_count++; 225 failure_count++;
226#endif 226#endif
227 if (GNUNET_OK != testSignVerify ()) 227 if (GNUNET_OK != testSignVerify())
228 failure_count++; 228 failure_count++;
229 GNUNET_free (key); 229 GNUNET_free(key);
230 perf_keygen (); 230 perf_keygen();
231 231
232 if (0 != failure_count) 232 if (0 != failure_count)
233 { 233 {
234 fprintf (stderr, 234 fprintf(stderr,
235 "\n\n%d TESTS FAILED!\n\n", 235 "\n\n%d TESTS FAILED!\n\n",
236 failure_count); 236 failure_count);
237 return -1; 237 return -1;
238 } 238 }
239 return 0; 239 return 0;
240} 240}
241 241
diff --git a/src/util/test_crypto_eddsa.c b/src/util/test_crypto_eddsa.c
index acb5fbdf5..2119e3080 100644
--- a/src/util/test_crypto_eddsa.c
+++ b/src/util/test_crypto_eddsa.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_eddsa.c 22 * @file util/test_crypto_eddsa.c
23 * @brief testcase for ECC public key crypto 23 * @brief testcase for ECC public key crypto
@@ -39,7 +39,7 @@ static struct GNUNET_CRYPTO_EddsaPrivateKey *key;
39 39
40 40
41static int 41static int
42testSignVerify () 42testSignVerify()
43{ 43{
44 struct GNUNET_CRYPTO_EddsaSignature sig; 44 struct GNUNET_CRYPTO_EddsaSignature sig;
45 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 45 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
@@ -48,47 +48,47 @@ testSignVerify ()
48 struct GNUNET_TIME_Absolute start; 48 struct GNUNET_TIME_Absolute start;
49 int ok = GNUNET_OK; 49 int ok = GNUNET_OK;
50 50
51 fprintf (stderr, "%s", "W"); 51 fprintf(stderr, "%s", "W");
52 GNUNET_CRYPTO_eddsa_key_get_public (key, &pkey); 52 GNUNET_CRYPTO_eddsa_key_get_public(key, &pkey);
53 start = GNUNET_TIME_absolute_get (); 53 start = GNUNET_TIME_absolute_get();
54 purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); 54 purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose));
55 purp.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TEST); 55 purp.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TEST);
56 56
57 for (i = 0; i < ITER; i++) 57 for (i = 0; i < ITER; i++)
58 {
59 fprintf (stderr, "%s", "."); fflush (stderr);
60 if (GNUNET_SYSERR == GNUNET_CRYPTO_eddsa_sign (key, &purp, &sig))
61 {
62 fprintf (stderr, "%s", "GNUNET_CRYPTO_eddsa_sign returned SYSERR\n");
63 ok = GNUNET_SYSERR;
64 continue;
65 }
66 if (GNUNET_SYSERR ==
67 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TEST, &purp, &sig,
68 &pkey))
69 {
70 printf ("GNUNET_CRYPTO_eddsa_verify failed!\n");
71 ok = GNUNET_SYSERR;
72 continue;
73 }
74 if (GNUNET_SYSERR !=
75 GNUNET_CRYPTO_eddsa_verify (GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
76 &purp, &sig, &pkey))
77 { 58 {
78 printf ("GNUNET_CRYPTO_eddsa_verify failed to fail!\n"); 59 fprintf(stderr, "%s", "."); fflush(stderr);
79 ok = GNUNET_SYSERR; 60 if (GNUNET_SYSERR == GNUNET_CRYPTO_eddsa_sign(key, &purp, &sig))
80 continue; 61 {
62 fprintf(stderr, "%s", "GNUNET_CRYPTO_eddsa_sign returned SYSERR\n");
63 ok = GNUNET_SYSERR;
64 continue;
65 }
66 if (GNUNET_SYSERR ==
67 GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_TEST, &purp, &sig,
68 &pkey))
69 {
70 printf("GNUNET_CRYPTO_eddsa_verify failed!\n");
71 ok = GNUNET_SYSERR;
72 continue;
73 }
74 if (GNUNET_SYSERR !=
75 GNUNET_CRYPTO_eddsa_verify(GNUNET_SIGNATURE_PURPOSE_TRANSPORT_PONG_OWN,
76 &purp, &sig, &pkey))
77 {
78 printf("GNUNET_CRYPTO_eddsa_verify failed to fail!\n");
79 ok = GNUNET_SYSERR;
80 continue;
81 }
81 } 82 }
82 } 83 printf("%d EdDSA sign/verify operations %s\n", ITER,
83 printf ("%d EdDSA sign/verify operations %s\n", ITER, 84 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES));
84 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES));
85 return ok; 85 return ok;
86} 86}
87 87
88 88
89#if PERF 89#if PERF
90static int 90static int
91testSignPerformance () 91testSignPerformance()
92{ 92{
93 struct GNUNET_CRYPTO_EccSignaturePurpose purp; 93 struct GNUNET_CRYPTO_EccSignaturePurpose purp;
94 struct GNUNET_CRYPTO_EddsaSignature sig; 94 struct GNUNET_CRYPTO_EddsaSignature sig;
@@ -97,112 +97,112 @@ testSignPerformance ()
97 struct GNUNET_TIME_Absolute start; 97 struct GNUNET_TIME_Absolute start;
98 int ok = GNUNET_OK; 98 int ok = GNUNET_OK;
99 99
100 purp.size = htonl (sizeof (struct GNUNET_CRYPTO_EccSignaturePurpose)); 100 purp.size = htonl(sizeof(struct GNUNET_CRYPTO_EccSignaturePurpose));
101 purp.purpose = htonl (GNUNET_SIGNATURE_PURPOSE_TEST); 101 purp.purpose = htonl(GNUNET_SIGNATURE_PURPOSE_TEST);
102 fprintf (stderr, "%s", "W"); 102 fprintf(stderr, "%s", "W");
103 GNUNET_CRYPTO_eddsa_key_get_public (key, &pkey); 103 GNUNET_CRYPTO_eddsa_key_get_public(key, &pkey);
104 start = GNUNET_TIME_absolute_get (); 104 start = GNUNET_TIME_absolute_get();
105 for (i = 0; i < ITER; i++) 105 for (i = 0; i < ITER; i++)
106 {
107 fprintf (stderr, "%s", "."); fflush (stderr);
108 if (GNUNET_SYSERR == GNUNET_CRYPTO_eddsa_sign (key, &purp, &sig))
109 { 106 {
110 fprintf (stderr, "%s", "GNUNET_CRYPTO_eddsa_sign returned SYSERR\n"); 107 fprintf(stderr, "%s", "."); fflush(stderr);
111 ok = GNUNET_SYSERR; 108 if (GNUNET_SYSERR == GNUNET_CRYPTO_eddsa_sign(key, &purp, &sig))
112 continue; 109 {
110 fprintf(stderr, "%s", "GNUNET_CRYPTO_eddsa_sign returned SYSERR\n");
111 ok = GNUNET_SYSERR;
112 continue;
113 }
113 } 114 }
114 } 115 printf("%d EdDSA sign operations %s\n", ITER,
115 printf ("%d EdDSA sign operations %s\n", ITER, 116 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start),
116 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), 117 GNUNET_YES));
117 GNUNET_YES));
118 return ok; 118 return ok;
119} 119}
120#endif 120#endif
121 121
122 122
123static int 123static int
124testCreateFromFile () 124testCreateFromFile()
125{ 125{
126 struct GNUNET_CRYPTO_EddsaPublicKey p1; 126 struct GNUNET_CRYPTO_EddsaPublicKey p1;
127 struct GNUNET_CRYPTO_EddsaPublicKey p2; 127 struct GNUNET_CRYPTO_EddsaPublicKey p2;
128 128
129 key = GNUNET_CRYPTO_eddsa_key_create_from_file (KEYFILE); 129 key = GNUNET_CRYPTO_eddsa_key_create_from_file(KEYFILE);
130 GNUNET_assert (NULL != key); 130 GNUNET_assert(NULL != key);
131 GNUNET_CRYPTO_eddsa_key_get_public (key, &p1); 131 GNUNET_CRYPTO_eddsa_key_get_public(key, &p1);
132 GNUNET_free (key); 132 GNUNET_free(key);
133 key = GNUNET_CRYPTO_eddsa_key_create_from_file (KEYFILE); 133 key = GNUNET_CRYPTO_eddsa_key_create_from_file(KEYFILE);
134 GNUNET_assert (NULL != key); 134 GNUNET_assert(NULL != key);
135 GNUNET_CRYPTO_eddsa_key_get_public (key, &p2); 135 GNUNET_CRYPTO_eddsa_key_get_public(key, &p2);
136 GNUNET_assert (0 == memcmp (&p1, &p2, sizeof (p1))); 136 GNUNET_assert(0 == memcmp(&p1, &p2, sizeof(p1)));
137 GNUNET_free (key); 137 GNUNET_free(key);
138 GNUNET_assert (0 == unlink (KEYFILE)); 138 GNUNET_assert(0 == unlink(KEYFILE));
139 key = GNUNET_CRYPTO_eddsa_key_create_from_file (KEYFILE); 139 key = GNUNET_CRYPTO_eddsa_key_create_from_file(KEYFILE);
140 GNUNET_assert (NULL != key); 140 GNUNET_assert(NULL != key);
141 GNUNET_CRYPTO_eddsa_key_get_public (key, &p2); 141 GNUNET_CRYPTO_eddsa_key_get_public(key, &p2);
142 GNUNET_assert (0 != memcmp (&p1, &p2, sizeof (p1))); 142 GNUNET_assert(0 != memcmp(&p1, &p2, sizeof(p1)));
143 GNUNET_free (key); 143 GNUNET_free(key);
144 return GNUNET_OK; 144 return GNUNET_OK;
145} 145}
146 146
147 147
148static void 148static void
149perf_keygen () 149perf_keygen()
150{ 150{
151 struct GNUNET_TIME_Absolute start; 151 struct GNUNET_TIME_Absolute start;
152 struct GNUNET_CRYPTO_EddsaPrivateKey *pk; 152 struct GNUNET_CRYPTO_EddsaPrivateKey *pk;
153 int i; 153 int i;
154 154
155 fprintf (stderr, "%s", "W"); 155 fprintf(stderr, "%s", "W");
156 start = GNUNET_TIME_absolute_get (); 156 start = GNUNET_TIME_absolute_get();
157 for (i=0;i<10;i++) 157 for (i = 0; i < 10; i++)
158 { 158 {
159 fprintf (stderr, "."); fflush (stderr); 159 fprintf(stderr, "."); fflush(stderr);
160 pk = GNUNET_CRYPTO_eddsa_key_create (); 160 pk = GNUNET_CRYPTO_eddsa_key_create();
161 GNUNET_free (pk); 161 GNUNET_free(pk);
162 } 162 }
163 for (;i<25;i++) 163 for (; i < 25; i++)
164 fprintf (stderr, "."); 164 fprintf(stderr, ".");
165 fflush (stderr); 165 fflush(stderr);
166 printf ("10 EdDSA keys created in %s\n", 166 printf("10 EdDSA keys created in %s\n",
167 GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_absolute_get_duration (start), GNUNET_YES)); 167 GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_absolute_get_duration(start), GNUNET_YES));
168} 168}
169 169
170 170
171int 171int
172main (int argc, char *argv[]) 172main(int argc, char *argv[])
173{ 173{
174 int failure_count = 0; 174 int failure_count = 0;
175 175
176 if (! gcry_check_version ("1.6.0")) 176 if (!gcry_check_version("1.6.0"))
177 { 177 {
178 fprintf (stderr, 178 fprintf(stderr,
179 _("libgcrypt has not the expected version (version %s is required).\n"), 179 _("libgcrypt has not the expected version (version %s is required).\n"),
180 "1.6.0"); 180 "1.6.0");
181 return 0; 181 return 0;
182 } 182 }
183 if (getenv ("GNUNET_GCRYPT_DEBUG")) 183 if (getenv("GNUNET_GCRYPT_DEBUG"))
184 gcry_control (GCRYCTL_SET_DEBUG_FLAGS, 1u , 0); 184 gcry_control(GCRYCTL_SET_DEBUG_FLAGS, 1u, 0);
185 GNUNET_log_setup ("test-crypto-eddsa", "WARNING", NULL); 185 GNUNET_log_setup("test-crypto-eddsa", "WARNING", NULL);
186 key = GNUNET_CRYPTO_eddsa_key_create (); 186 key = GNUNET_CRYPTO_eddsa_key_create();
187#if PERF 187#if PERF
188 if (GNUNET_OK != testSignPerformance ()) 188 if (GNUNET_OK != testSignPerformance())
189 failure_count++; 189 failure_count++;
190#endif 190#endif
191 if (GNUNET_OK != testSignVerify ()) 191 if (GNUNET_OK != testSignVerify())
192 failure_count++; 192 failure_count++;
193 GNUNET_free (key); 193 GNUNET_free(key);
194 if (GNUNET_OK != testCreateFromFile ()) 194 if (GNUNET_OK != testCreateFromFile())
195 failure_count++; 195 failure_count++;
196 GNUNET_assert (0 == unlink (KEYFILE)); 196 GNUNET_assert(0 == unlink(KEYFILE));
197 perf_keygen (); 197 perf_keygen();
198 198
199 if (0 != failure_count) 199 if (0 != failure_count)
200 { 200 {
201 fprintf (stderr, 201 fprintf(stderr,
202 "\n\n%d TESTS FAILED!\n\n", 202 "\n\n%d TESTS FAILED!\n\n",
203 failure_count); 203 failure_count);
204 return -1; 204 return -1;
205 } 205 }
206 return 0; 206 return 0;
207} 207}
208 208
diff --git a/src/util/test_crypto_hash.c b/src/util/test_crypto_hash.c
index e08348e53..0e8246595 100644
--- a/src/util/test_crypto_hash.c
+++ b/src/util/test_crypto_hash.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
@@ -31,37 +31,37 @@ static char block[65536];
31#define FILENAME "testblock.dat" 31#define FILENAME "testblock.dat"
32 32
33static int 33static int
34test (int number) 34test(int number)
35{ 35{
36 struct GNUNET_HashCode h1; 36 struct GNUNET_HashCode h1;
37 struct GNUNET_HashCode h2; 37 struct GNUNET_HashCode h2;
38 struct GNUNET_CRYPTO_HashAsciiEncoded enc; 38 struct GNUNET_CRYPTO_HashAsciiEncoded enc;
39 39
40 memset (&h1, number, sizeof (struct GNUNET_HashCode)); 40 memset(&h1, number, sizeof(struct GNUNET_HashCode));
41 GNUNET_CRYPTO_hash_to_enc (&h1, &enc); 41 GNUNET_CRYPTO_hash_to_enc(&h1, &enc);
42 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string ((char *) &enc, &h2)) 42 if (GNUNET_OK != GNUNET_CRYPTO_hash_from_string((char *)&enc, &h2))
43 { 43 {
44 printf ("enc2hash failed!\n"); 44 printf("enc2hash failed!\n");
45 return 1; 45 return 1;
46 } 46 }
47 if (0 != memcmp (&h1, &h2, sizeof (struct GNUNET_HashCode))) 47 if (0 != memcmp(&h1, &h2, sizeof(struct GNUNET_HashCode)))
48 return 1; 48 return 1;
49 return 0; 49 return 0;
50} 50}
51 51
52static int 52static int
53testEncoding () 53testEncoding()
54{ 54{
55 int i; 55 int i;
56 56
57 for (i = 0; i < 255; i++) 57 for (i = 0; i < 255; i++)
58 if (0 != test (i)) 58 if (0 != test(i))
59 return 1; 59 return 1;
60 return 0; 60 return 0;
61} 61}
62 62
63static int 63static int
64testArithmetic () 64testArithmetic()
65{ 65{
66 struct GNUNET_HashCode h1; 66 struct GNUNET_HashCode h1;
67 struct GNUNET_HashCode h2; 67 struct GNUNET_HashCode h2;
@@ -70,43 +70,43 @@ testArithmetic ()
70 struct GNUNET_CRYPTO_SymmetricSessionKey skey; 70 struct GNUNET_CRYPTO_SymmetricSessionKey skey;
71 struct GNUNET_CRYPTO_SymmetricInitializationVector iv; 71 struct GNUNET_CRYPTO_SymmetricInitializationVector iv;
72 72
73 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &h1); 73 GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, &h1);
74 GNUNET_CRYPTO_hash_create_random (GNUNET_CRYPTO_QUALITY_WEAK, &h2); 74 GNUNET_CRYPTO_hash_create_random(GNUNET_CRYPTO_QUALITY_WEAK, &h2);
75 if (GNUNET_CRYPTO_hash_distance_u32 (&h1, &h2) != 75 if (GNUNET_CRYPTO_hash_distance_u32(&h1, &h2) !=
76 GNUNET_CRYPTO_hash_distance_u32 (&h2, &h1)) 76 GNUNET_CRYPTO_hash_distance_u32(&h2, &h1))
77 return 1; 77 return 1;
78 GNUNET_CRYPTO_hash_difference (&h1, &h2, &d); 78 GNUNET_CRYPTO_hash_difference(&h1, &h2, &d);
79 GNUNET_CRYPTO_hash_sum (&h1, &d, &s); 79 GNUNET_CRYPTO_hash_sum(&h1, &d, &s);
80 if (0 != GNUNET_CRYPTO_hash_cmp (&s, &h2)) 80 if (0 != GNUNET_CRYPTO_hash_cmp(&s, &h2))
81 return 1; 81 return 1;
82 GNUNET_CRYPTO_hash_xor (&h1, &h2, &d); 82 GNUNET_CRYPTO_hash_xor(&h1, &h2, &d);
83 GNUNET_CRYPTO_hash_xor (&h1, &d, &s); 83 GNUNET_CRYPTO_hash_xor(&h1, &d, &s);
84 if (0 != GNUNET_CRYPTO_hash_cmp (&s, &h2)) 84 if (0 != GNUNET_CRYPTO_hash_cmp(&s, &h2))
85 return 1; 85 return 1;
86 if (0 != GNUNET_CRYPTO_hash_xorcmp (&s, &h2, &h1)) 86 if (0 != GNUNET_CRYPTO_hash_xorcmp(&s, &h2, &h1))
87 return 1; 87 return 1;
88 if (-1 != GNUNET_CRYPTO_hash_xorcmp (&h1, &h2, &h1)) 88 if (-1 != GNUNET_CRYPTO_hash_xorcmp(&h1, &h2, &h1))
89 return 1; 89 return 1;
90 if (1 != GNUNET_CRYPTO_hash_xorcmp (&h1, &h2, &h2)) 90 if (1 != GNUNET_CRYPTO_hash_xorcmp(&h1, &h2, &h2))
91 return 1; 91 return 1;
92 memset (&d, 0xF0, sizeof (d)); 92 memset(&d, 0xF0, sizeof(d));
93 if (0 != GNUNET_CRYPTO_hash_get_bit (&d, 3)) 93 if (0 != GNUNET_CRYPTO_hash_get_bit(&d, 3))
94 return 1; 94 return 1;
95 if (1 != GNUNET_CRYPTO_hash_get_bit (&d, 6)) 95 if (1 != GNUNET_CRYPTO_hash_get_bit(&d, 6))
96 return 1; 96 return 1;
97 memset (&d, 0, sizeof (d)); 97 memset(&d, 0, sizeof(d));
98 GNUNET_CRYPTO_hash_to_aes_key (&d, &skey, &iv); 98 GNUNET_CRYPTO_hash_to_aes_key(&d, &skey, &iv);
99 return 0; 99 return 0;
100} 100}
101 101
102static void 102static void
103finished_task (void *cls, const struct GNUNET_HashCode * res) 103finished_task(void *cls, const struct GNUNET_HashCode * res)
104{ 104{
105 int *ret = cls; 105 int *ret = cls;
106 struct GNUNET_HashCode want; 106 struct GNUNET_HashCode want;
107 107
108 GNUNET_CRYPTO_hash (block, sizeof (block), &want); 108 GNUNET_CRYPTO_hash(block, sizeof(block), &want);
109 if (0 != memcmp (res, &want, sizeof (want))) 109 if (0 != memcmp(res, &want, sizeof(want)))
110 *ret = 2; 110 *ret = 2;
111 else 111 else
112 *ret = 0; 112 *ret = 0;
@@ -114,43 +114,43 @@ finished_task (void *cls, const struct GNUNET_HashCode * res)
114 114
115 115
116static void 116static void
117file_hasher (void *cls) 117file_hasher(void *cls)
118{ 118{
119 GNUNET_assert (NULL != 119 GNUNET_assert(NULL !=
120 GNUNET_CRYPTO_hash_file (GNUNET_SCHEDULER_PRIORITY_DEFAULT, 120 GNUNET_CRYPTO_hash_file(GNUNET_SCHEDULER_PRIORITY_DEFAULT,
121 FILENAME, 1024, &finished_task, cls)); 121 FILENAME, 1024, &finished_task, cls));
122} 122}
123 123
124 124
125static int 125static int
126testFileHash () 126testFileHash()
127{ 127{
128 int ret; 128 int ret;
129 FILE *f; 129 FILE *f;
130 130
131 memset (block, 42, sizeof (block) / 2); 131 memset(block, 42, sizeof(block) / 2);
132 memset (&block[sizeof (block) / 2], 43, sizeof (block) / 2); 132 memset(&block[sizeof(block) / 2], 43, sizeof(block) / 2);
133 GNUNET_assert (NULL != (f = fopen (FILENAME, "w+"))); 133 GNUNET_assert(NULL != (f = fopen(FILENAME, "w+")));
134 GNUNET_break (sizeof (block) == fwrite (block, 1, sizeof (block), f)); 134 GNUNET_break(sizeof(block) == fwrite(block, 1, sizeof(block), f));
135 GNUNET_break (0 == fclose (f)); 135 GNUNET_break(0 == fclose(f));
136 ret = 1; 136 ret = 1;
137 GNUNET_SCHEDULER_run (&file_hasher, &ret); 137 GNUNET_SCHEDULER_run(&file_hasher, &ret);
138 GNUNET_break (0 == unlink (FILENAME)); 138 GNUNET_break(0 == unlink(FILENAME));
139 return ret; 139 return ret;
140} 140}
141 141
142 142
143int 143int
144main (int argc, char *argv[]) 144main(int argc, char *argv[])
145{ 145{
146 int failureCount = 0; 146 int failureCount = 0;
147 int i; 147 int i;
148 148
149 GNUNET_log_setup ("test-crypto-hash", "WARNING", NULL); 149 GNUNET_log_setup("test-crypto-hash", "WARNING", NULL);
150 for (i = 0; i < 10; i++) 150 for (i = 0; i < 10; i++)
151 failureCount += testEncoding (); 151 failureCount += testEncoding();
152 failureCount += testArithmetic (); 152 failureCount += testArithmetic();
153 failureCount += testFileHash (); 153 failureCount += testFileHash();
154 if (failureCount != 0) 154 if (failureCount != 0)
155 return 1; 155 return 1;
156 return 0; 156 return 0;
diff --git a/src/util/test_crypto_hash_context.c b/src/util/test_crypto_hash_context.c
index 847fe56ba..778b70eec 100644
--- a/src/util/test_crypto_hash_context.c
+++ b/src/util/test_crypto_hash_context.c
@@ -1,22 +1,22 @@
1/* 1/*
2 This file is part of GNUnet 2 This file is part of GNUnet
3 Copyright (C) 2014 GNUnet e.V. 3 Copyright (C) 2014 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_crypto_hash_context.c 21 * @file util/test_crypto_hash_context.c
22 * @brief test case for incremental hashing 22 * @brief test case for incremental hashing
@@ -34,15 +34,15 @@ int main()
34 struct GNUNET_HashCode hc2; 34 struct GNUNET_HashCode hc2;
35 struct GNUNET_HashContext *hctx; 35 struct GNUNET_HashContext *hctx;
36 36
37 memset (data, 42, LEN); 37 memset(data, 42, LEN);
38 38
39 hctx = GNUNET_CRYPTO_hash_context_start (); 39 hctx = GNUNET_CRYPTO_hash_context_start();
40 GNUNET_CRYPTO_hash_context_read (hctx, data, LEN); 40 GNUNET_CRYPTO_hash_context_read(hctx, data, LEN);
41 GNUNET_CRYPTO_hash_context_finish (hctx, &hc1); 41 GNUNET_CRYPTO_hash_context_finish(hctx, &hc1);
42 42
43 GNUNET_CRYPTO_hash (data, LEN, &hc2); 43 GNUNET_CRYPTO_hash(data, LEN, &hc2);
44 44
45 if (0 == memcmp (&hc1, &hc2, sizeof (struct GNUNET_HashCode))) 45 if (0 == memcmp(&hc1, &hc2, sizeof(struct GNUNET_HashCode)))
46 return 0; 46 return 0;
47 return 1; 47 return 1;
48} 48}
diff --git a/src/util/test_crypto_hkdf.c b/src/util/test_crypto_hkdf.c
index 752116194..d4829791d 100644
--- a/src/util/test_crypto_hkdf.c
+++ b/src/util/test_crypto_hkdf.c
@@ -18,7 +18,7 @@
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE. 20 THE SOFTWARE.
21*/ 21 */
22 22
23/** 23/**
24 * @file src/util/test_crypt_hkdf.c 24 * @file src/util/test_crypt_hkdf.c
@@ -33,319 +33,293 @@
33#include "gnunet_crypto_lib.h" 33#include "gnunet_crypto_lib.h"
34 34
35void 35void
36tc1 () 36tc1()
37{ 37{
38 unsigned char ikm[22] = 38 unsigned char ikm[22] =
39 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 39 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
40 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b 40 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
41 };
42 unsigned char salt[13] = 41 unsigned char salt[13] =
43 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 42 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
44 0x0a, 0x0b, 0x0c 43 0x0a, 0x0b, 0x0c };
45 };
46 unsigned char info[10] = 44 unsigned char info[10] =
47 { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; 45 { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
48 unsigned char okm[42] = 46 unsigned char okm[42] =
49 { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43, 47 { 0x3c, 0xb2, 0x5f, 0x25, 0xfa, 0xac, 0xd5, 0x7a, 0x90, 0x43,
50 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a, 48 0x4f, 0x64, 0xd0, 0x36, 0x2f, 0x2a, 0x2d, 0x2d, 0x0a, 0x90, 0xcf, 0x1a,
51 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00, 49 0x5a, 0x4c, 0x5d, 0xb0, 0x2d, 0x56, 0xec, 0xc4, 0xc5, 0xbf, 0x34, 0x00,
52 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 50 0x72, 0x08, 0xd5, 0xb8, 0x87, 0x18, 0x58, 0x65 };
53 };
54 unsigned char result[44]; 51 unsigned char result[44];
55 int l = 42; 52 int l = 42;
56 53
57 memset (result, 0, sizeof (result)); 54 memset(result, 0, sizeof(result));
58 GNUNET_assert (GNUNET_CRYPTO_hkdf 55 GNUNET_assert(GNUNET_CRYPTO_hkdf
59 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, salt, 56 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, salt,
60 sizeof (salt), ikm, sizeof (ikm), info, sizeof (info), 57 sizeof(salt), ikm, sizeof(ikm), info, sizeof(info),
61 NULL) == GNUNET_YES); 58 NULL) == GNUNET_YES);
62 GNUNET_assert (memcmp (result, okm, l) == 0); 59 GNUNET_assert(memcmp(result, okm, l) == 0);
63 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 60 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
64} 61}
65 62
66void 63void
67tc2 () 64tc2()
68{ 65{
69 unsigned char ikm[80] = 66 unsigned char ikm[80] =
70 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 67 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
71 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 68 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
72 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 69 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21,
73 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 70 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
74 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 71 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
75 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 72 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
76 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f 73 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f };
77 };
78 unsigned char salt[80] = 74 unsigned char salt[80] =
79 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 75 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
80 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 76 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
81 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 77 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81,
82 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 78 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
83 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 79 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
84 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 80 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5,
85 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf 81 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf };
86 };
87 unsigned char info[80] = 82 unsigned char info[80] =
88 { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 83 { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9,
89 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 84 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5,
90 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 85 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1,
91 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 86 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd,
92 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 87 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
93 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 88 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5,
94 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff 89 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
95 };
96 unsigned char okm[82] = 90 unsigned char okm[82] =
97 { 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7, 91 { 0xb1, 0x1e, 0x39, 0x8d, 0xc8, 0x03, 0x27, 0xa1, 0xc8, 0xe7,
98 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e, 92 0xf7, 0x8c, 0x59, 0x6a, 0x49, 0x34, 0x4f, 0x01, 0x2e, 0xda, 0x2d, 0x4e,
99 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04, 93 0xfa, 0xd8, 0xa0, 0x50, 0xcc, 0x4c, 0x19, 0xaf, 0xa9, 0x7c, 0x59, 0x04,
100 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59, 94 0x5a, 0x99, 0xca, 0xc7, 0x82, 0x72, 0x71, 0xcb, 0x41, 0xc6, 0x5e, 0x59,
101 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77, 95 0x0e, 0x09, 0xda, 0x32, 0x75, 0x60, 0x0c, 0x2f, 0x09, 0xb8, 0x36, 0x77,
102 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec, 96 0x93, 0xa9, 0xac, 0xa3, 0xdb, 0x71, 0xcc, 0x30, 0xc5, 0x81, 0x79, 0xec,
103 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87 97 0x3e, 0x87, 0xc1, 0x4c, 0x01, 0xd5, 0xc1, 0xf3, 0x43, 0x4f, 0x1d, 0x87 };
104 };
105 char result[84]; 98 char result[84];
106 int l = 82; 99 int l = 82;
107 100
108 memset (result, 0, sizeof (result)); 101 memset(result, 0, sizeof(result));
109 GNUNET_assert (GNUNET_CRYPTO_hkdf 102 GNUNET_assert(GNUNET_CRYPTO_hkdf
110 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, salt, 103 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, salt,
111 sizeof (salt), ikm, sizeof (ikm), info, sizeof (info), 104 sizeof(salt), ikm, sizeof(ikm), info, sizeof(info),
112 NULL) == GNUNET_YES); 105 NULL) == GNUNET_YES);
113 GNUNET_assert (memcmp (result, okm, l) == 0); 106 GNUNET_assert(memcmp(result, okm, l) == 0);
114 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 107 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
115} 108}
116 109
117void 110void
118tc3 () 111tc3()
119{ 112{
120 unsigned char ikm[22] = 113 unsigned char ikm[22] =
121 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 114 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
122 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b 115 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
123 };
124 unsigned char okm[42] = 116 unsigned char okm[42] =
125 { 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f, 117 { 0x8d, 0xa4, 0xe7, 0x75, 0xa5, 0x63, 0xc1, 0x8f, 0x71, 0x5f,
126 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1, 118 0x80, 0x2a, 0x06, 0x3c, 0x5a, 0x31, 0xb8, 0xa1, 0x1f, 0x5c, 0x5e, 0xe1,
127 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20, 119 0x87, 0x9e, 0xc3, 0x45, 0x4e, 0x5f, 0x3c, 0x73, 0x8d, 0x2d, 0x9d, 0x20,
128 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8 120 0x13, 0x95, 0xfa, 0xa4, 0xb6, 0x1a, 0x96, 0xc8 };
129 };
130 unsigned char result[44]; 121 unsigned char result[44];
131 int l = 42; 122 int l = 42;
132 123
133 memset (result, 0, sizeof (result)); 124 memset(result, 0, sizeof(result));
134 GNUNET_assert (GNUNET_CRYPTO_hkdf 125 GNUNET_assert(GNUNET_CRYPTO_hkdf
135 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, NULL, 0, ikm, 126 (result, l, GCRY_MD_SHA256, GCRY_MD_SHA256, NULL, 0, ikm,
136 sizeof (ikm), NULL, 0, NULL) == GNUNET_YES); 127 sizeof(ikm), NULL, 0, NULL) == GNUNET_YES);
137 GNUNET_assert (memcmp (result, okm, l) == 0); 128 GNUNET_assert(memcmp(result, okm, l) == 0);
138 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 129 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
139} 130}
140 131
141void 132void
142tc4 () 133tc4()
143{ 134{
144 unsigned char ikm[11] = 135 unsigned char ikm[11] =
145 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 136 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
146 0x0b 137 0x0b };
147 };
148 unsigned char salt[13] = 138 unsigned char salt[13] =
149 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 139 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
150 0x0a, 0x0b, 0x0c 140 0x0a, 0x0b, 0x0c };
151 };
152 unsigned char info[10] = 141 unsigned char info[10] =
153 { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 }; 142 { 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9 };
154 unsigned char okm[42] = 143 unsigned char okm[42] =
155 { 0x08, 0x5a, 0x01, 0xea, 0x1b, 0x10, 0xf3, 0x69, 0x33, 0x06, 144 { 0x08, 0x5a, 0x01, 0xea, 0x1b, 0x10, 0xf3, 0x69, 0x33, 0x06,
156 0x8b, 0x56, 0xef, 0xa5, 0xad, 0x81, 0xa4, 0xf1, 0x4b, 0x82, 0x2f, 0x5b, 145 0x8b, 0x56, 0xef, 0xa5, 0xad, 0x81, 0xa4, 0xf1, 0x4b, 0x82, 0x2f, 0x5b,
157 0x09, 0x15, 0x68, 0xa9, 0xcd, 0xd4, 0xf1, 0x55, 0xfd, 0xa2, 0xc2, 0x2e, 146 0x09, 0x15, 0x68, 0xa9, 0xcd, 0xd4, 0xf1, 0x55, 0xfd, 0xa2, 0xc2, 0x2e,
158 0x42, 0x24, 0x78, 0xd3, 0x05, 0xf3, 0xf8, 0x96 147 0x42, 0x24, 0x78, 0xd3, 0x05, 0xf3, 0xf8, 0x96 };
159 };
160 char result[84]; 148 char result[84];
161 int l = 42; 149 int l = 42;
162 150
163 memset (result, 0, sizeof (result)); 151 memset(result, 0, sizeof(result));
164 GNUNET_assert (GNUNET_CRYPTO_hkdf 152 GNUNET_assert(GNUNET_CRYPTO_hkdf
165 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof (salt), 153 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof(salt),
166 ikm, sizeof (ikm), info, sizeof (info), NULL) == GNUNET_YES); 154 ikm, sizeof(ikm), info, sizeof(info), NULL) == GNUNET_YES);
167 GNUNET_assert (memcmp (result, okm, l) == 0); 155 GNUNET_assert(memcmp(result, okm, l) == 0);
168 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 156 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
169} 157}
170 158
171void 159void
172tc5 () 160tc5()
173{ 161{
174 unsigned char ikm[80] = 162 unsigned char ikm[80] =
175 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 163 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
176 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 164 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
177 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 165 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21,
178 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 166 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
179 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 167 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
180 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 168 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
181 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f 169 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f };
182 };
183 unsigned char salt[80] = 170 unsigned char salt[80] =
184 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 171 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
185 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 172 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
186 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 173 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81,
187 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 174 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
188 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 175 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
189 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 176 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5,
190 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf 177 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf };
191 };
192 unsigned char info[80] = 178 unsigned char info[80] =
193 { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 179 { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 0xb8, 0xb9,
194 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 180 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5,
195 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1, 181 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 0xd0, 0xd1,
196 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 182 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd,
197 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 183 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
198 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 184 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5,
199 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff 185 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff };
200 };
201 unsigned char okm[82] = 186 unsigned char okm[82] =
202 { 0x0b, 0xd7, 0x70, 0xa7, 0x4d, 0x11, 0x60, 0xf7, 0xc9, 0xf1, 187 { 0x0b, 0xd7, 0x70, 0xa7, 0x4d, 0x11, 0x60, 0xf7, 0xc9, 0xf1,
203 0x2c, 0xd5, 0x91, 0x2a, 0x06, 0xeb, 0xff, 0x6a, 0xdc, 0xae, 0x89, 0x9d, 188 0x2c, 0xd5, 0x91, 0x2a, 0x06, 0xeb, 0xff, 0x6a, 0xdc, 0xae, 0x89, 0x9d,
204 0x92, 0x19, 0x1f, 0xe4, 0x30, 0x56, 0x73, 0xba, 0x2f, 0xfe, 0x8f, 0xa3, 189 0x92, 0x19, 0x1f, 0xe4, 0x30, 0x56, 0x73, 0xba, 0x2f, 0xfe, 0x8f, 0xa3,
205 0xf1, 0xa4, 0xe5, 0xad, 0x79, 0xf3, 0xf3, 0x34, 0xb3, 0xb2, 0x02, 0xb2, 190 0xf1, 0xa4, 0xe5, 0xad, 0x79, 0xf3, 0xf3, 0x34, 0xb3, 0xb2, 0x02, 0xb2,
206 0x17, 0x3c, 0x48, 0x6e, 0xa3, 0x7c, 0xe3, 0xd3, 0x97, 0xed, 0x03, 0x4c, 191 0x17, 0x3c, 0x48, 0x6e, 0xa3, 0x7c, 0xe3, 0xd3, 0x97, 0xed, 0x03, 0x4c,
207 0x7f, 0x9d, 0xfe, 0xb1, 0x5c, 0x5e, 0x92, 0x73, 0x36, 0xd0, 0x44, 0x1f, 192 0x7f, 0x9d, 0xfe, 0xb1, 0x5c, 0x5e, 0x92, 0x73, 0x36, 0xd0, 0x44, 0x1f,
208 0x4c, 0x43, 0x00, 0xe2, 0xcf, 0xf0, 0xd0, 0x90, 0x0b, 0x52, 0xd3, 0xb4 193 0x4c, 0x43, 0x00, 0xe2, 0xcf, 0xf0, 0xd0, 0x90, 0x0b, 0x52, 0xd3, 0xb4 };
209 };
210 char result[84]; 194 char result[84];
211 int l = 82; 195 int l = 82;
212 196
213 memset (result, 0, sizeof (result)); 197 memset(result, 0, sizeof(result));
214 GNUNET_assert (GNUNET_CRYPTO_hkdf 198 GNUNET_assert(GNUNET_CRYPTO_hkdf
215 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof (salt), 199 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof(salt),
216 ikm, sizeof (ikm), info, sizeof (info), NULL) == GNUNET_YES); 200 ikm, sizeof(ikm), info, sizeof(info), NULL) == GNUNET_YES);
217 GNUNET_assert (memcmp (result, okm, l) == 0); 201 GNUNET_assert(memcmp(result, okm, l) == 0);
218 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 202 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
219} 203}
220 204
221void 205void
222tc6 () 206tc6()
223{ 207{
224 unsigned char ikm[22] = 208 unsigned char ikm[22] =
225 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 209 { 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
226 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b 210 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b };
227 };
228 unsigned char okm[42] = 211 unsigned char okm[42] =
229 { 0x0a, 0xc1, 0xaf, 0x70, 0x02, 0xb3, 0xd7, 0x61, 0xd1, 0xe5, 212 { 0x0a, 0xc1, 0xaf, 0x70, 0x02, 0xb3, 0xd7, 0x61, 0xd1, 0xe5,
230 0x52, 0x98, 0xda, 0x9d, 0x05, 0x06, 0xb9, 0xae, 0x52, 0x05, 0x72, 0x20, 213 0x52, 0x98, 0xda, 0x9d, 0x05, 0x06, 0xb9, 0xae, 0x52, 0x05, 0x72, 0x20,
231 0xa3, 0x06, 0xe0, 0x7b, 0x6b, 0x87, 0xe8, 0xdf, 0x21, 0xd0, 0xea, 0x00, 214 0xa3, 0x06, 0xe0, 0x7b, 0x6b, 0x87, 0xe8, 0xdf, 0x21, 0xd0, 0xea, 0x00,
232 0x03, 0x3d, 0xe0, 0x39, 0x84, 0xd3, 0x49, 0x18 215 0x03, 0x3d, 0xe0, 0x39, 0x84, 0xd3, 0x49, 0x18 };
233 };
234 char result[44]; 216 char result[44];
235 int l = 42; 217 int l = 42;
236 218
237 memset (result, 0, sizeof (result)); 219 memset(result, 0, sizeof(result));
238 GNUNET_assert (GNUNET_CRYPTO_hkdf 220 GNUNET_assert(GNUNET_CRYPTO_hkdf
239 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, NULL, 0, ikm, 221 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, NULL, 0, ikm,
240 sizeof (ikm), NULL, 0, NULL) == GNUNET_YES); 222 sizeof(ikm), NULL, 0, NULL) == GNUNET_YES);
241 GNUNET_assert (memcmp (result, okm, l) == 0); 223 GNUNET_assert(memcmp(result, okm, l) == 0);
242 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 224 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
243} 225}
244 226
245void 227void
246tc7 () 228tc7()
247{ 229{
248 unsigned char ikm[80] = 230 unsigned char ikm[80] =
249 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 231 { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09,
250 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 232 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
251 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 233 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21,
252 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 234 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d,
253 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 235 0x2e, 0x2f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
254 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 236 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45,
255 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f 237 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f };
256 };
257 unsigned char salt[80] = 238 unsigned char salt[80] =
258 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 239 { 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
259 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 240 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75,
260 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81, 241 0x76, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 0x80, 0x81,
261 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 242 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d,
262 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99, 243 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98, 0x99,
263 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 244 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5,
264 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf 245 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf };
265 };
266 unsigned char info1[34] = { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 246 unsigned char info1[34] = { 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
267 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 247 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3,
268 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 248 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
269 0xd0, 0xd1 249 0xd0, 0xd1 };
270 };
271 unsigned char info2[46] = { 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 250 unsigned char info2[46] = { 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9,
272 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 251 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5,
273 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1, 252 0xe6, 0xe7, 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 0xf0, 0xf1,
274 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 253 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd,
275 0xfe, 0xff 254 0xfe, 0xff };
276 };
277 unsigned char okm[82] = 255 unsigned char okm[82] =
278 { 0x0b, 0xd7, 0x70, 0xa7, 0x4d, 0x11, 0x60, 0xf7, 0xc9, 0xf1, 256 { 0x0b, 0xd7, 0x70, 0xa7, 0x4d, 0x11, 0x60, 0xf7, 0xc9, 0xf1,
279 0x2c, 0xd5, 0x91, 0x2a, 0x06, 0xeb, 0xff, 0x6a, 0xdc, 0xae, 0x89, 0x9d, 257 0x2c, 0xd5, 0x91, 0x2a, 0x06, 0xeb, 0xff, 0x6a, 0xdc, 0xae, 0x89, 0x9d,
280 0x92, 0x19, 0x1f, 0xe4, 0x30, 0x56, 0x73, 0xba, 0x2f, 0xfe, 0x8f, 0xa3, 258 0x92, 0x19, 0x1f, 0xe4, 0x30, 0x56, 0x73, 0xba, 0x2f, 0xfe, 0x8f, 0xa3,
281 0xf1, 0xa4, 0xe5, 0xad, 0x79, 0xf3, 0xf3, 0x34, 0xb3, 0xb2, 0x02, 0xb2, 259 0xf1, 0xa4, 0xe5, 0xad, 0x79, 0xf3, 0xf3, 0x34, 0xb3, 0xb2, 0x02, 0xb2,
282 0x17, 0x3c, 0x48, 0x6e, 0xa3, 0x7c, 0xe3, 0xd3, 0x97, 0xed, 0x03, 0x4c, 260 0x17, 0x3c, 0x48, 0x6e, 0xa3, 0x7c, 0xe3, 0xd3, 0x97, 0xed, 0x03, 0x4c,
283 0x7f, 0x9d, 0xfe, 0xb1, 0x5c, 0x5e, 0x92, 0x73, 0x36, 0xd0, 0x44, 0x1f, 261 0x7f, 0x9d, 0xfe, 0xb1, 0x5c, 0x5e, 0x92, 0x73, 0x36, 0xd0, 0x44, 0x1f,
284 0x4c, 0x43, 0x00, 0xe2, 0xcf, 0xf0, 0xd0, 0x90, 0x0b, 0x52, 0xd3, 0xb4 262 0x4c, 0x43, 0x00, 0xe2, 0xcf, 0xf0, 0xd0, 0x90, 0x0b, 0x52, 0xd3, 0xb4 };
285 };
286 char result[84]; 263 char result[84];
287 int l = 82; 264 int l = 82;
288 265
289 memset (result, 0, sizeof (result)); 266 memset(result, 0, sizeof(result));
290 GNUNET_assert (GNUNET_CRYPTO_hkdf 267 GNUNET_assert(GNUNET_CRYPTO_hkdf
291 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof (salt), 268 (result, l, GCRY_MD_SHA1, GCRY_MD_SHA1, salt, sizeof(salt),
292 ikm, sizeof (ikm), info1, sizeof (info1), info2, 269 ikm, sizeof(ikm), info1, sizeof(info1), info2,
293 sizeof (info2), NULL) == GNUNET_YES); 270 sizeof(info2), NULL) == GNUNET_YES);
294 GNUNET_assert (memcmp (result, okm, l) == 0); 271 GNUNET_assert(memcmp(result, okm, l) == 0);
295 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 272 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
296} 273}
297 274
298void 275void
299tc8 () 276tc8()
300{ 277{
301 unsigned char ikm[32] = 278 unsigned char ikm[32] =
302 { 0xbf, 0x16, 0x6e, 0x46, 0x3a, 0x6c, 0xf3, 0x93, 0xa7, 0x72, 279 { 0xbf, 0x16, 0x6e, 0x46, 0x3a, 0x6c, 0xf3, 0x93, 0xa7, 0x72,
303 0x11, 0xa1, 0xdc, 0x0b, 0x07, 0xdb, 0x1a, 0x5e, 0xd9, 0xb9, 0x81, 0xbe, 280 0x11, 0xa1, 0xdc, 0x0b, 0x07, 0xdb, 0x1a, 0x5e, 0xd9, 0xb9, 0x81, 0xbe,
304 0xea, 0xe4, 0x31, 0x5f, 0x24, 0xff, 0xfe, 0x50, 0x8a, 0xde 281 0xea, 0xe4, 0x31, 0x5f, 0x24, 0xff, 0xfe, 0x50, 0x8a, 0xde };
305 };
306 unsigned char salt[4] = { 0xfc, 0x62, 0x76, 0x35 }; 282 unsigned char salt[4] = { 0xfc, 0x62, 0x76, 0x35 };
307 unsigned char info[86] = 283 unsigned char info[86] =
308 { 0x8c, 0x0d, 0xcf, 0xb3, 0x25, 0x6e, 0x88, 0x0d, 0xc1, 0x0b, 284 { 0x8c, 0x0d, 0xcf, 0xb3, 0x25, 0x6e, 0x88, 0x0d, 0xc1, 0x0b,
309 0x1d, 0x33, 0x15, 0x3e, 0x52, 0x0b, 0xb0, 0x77, 0xff, 0x7d, 0xc3, 0xc7, 285 0x1d, 0x33, 0x15, 0x3e, 0x52, 0x0b, 0xb0, 0x77, 0xff, 0x7d, 0xc3, 0xc7,
310 0xef, 0xe5, 0x8e, 0x3c, 0xc4, 0x4e, 0x8b, 0x41, 0x46, 0x1f, 0x02, 0x94, 286 0xef, 0xe5, 0x8e, 0x3c, 0xc4, 0x4e, 0x8b, 0x41, 0x46, 0x1f, 0x02, 0x94,
311 0x82, 0x35, 0xc5, 0xa6, 0x5e, 0x91, 0xd8, 0xa2, 0x90, 0xfd, 0x6f, 0xb4, 287 0x82, 0x35, 0xc5, 0xa6, 0x5e, 0x91, 0xd8, 0xa2, 0x90, 0xfd, 0x6f, 0xb4,
312 0x07, 0xc9, 0xed, 0x6b, 0x18, 0x90, 0x31, 0xab, 0x0f, 0xb5, 0x6b, 0xec, 288 0x07, 0xc9, 0xed, 0x6b, 0x18, 0x90, 0x31, 0xab, 0x0f, 0xb5, 0x6b, 0xec,
313 0x9e, 0x45, 0xa2, 0x83, 0x65, 0x41, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 289 0x9e, 0x45, 0xa2, 0x83, 0x65, 0x41, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61,
314 0x6c, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x76, 0x65, 0x63, 290 0x6c, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x76, 0x65, 0x63,
315 0x74, 0x6f, 0x72, 0x00 291 0x74, 0x6f, 0x72, 0x00 };
316 };
317 unsigned char okm[16] = 292 unsigned char okm[16] =
318 { 0xd6, 0x90, 0xec, 0x9e, 0x62, 0xdf, 0xb9, 0x41, 0xff, 0x92, 293 { 0xd6, 0x90, 0xec, 0x9e, 0x62, 0xdf, 0xb9, 0x41, 0xff, 0x92,
319 0x4f, 0xd2, 0xf6, 0x1d, 0x67, 0xe0 294 0x4f, 0xd2, 0xf6, 0x1d, 0x67, 0xe0 };
320 };
321 char result[18]; 295 char result[18];
322 int l = 16; 296 int l = 16;
323 297
324 memset (result, 0, sizeof (result)); 298 memset(result, 0, sizeof(result));
325 GNUNET_assert (GNUNET_CRYPTO_hkdf 299 GNUNET_assert(GNUNET_CRYPTO_hkdf
326 (result, l, GCRY_MD_SHA512, GCRY_MD_SHA256, salt, 300 (result, l, GCRY_MD_SHA512, GCRY_MD_SHA256, salt,
327 sizeof (salt), ikm, sizeof (ikm), info, sizeof (info), 301 sizeof(salt), ikm, sizeof(ikm), info, sizeof(info),
328 NULL) == GNUNET_YES); 302 NULL) == GNUNET_YES);
329 GNUNET_assert (memcmp (result, okm, l) == 0); 303 GNUNET_assert(memcmp(result, okm, l) == 0);
330 GNUNET_assert (memcmp (result + l, "\0", 2) == 0); 304 GNUNET_assert(memcmp(result + l, "\0", 2) == 0);
331} 305}
332 306
333int 307int
334main () 308main()
335{ 309{
336 GNUNET_log_setup ("test-crypto-hkdf", "WARNING", NULL); 310 GNUNET_log_setup("test-crypto-hkdf", "WARNING", NULL);
337 311
338 /* Official test vectors */ 312 /* Official test vectors */
339 tc1 (); 313 tc1();
340 tc2 (); 314 tc2();
341 tc3 (); 315 tc3();
342 tc4 (); 316 tc4();
343 tc5 (); 317 tc5();
344 tc6 (); 318 tc6();
345 319
346 /* Additional tests */ 320 /* Additional tests */
347 tc7 (); 321 tc7();
348 tc8 (); 322 tc8();
349 323
350 return 0; 324 return 0;
351} 325}
diff --git a/src/util/test_crypto_kdf.c b/src/util/test_crypto_kdf.c
index f75bafbb1..a5c9bba20 100644
--- a/src/util/test_crypto_kdf.c
+++ b/src/util/test_crypto_kdf.c
@@ -18,7 +18,7 @@
18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 18 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 19 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 THE SOFTWARE. 20 THE SOFTWARE.
21*/ 21 */
22 22
23/** 23/**
24 * @file src/util/test_crypt_kdf.c 24 * @file src/util/test_crypt_kdf.c
@@ -33,38 +33,39 @@
33 33
34 34
35int 35int
36main () 36main()
37{ 37{
38#define RND_BLK_SIZE 4096 38#define RND_BLK_SIZE 4096
39 unsigned char rnd_blk[RND_BLK_SIZE]; 39 unsigned char rnd_blk[RND_BLK_SIZE];
40 int i; 40 int i;
41 gcry_mpi_t r,n; 41 gcry_mpi_t r, n;
42 42
43 GNUNET_log_setup ("test-crypto-kdf", "WARNING", NULL); 43 GNUNET_log_setup("test-crypto-kdf", "WARNING", NULL);
44 44
45 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 45 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
46 rnd_blk, 46 rnd_blk,
47 RND_BLK_SIZE); 47 RND_BLK_SIZE);
48 48
49 /* test full domain hash size */ 49 /* test full domain hash size */
50 for (i=0; i<100; i++) { 50 for (i = 0; i < 100; i++)
51 gcry_mpi_scan (&n, 51 {
52 GCRYMPI_FMT_USG, 52 gcry_mpi_scan(&n,
53 rnd_blk, RND_BLK_SIZE, 53 GCRYMPI_FMT_USG,
54 NULL); 54 rnd_blk, RND_BLK_SIZE,
55 GNUNET_CRYPTO_kdf_mod_mpi (&r, n, 55 NULL);
56 "", 0, 56 GNUNET_CRYPTO_kdf_mod_mpi(&r, n,
57 "", 0, 57 "", 0,
58 ""); 58 "", 0,
59 GNUNET_assert( 0 > gcry_mpi_cmp(r,n) ); 59 "");
60 GNUNET_assert(0 > gcry_mpi_cmp(r, n));
60 61
61 /* Is it worth checking that it's not too small? */ 62 /* Is it worth checking that it's not too small? */
62 /* GNUNET_assert (gcry_mpi_get_nbits(r) > 3*RND_BLK_SIZE/4); */ 63 /* GNUNET_assert (gcry_mpi_get_nbits(r) > 3*RND_BLK_SIZE/4); */
63 /* This test necessarily randomly fails with probability 2^(3 - RND_BLK_SIZE/4) */ 64 /* This test necessarily randomly fails with probability 2^(3 - RND_BLK_SIZE/4) */
64 65
65 gcry_mpi_release(n); 66 gcry_mpi_release(n);
66 gcry_mpi_release(r); 67 gcry_mpi_release(r);
67 } 68 }
68 69
69 return 0; 70 return 0;
70} 71}
diff --git a/src/util/test_crypto_paillier.c b/src/util/test_crypto_paillier.c
index d19696372..c4555fd10 100644
--- a/src/util/test_crypto_paillier.c
+++ b/src/util/test_crypto_paillier.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @file util/test_crypto_paillier.c 22 * @file util/test_crypto_paillier.c
23 * @brief testcase paillier crypto 23 * @brief testcase paillier crypto
@@ -30,7 +30,7 @@
30 30
31 31
32static int 32static int
33test_crypto () 33test_crypto()
34{ 34{
35 gcry_mpi_t plaintext; 35 gcry_mpi_t plaintext;
36 gcry_mpi_t plaintext_result; 36 gcry_mpi_t plaintext_result;
@@ -39,43 +39,43 @@ test_crypto ()
39 struct GNUNET_CRYPTO_PaillierPrivateKey private_key; 39 struct GNUNET_CRYPTO_PaillierPrivateKey private_key;
40 int ret = 0; 40 int ret = 0;
41 41
42 GNUNET_CRYPTO_paillier_create (&public_key, 42 GNUNET_CRYPTO_paillier_create(&public_key,
43 &private_key); 43 &private_key);
44 GNUNET_assert (NULL != (plaintext = gcry_mpi_new (0))); 44 GNUNET_assert(NULL != (plaintext = gcry_mpi_new(0)));
45 GNUNET_assert (NULL != (plaintext_result = gcry_mpi_new (0))); 45 GNUNET_assert(NULL != (plaintext_result = gcry_mpi_new(0)));
46 gcry_mpi_randomize (plaintext, 46 gcry_mpi_randomize(plaintext,
47 GNUNET_CRYPTO_PAILLIER_BITS / 2, 47 GNUNET_CRYPTO_PAILLIER_BITS / 2,
48 GCRY_WEAK_RANDOM); 48 GCRY_WEAK_RANDOM);
49 49
50 GNUNET_CRYPTO_paillier_encrypt (&public_key, 50 GNUNET_CRYPTO_paillier_encrypt(&public_key,
51 plaintext, 51 plaintext,
52 0 /* 0 hom ops */, 52 0 /* 0 hom ops */,
53 &ciphertext); 53 &ciphertext);
54 GNUNET_CRYPTO_paillier_decrypt (&private_key, 54 GNUNET_CRYPTO_paillier_decrypt(&private_key,
55 &public_key, 55 &public_key,
56 &ciphertext, 56 &ciphertext,
57 plaintext_result); 57 plaintext_result);
58 if (0 != gcry_mpi_cmp (plaintext, 58 if (0 != gcry_mpi_cmp(plaintext,
59 plaintext_result)) 59 plaintext_result))
60 { 60 {
61 fprintf (stderr, 61 fprintf(stderr,
62 "Paillier decryption failed with plaintext of size %u\n", 62 "Paillier decryption failed with plaintext of size %u\n",
63 gcry_mpi_get_nbits (plaintext)); 63 gcry_mpi_get_nbits(plaintext));
64 gcry_log_debugmpi ("\n", 64 gcry_log_debugmpi("\n",
65 plaintext); 65 plaintext);
66 gcry_log_debugmpi ("\n", 66 gcry_log_debugmpi("\n",
67 plaintext_result); 67 plaintext_result);
68 ret = 1; 68 ret = 1;
69 } 69 }
70 gcry_mpi_release (plaintext); 70 gcry_mpi_release(plaintext);
71 gcry_mpi_release (plaintext_result); 71 gcry_mpi_release(plaintext_result);
72 return ret; 72 return ret;
73} 73}
74 74
75 75
76static int 76static int
77test_hom_simple (unsigned int a, 77test_hom_simple(unsigned int a,
78 unsigned int b) 78 unsigned int b)
79{ 79{
80 gcry_mpi_t m1; 80 gcry_mpi_t m1;
81 gcry_mpi_t m2; 81 gcry_mpi_t m2;
@@ -88,52 +88,52 @@ test_hom_simple (unsigned int a,
88 struct GNUNET_CRYPTO_PaillierPrivateKey private_key; 88 struct GNUNET_CRYPTO_PaillierPrivateKey private_key;
89 int ret = 0; 89 int ret = 0;
90 90
91 GNUNET_CRYPTO_paillier_create (&public_key, 91 GNUNET_CRYPTO_paillier_create(&public_key,
92 &private_key); 92 &private_key);
93 93
94 GNUNET_assert (NULL != (m1 = gcry_mpi_new (0))); 94 GNUNET_assert(NULL != (m1 = gcry_mpi_new(0)));
95 GNUNET_assert (NULL != (m2 = gcry_mpi_new (0))); 95 GNUNET_assert(NULL != (m2 = gcry_mpi_new(0)));
96 GNUNET_assert (NULL != (result = gcry_mpi_new (0))); 96 GNUNET_assert(NULL != (result = gcry_mpi_new(0)));
97 GNUNET_assert (NULL != (hom_result = gcry_mpi_new (0))); 97 GNUNET_assert(NULL != (hom_result = gcry_mpi_new(0)));
98 m1 = gcry_mpi_set_ui (m1, a); 98 m1 = gcry_mpi_set_ui(m1, a);
99 m2 = gcry_mpi_set_ui (m2, b); 99 m2 = gcry_mpi_set_ui(m2, b);
100 gcry_mpi_add (result, 100 gcry_mpi_add(result,
101 m1, 101 m1,
102 m2); 102 m2);
103 GNUNET_CRYPTO_paillier_encrypt (&public_key, 103 GNUNET_CRYPTO_paillier_encrypt(&public_key,
104 m1, 104 m1,
105 2, 105 2,
106 &c1); 106 &c1);
107 GNUNET_CRYPTO_paillier_encrypt (&public_key, 107 GNUNET_CRYPTO_paillier_encrypt(&public_key,
108 m2, 108 m2,
109 2, 109 2,
110 &c2); 110 &c2);
111 GNUNET_CRYPTO_paillier_hom_add (&public_key, 111 GNUNET_CRYPTO_paillier_hom_add(&public_key,
112 &c1, 112 &c1,
113 &c2, 113 &c2,
114 &c_result); 114 &c_result);
115 GNUNET_CRYPTO_paillier_decrypt (&private_key, 115 GNUNET_CRYPTO_paillier_decrypt(&private_key,
116 &public_key, 116 &public_key,
117 &c_result, 117 &c_result,
118 hom_result); 118 hom_result);
119 if (0 != gcry_mpi_cmp (result, hom_result)) 119 if (0 != gcry_mpi_cmp(result, hom_result))
120 { 120 {
121 fprintf (stderr, 121 fprintf(stderr,
122 "GNUNET_CRYPTO_paillier failed simple math!\n"); 122 "GNUNET_CRYPTO_paillier failed simple math!\n");
123 gcry_log_debugmpi ("got ", hom_result); 123 gcry_log_debugmpi("got ", hom_result);
124 gcry_log_debugmpi ("wanted ", result); 124 gcry_log_debugmpi("wanted ", result);
125 ret = 1; 125 ret = 1;
126 } 126 }
127 gcry_mpi_release (m1); 127 gcry_mpi_release(m1);
128 gcry_mpi_release (m2); 128 gcry_mpi_release(m2);
129 gcry_mpi_release (result); 129 gcry_mpi_release(result);
130 gcry_mpi_release (hom_result); 130 gcry_mpi_release(hom_result);
131 return ret; 131 return ret;
132} 132}
133 133
134 134
135static int 135static int
136test_hom () 136test_hom()
137{ 137{
138 int ret; 138 int ret;
139 gcry_mpi_t m1; 139 gcry_mpi_t m1;
@@ -146,99 +146,100 @@ test_hom ()
146 struct GNUNET_CRYPTO_PaillierPublicKey public_key; 146 struct GNUNET_CRYPTO_PaillierPublicKey public_key;
147 struct GNUNET_CRYPTO_PaillierPrivateKey private_key; 147 struct GNUNET_CRYPTO_PaillierPrivateKey private_key;
148 148
149 GNUNET_CRYPTO_paillier_create (&public_key, 149 GNUNET_CRYPTO_paillier_create(&public_key,
150 &private_key); 150 &private_key);
151 151
152 GNUNET_assert (NULL != (m1 = gcry_mpi_new (0))); 152 GNUNET_assert(NULL != (m1 = gcry_mpi_new(0)));
153 GNUNET_assert (NULL != (m2 = gcry_mpi_new (0))); 153 GNUNET_assert(NULL != (m2 = gcry_mpi_new(0)));
154 GNUNET_assert (NULL != (result = gcry_mpi_new (0))); 154 GNUNET_assert(NULL != (result = gcry_mpi_new(0)));
155 GNUNET_assert (NULL != (hom_result = gcry_mpi_new (0))); 155 GNUNET_assert(NULL != (hom_result = gcry_mpi_new(0)));
156 m1 = gcry_mpi_set_ui (m1, 1); 156 m1 = gcry_mpi_set_ui(m1, 1);
157 /* m1 = m1 * 2 ^ (GCPB - 3) */ 157 /* m1 = m1 * 2 ^ (GCPB - 3) */
158 gcry_mpi_mul_2exp (m1, 158 gcry_mpi_mul_2exp(m1,
159 m1, 159 m1,
160 GNUNET_CRYPTO_PAILLIER_BITS - 3); 160 GNUNET_CRYPTO_PAILLIER_BITS - 3);
161 m2 = gcry_mpi_set_ui (m2, 15); 161 m2 = gcry_mpi_set_ui(m2, 15);
162 /* m1 = m1 * 2 ^ (GCPB / 2) */ 162 /* m1 = m1 * 2 ^ (GCPB / 2) */
163 gcry_mpi_mul_2exp (m2, 163 gcry_mpi_mul_2exp(m2,
164 m2, 164 m2,
165 GNUNET_CRYPTO_PAILLIER_BITS / 2); 165 GNUNET_CRYPTO_PAILLIER_BITS / 2);
166 gcry_mpi_add (result, 166 gcry_mpi_add(result,
167 m1, 167 m1,
168 m2); 168 m2);
169 169
170 if (1 != (ret = GNUNET_CRYPTO_paillier_encrypt (&public_key, 170 if (1 != (ret = GNUNET_CRYPTO_paillier_encrypt(&public_key,
171 m1, 171 m1,
172 2, 172 2,
173 &c1))) 173 &c1)))
174 { 174 {
175 fprintf (stderr, 175 fprintf(stderr,
176 "GNUNET_CRYPTO_paillier_encrypt 1 failed, should return 1 allowed operation, got %d!\n", 176 "GNUNET_CRYPTO_paillier_encrypt 1 failed, should return 1 allowed operation, got %d!\n",
177 ret); 177 ret);
178 ret = 1; 178 ret = 1;
179 goto out; 179 goto out;
180 } 180 }
181 if (2 != (ret = GNUNET_CRYPTO_paillier_encrypt (&public_key, 181 if (2 != (ret = GNUNET_CRYPTO_paillier_encrypt(&public_key,
182 m2, 182 m2,
183 2, 183 2,
184 &c2))) 184 &c2)))
185 { 185 {
186 fprintf (stderr, 186 fprintf(stderr,
187 "GNUNET_CRYPTO_paillier_encrypt 2 failed, should return 2 allowed operation, got %d!\n", 187 "GNUNET_CRYPTO_paillier_encrypt 2 failed, should return 2 allowed operation, got %d!\n",
188 ret); 188 ret);
189 ret = 1; 189 ret = 1;
190 goto out; 190 goto out;
191 } 191 }
192 192
193 if (0 != (ret = GNUNET_CRYPTO_paillier_hom_add (&public_key, 193 if (0 != (ret = GNUNET_CRYPTO_paillier_hom_add(&public_key,
194 &c1, 194 &c1,
195 &c2, 195 &c2,
196 &c_result))) 196 &c_result)))
197 { 197 {
198 fprintf (stderr, 198 fprintf(stderr,
199 "GNUNET_CRYPTO_paillier_hom_add failed, expected 0 remaining operations, got %d!\n", 199 "GNUNET_CRYPTO_paillier_hom_add failed, expected 0 remaining operations, got %d!\n",
200 ret); 200 ret);
201 ret = 1; 201 ret = 1;
202 goto out; 202 goto out;
203 } 203 }
204 204
205 GNUNET_CRYPTO_paillier_decrypt (&private_key, 205 GNUNET_CRYPTO_paillier_decrypt(&private_key,
206 &public_key, 206 &public_key,
207 &c_result, 207 &c_result,
208 hom_result); 208 hom_result);
209 209
210 if (0 != gcry_mpi_cmp (result, hom_result)) 210 if (0 != gcry_mpi_cmp(result, hom_result))
211 { 211 {
212 fprintf (stderr, 212 fprintf(stderr,
213 "GNUNET_CRYPTO_paillier miscalculated with large numbers!\n"); 213 "GNUNET_CRYPTO_paillier miscalculated with large numbers!\n");
214 gcry_log_debugmpi ("got", hom_result); 214 gcry_log_debugmpi("got", hom_result);
215 gcry_log_debugmpi ("wanted", result); 215 gcry_log_debugmpi("wanted", result);
216 ret = 1; 216 ret = 1;
217 } 217 }
218out: 218out:
219 gcry_mpi_release (m1); 219 gcry_mpi_release(m1);
220 gcry_mpi_release (m2); 220 gcry_mpi_release(m2);
221 gcry_mpi_release (result); 221 gcry_mpi_release(result);
222 gcry_mpi_release (hom_result); 222 gcry_mpi_release(hom_result);
223 return ret; 223 return ret;
224} 224}
225 225
226 226
227int 227int
228main (int argc, 228main(int argc,
229 char *argv[]) 229 char *argv[])
230{ 230{
231 int ret; 231 int ret;
232 ret = test_crypto (); 232
233 ret = test_crypto();
233 if (0 != ret) 234 if (0 != ret)
234 return ret; 235 return ret;
235 ret = test_hom_simple (2,4); 236 ret = test_hom_simple(2, 4);
236 if (0 != ret) 237 if (0 != ret)
237 return ret; 238 return ret;
238 ret = test_hom_simple (13,17); 239 ret = test_hom_simple(13, 17);
239 if (0 != ret) 240 if (0 != ret)
240 return ret; 241 return ret;
241 ret = test_hom (); 242 ret = test_hom();
242 return ret; 243 return ret;
243} 244}
244 245
diff --git a/src/util/test_crypto_random.c b/src/util/test_crypto_random.c
index 6386c79db..11f87a25e 100644
--- a/src/util/test_crypto_random.c
+++ b/src/util/test_crypto_random.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21 21
22/** 22/**
23 * @file util/test_crypto_random.c 23 * @file util/test_crypto_random.c
@@ -27,43 +27,42 @@
27#include "gnunet_util_lib.h" 27#include "gnunet_util_lib.h"
28 28
29static int 29static int
30test (enum GNUNET_CRYPTO_Quality mode) 30test(enum GNUNET_CRYPTO_Quality mode)
31{ 31{
32
33 int buf[1024]; 32 int buf[1024];
34 unsigned int *b2; 33 unsigned int *b2;
35 int i; 34 int i;
36 unsigned long long n; 35 unsigned long long n;
37 36
38 for (i = 0; i < 1024; i++) 37 for (i = 0; i < 1024; i++)
39 GNUNET_break (1024 > (buf[i] = GNUNET_CRYPTO_random_u32 (mode, 1024))); 38 GNUNET_break(1024 > (buf[i] = GNUNET_CRYPTO_random_u32(mode, 1024)));
40 for (i = 0; i < 10; i++) 39 for (i = 0; i < 10; i++)
41 {
42 b2 = GNUNET_CRYPTO_random_permute (mode, 1024);
43 if (0 == memcmp (b2, buf, sizeof (buf)))
44 { 40 {
45 fprintf (stderr, "%s", "!"); 41 b2 = GNUNET_CRYPTO_random_permute(mode, 1024);
46 GNUNET_free (b2); 42 if (0 == memcmp(b2, buf, sizeof(buf)))
47 continue; 43 {
44 fprintf(stderr, "%s", "!");
45 GNUNET_free(b2);
46 continue;
47 }
48 GNUNET_free(b2);
49 break;
48 } 50 }
49 GNUNET_free (b2);
50 break;
51 }
52 if (i == 10) 51 if (i == 10)
53 return 1; /* virtually impossible... */ 52 return 1; /* virtually impossible... */
54 53
55 for (n = 10; n < 1024LL * 1024LL * 1024LL; n *= 10) 54 for (n = 10; n < 1024LL * 1024LL * 1024LL; n *= 10)
56 GNUNET_break (n > GNUNET_CRYPTO_random_u64 (mode, n)); 55 GNUNET_break(n > GNUNET_CRYPTO_random_u64(mode, n));
57 return 0; 56 return 0;
58} 57}
59 58
60int 59int
61main (int argc, char *argv[]) 60main(int argc, char *argv[])
62{ 61{
63 GNUNET_log_setup ("test-crypto-random", "WARNING", NULL); 62 GNUNET_log_setup("test-crypto-random", "WARNING", NULL);
64 if (0 != test (GNUNET_CRYPTO_QUALITY_WEAK)) 63 if (0 != test(GNUNET_CRYPTO_QUALITY_WEAK))
65 return 1; 64 return 1;
66 if (0 != test (GNUNET_CRYPTO_QUALITY_STRONG)) 65 if (0 != test(GNUNET_CRYPTO_QUALITY_STRONG))
67 return 1; 66 return 1;
68 67
69 return 0; 68 return 0;
diff --git a/src/util/test_crypto_rsa.c b/src/util/test_crypto_rsa.c
index 36c47005e..0d8827c84 100644
--- a/src/util/test_crypto_rsa.c
+++ b/src/util/test_crypto_rsa.c
@@ -1,22 +1,22 @@
1/* 1/*
2 This file is part of GNUnet 2 This file is part of GNUnet
3 Copyright (C) 2014,2015 GNUnet e.V. 3 Copyright (C) 2014,2015 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_crypto_rsa.c 22 * @file util/test_crypto_rsa.c
@@ -32,8 +32,8 @@
32 32
33 33
34int 34int
35main (int argc, 35main(int argc,
36 char *argv[]) 36 char *argv[])
37{ 37{
38#define RND_BLK_SIZE 4096 38#define RND_BLK_SIZE 4096
39 unsigned char rnd_blk[RND_BLK_SIZE]; 39 unsigned char rnd_blk[RND_BLK_SIZE];
@@ -49,79 +49,79 @@ main (int argc,
49 char *blind_buf; 49 char *blind_buf;
50 size_t bsize; 50 size_t bsize;
51 51
52 GNUNET_log_setup ("test-rsa", "WARNING", NULL); 52 GNUNET_log_setup("test-rsa", "WARNING", NULL);
53 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 53 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
54 rnd_blk, 54 rnd_blk,
55 RND_BLK_SIZE); 55 RND_BLK_SIZE);
56 GNUNET_CRYPTO_hash (rnd_blk, 56 GNUNET_CRYPTO_hash(rnd_blk,
57 RND_BLK_SIZE, 57 RND_BLK_SIZE,
58 &hash); 58 &hash);
59 priv = GNUNET_CRYPTO_rsa_private_key_create (KEY_SIZE); 59 priv = GNUNET_CRYPTO_rsa_private_key_create(KEY_SIZE);
60 priv_copy = GNUNET_CRYPTO_rsa_private_key_dup (priv); 60 priv_copy = GNUNET_CRYPTO_rsa_private_key_dup(priv);
61 GNUNET_assert (NULL != priv_copy); 61 GNUNET_assert(NULL != priv_copy);
62 GNUNET_assert (0 == GNUNET_CRYPTO_rsa_private_key_cmp (priv, priv_copy)); 62 GNUNET_assert(0 == GNUNET_CRYPTO_rsa_private_key_cmp(priv, priv_copy));
63 pub = GNUNET_CRYPTO_rsa_private_key_get_public (priv); 63 pub = GNUNET_CRYPTO_rsa_private_key_get_public(priv);
64 64
65 /* Encoding */ 65 /* Encoding */
66 size_t size; 66 size_t size;
67 char *enc; 67 char *enc;
68 enc = NULL; 68 enc = NULL;
69 size = GNUNET_CRYPTO_rsa_private_key_encode (priv, &enc); 69 size = GNUNET_CRYPTO_rsa_private_key_encode(priv, &enc);
70 70
71 /* Decoding */ 71 /* Decoding */
72 GNUNET_CRYPTO_rsa_private_key_free (priv); 72 GNUNET_CRYPTO_rsa_private_key_free(priv);
73 priv = NULL; 73 priv = NULL;
74 priv = GNUNET_CRYPTO_rsa_private_key_decode (enc, size); 74 priv = GNUNET_CRYPTO_rsa_private_key_decode(enc, size);
75 GNUNET_assert (NULL != priv); 75 GNUNET_assert(NULL != priv);
76 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 76 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
77 enc, size); 77 enc, size);
78 GNUNET_assert (NULL == GNUNET_CRYPTO_rsa_private_key_decode (enc, size)); 78 GNUNET_assert(NULL == GNUNET_CRYPTO_rsa_private_key_decode(enc, size));
79 (void) fprintf (stderr, "The above warning is expected.\n"); 79 (void)fprintf(stderr, "The above warning is expected.\n");
80 GNUNET_free (enc); 80 GNUNET_free(enc);
81 81
82 /* try ordinary sig first */ 82 /* try ordinary sig first */
83 sig = GNUNET_CRYPTO_rsa_sign_fdh (priv, 83 sig = GNUNET_CRYPTO_rsa_sign_fdh(priv,
84 &hash); 84 &hash);
85 sig_copy = GNUNET_CRYPTO_rsa_signature_dup (sig); 85 sig_copy = GNUNET_CRYPTO_rsa_signature_dup(sig);
86 GNUNET_assert (NULL != sig); 86 GNUNET_assert(NULL != sig);
87 GNUNET_assert (0 == GNUNET_CRYPTO_rsa_signature_cmp (sig, sig_copy)); 87 GNUNET_assert(0 == GNUNET_CRYPTO_rsa_signature_cmp(sig, sig_copy));
88 pub_copy = GNUNET_CRYPTO_rsa_public_key_dup (pub); 88 pub_copy = GNUNET_CRYPTO_rsa_public_key_dup(pub);
89 GNUNET_assert (NULL != pub_copy); 89 GNUNET_assert(NULL != pub_copy);
90 GNUNET_assert (GNUNET_OK == 90 GNUNET_assert(GNUNET_OK ==
91 GNUNET_CRYPTO_rsa_verify (&hash, sig, pub_copy)); 91 GNUNET_CRYPTO_rsa_verify(&hash, sig, pub_copy));
92 /* corrupt our hash and see if the signature is still valid */ 92 /* corrupt our hash and see if the signature is still valid */
93 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, &hash, 93 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK, &hash,
94 sizeof (struct GNUNET_HashCode)); 94 sizeof(struct GNUNET_HashCode));
95 GNUNET_assert (GNUNET_OK != GNUNET_CRYPTO_rsa_verify (&hash, 95 GNUNET_assert(GNUNET_OK != GNUNET_CRYPTO_rsa_verify(&hash,
96 sig, 96 sig,
97 pub)); 97 pub));
98 (void) fprintf (stderr, "The above warning is expected.\n"); 98 (void)fprintf(stderr, "The above warning is expected.\n");
99 GNUNET_CRYPTO_rsa_signature_free (sig); 99 GNUNET_CRYPTO_rsa_signature_free(sig);
100 100
101 /* test blind signing */ 101 /* test blind signing */
102 GNUNET_CRYPTO_random_block (GNUNET_CRYPTO_QUALITY_WEAK, 102 GNUNET_CRYPTO_random_block(GNUNET_CRYPTO_QUALITY_WEAK,
103 &bsec, 103 &bsec,
104 sizeof (bsec)); 104 sizeof(bsec));
105 GNUNET_CRYPTO_rsa_blind (&hash, 105 GNUNET_CRYPTO_rsa_blind(&hash,
106 &bsec, 106 &bsec,
107 pub, 107 pub,
108 &blind_buf,&bsize); 108 &blind_buf, &bsize);
109 GNUNET_assert (0 != bsize); 109 GNUNET_assert(0 != bsize);
110 bsig = GNUNET_CRYPTO_rsa_sign_blinded (priv, 110 bsig = GNUNET_CRYPTO_rsa_sign_blinded(priv,
111 blind_buf, 111 blind_buf,
112 bsize); 112 bsize);
113 GNUNET_free (blind_buf); 113 GNUNET_free(blind_buf);
114 sig = GNUNET_CRYPTO_rsa_unblind (bsig, 114 sig = GNUNET_CRYPTO_rsa_unblind(bsig,
115 &bsec, 115 &bsec,
116 pub); 116 pub);
117 GNUNET_CRYPTO_rsa_signature_free (bsig); 117 GNUNET_CRYPTO_rsa_signature_free(bsig);
118 GNUNET_assert (GNUNET_OK == 118 GNUNET_assert(GNUNET_OK ==
119 GNUNET_CRYPTO_rsa_verify (&hash, sig, pub)); 119 GNUNET_CRYPTO_rsa_verify(&hash, sig, pub));
120 GNUNET_CRYPTO_rsa_signature_free (sig); 120 GNUNET_CRYPTO_rsa_signature_free(sig);
121 GNUNET_CRYPTO_rsa_signature_free (sig_copy); 121 GNUNET_CRYPTO_rsa_signature_free(sig_copy);
122 GNUNET_CRYPTO_rsa_private_key_free (priv); 122 GNUNET_CRYPTO_rsa_private_key_free(priv);
123 GNUNET_CRYPTO_rsa_private_key_free (priv_copy); 123 GNUNET_CRYPTO_rsa_private_key_free(priv_copy);
124 GNUNET_CRYPTO_rsa_public_key_free (pub); 124 GNUNET_CRYPTO_rsa_public_key_free(pub);
125 GNUNET_CRYPTO_rsa_public_key_free (pub_copy); 125 GNUNET_CRYPTO_rsa_public_key_free(pub_copy);
126 return 0; 126 return 0;
127} 127}
diff --git a/src/util/test_crypto_symmetric.c b/src/util/test_crypto_symmetric.c
index d731c45b7..c6854711f 100644
--- a/src/util/test_crypto_symmetric.c
+++ b/src/util/test_crypto_symmetric.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
23 * @file util/test_crypto_symmetric.c 23 * @file util/test_crypto_symmetric.c
@@ -30,46 +30,46 @@
30#define INITVALUE "InitializationVectorValueinitializationvectorvalue" 30#define INITVALUE "InitializationVectorValueinitializationvectorvalue"
31 31
32static int 32static int
33testSymcipher () 33testSymcipher()
34{ 34{
35 struct GNUNET_CRYPTO_SymmetricSessionKey key; 35 struct GNUNET_CRYPTO_SymmetricSessionKey key;
36 char result[100]; 36 char result[100];
37 int size; 37 int size;
38 char res[100]; 38 char res[100];
39 39
40 GNUNET_CRYPTO_symmetric_create_session_key (&key); 40 GNUNET_CRYPTO_symmetric_create_session_key(&key);
41 size = 41 size =
42 GNUNET_CRYPTO_symmetric_encrypt (TESTSTRING, strlen (TESTSTRING) + 1, &key, 42 GNUNET_CRYPTO_symmetric_encrypt(TESTSTRING, strlen(TESTSTRING) + 1, &key,
43 (const struct 43 (const struct
44 GNUNET_CRYPTO_SymmetricInitializationVector *) 44 GNUNET_CRYPTO_SymmetricInitializationVector *)
45 INITVALUE, result); 45 INITVALUE, result);
46 if (size == -1) 46 if (size == -1)
47 { 47 {
48 printf ("symciphertest failed: encryptBlock returned %d\n", size); 48 printf("symciphertest failed: encryptBlock returned %d\n", size);
49 return 1; 49 return 1;
50 } 50 }
51 size = 51 size =
52 GNUNET_CRYPTO_symmetric_decrypt (result, size, &key, 52 GNUNET_CRYPTO_symmetric_decrypt(result, size, &key,
53 (const struct 53 (const struct
54 GNUNET_CRYPTO_SymmetricInitializationVector *) 54 GNUNET_CRYPTO_SymmetricInitializationVector *)
55 INITVALUE, res); 55 INITVALUE, res);
56 if (strlen (TESTSTRING) + 1 != size) 56 if (strlen(TESTSTRING) + 1 != size)
57 { 57 {
58 printf ("symciphertest failed: decryptBlock returned %d\n", size); 58 printf("symciphertest failed: decryptBlock returned %d\n", size);
59 return 1; 59 return 1;
60 } 60 }
61 if (0 != strcmp (res, TESTSTRING)) 61 if (0 != strcmp(res, TESTSTRING))
62 { 62 {
63 printf ("symciphertest failed: %s != %s\n", res, TESTSTRING); 63 printf("symciphertest failed: %s != %s\n", res, TESTSTRING);
64 return 1; 64 return 1;
65 } 65 }
66 else 66 else
67 return 0; 67 return 0;
68} 68}
69 69
70 70
71static int 71static int
72verifyCrypto () 72verifyCrypto()
73{ 73{
74 struct GNUNET_CRYPTO_SymmetricSessionKey key; 74 struct GNUNET_CRYPTO_SymmetricSessionKey key;
75 char result[GNUNET_CRYPTO_AES_KEY_LENGTH]; 75 char result[GNUNET_CRYPTO_AES_KEY_LENGTH];
@@ -103,68 +103,68 @@ verifyCrypto ()
103 res = NULL; 103 res = NULL;
104 ret = 0; 104 ret = 0;
105 105
106 GNUNET_memcpy (key.aes_key, raw_key_aes, GNUNET_CRYPTO_AES_KEY_LENGTH); 106 GNUNET_memcpy(key.aes_key, raw_key_aes, GNUNET_CRYPTO_AES_KEY_LENGTH);
107 GNUNET_memcpy (key.twofish_key, raw_key_twofish, GNUNET_CRYPTO_AES_KEY_LENGTH); 107 GNUNET_memcpy(key.twofish_key, raw_key_twofish, GNUNET_CRYPTO_AES_KEY_LENGTH);
108 if (GNUNET_CRYPTO_AES_KEY_LENGTH != 108 if (GNUNET_CRYPTO_AES_KEY_LENGTH !=
109 GNUNET_CRYPTO_symmetric_encrypt (plain, GNUNET_CRYPTO_AES_KEY_LENGTH, &key, 109 GNUNET_CRYPTO_symmetric_encrypt(plain, GNUNET_CRYPTO_AES_KEY_LENGTH, &key,
110 (const struct 110 (const struct
111 GNUNET_CRYPTO_SymmetricInitializationVector *) 111 GNUNET_CRYPTO_SymmetricInitializationVector *)
112 "testtesttesttesttesttesttesttest", 112 "testtesttesttesttesttesttesttest",
113 result)) 113 result))
114 { 114 {
115 printf ("Wrong return value from encrypt block.\n"); 115 printf("Wrong return value from encrypt block.\n");
116 ret = 1; 116 ret = 1;
117 goto error; 117 goto error;
118 } 118 }
119 119
120 if (0 != memcmp (encrresult, result, GNUNET_CRYPTO_AES_KEY_LENGTH)) 120 if (0 != memcmp(encrresult, result, GNUNET_CRYPTO_AES_KEY_LENGTH))
121 { 121 {
122 int i; 122 int i;
123 printf ("Encrypted result wrong.\n"); 123 printf("Encrypted result wrong.\n");
124 for (i=0;i<GNUNET_CRYPTO_AES_KEY_LENGTH;i++) 124 for (i = 0; i < GNUNET_CRYPTO_AES_KEY_LENGTH; i++)
125 printf ("%u, ", (uint8_t) result[i]); 125 printf("%u, ", (uint8_t)result[i]);
126 ret = 1; 126 ret = 1;
127 goto error; 127 goto error;
128 } 128 }
129 129
130 res = GNUNET_malloc (GNUNET_CRYPTO_AES_KEY_LENGTH); 130 res = GNUNET_malloc(GNUNET_CRYPTO_AES_KEY_LENGTH);
131 if (GNUNET_CRYPTO_AES_KEY_LENGTH != 131 if (GNUNET_CRYPTO_AES_KEY_LENGTH !=
132 GNUNET_CRYPTO_symmetric_decrypt (result, GNUNET_CRYPTO_AES_KEY_LENGTH, &key, 132 GNUNET_CRYPTO_symmetric_decrypt(result, GNUNET_CRYPTO_AES_KEY_LENGTH, &key,
133 (const struct 133 (const struct
134 GNUNET_CRYPTO_SymmetricInitializationVector *) 134 GNUNET_CRYPTO_SymmetricInitializationVector *)
135 "testtesttesttesttesttesttesttest", res)) 135 "testtesttesttesttesttesttesttest", res))
136 { 136 {
137 printf ("Wrong return value from decrypt block.\n"); 137 printf("Wrong return value from decrypt block.\n");
138 ret = 1; 138 ret = 1;
139 goto error; 139 goto error;
140 } 140 }
141 if (0 != memcmp (res, plain, GNUNET_CRYPTO_AES_KEY_LENGTH)) 141 if (0 != memcmp(res, plain, GNUNET_CRYPTO_AES_KEY_LENGTH))
142 { 142 {
143 printf ("Decrypted result does not match input.\n"); 143 printf("Decrypted result does not match input.\n");
144 ret = 1; 144 ret = 1;
145 } 145 }
146error: 146error:
147 GNUNET_free_non_null (res); 147 GNUNET_free_non_null(res);
148 return ret; 148 return ret;
149} 149}
150 150
151 151
152int 152int
153main (int argc, char *argv[]) 153main(int argc, char *argv[])
154{ 154{
155 int failureCount = 0; 155 int failureCount = 0;
156 156
157 GNUNET_log_setup ("test-crypto-aes", "WARNING", NULL); 157 GNUNET_log_setup("test-crypto-aes", "WARNING", NULL);
158 GNUNET_assert (strlen (INITVALUE) > 158 GNUNET_assert(strlen(INITVALUE) >
159 sizeof (struct GNUNET_CRYPTO_SymmetricInitializationVector)); 159 sizeof(struct GNUNET_CRYPTO_SymmetricInitializationVector));
160 failureCount += testSymcipher (); 160 failureCount += testSymcipher();
161 failureCount += verifyCrypto (); 161 failureCount += verifyCrypto();
162 162
163 if (failureCount != 0) 163 if (failureCount != 0)
164 { 164 {
165 printf ("%d TESTS FAILED!\n", failureCount); 165 printf("%d TESTS FAILED!\n", failureCount);
166 return -1; 166 return -1;
167 } 167 }
168 return 0; 168 return 0;
169} 169}
170 170
diff --git a/src/util/test_disk.c b/src/util/test_disk.c
index 5746aa96e..13fb18e88 100644
--- a/src/util/test_disk.c
+++ b/src/util/test_disk.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_disk.c 22 * @file util/test_disk.c
@@ -30,51 +30,51 @@
30 30
31 31
32static int 32static int
33testReadWrite () 33testReadWrite()
34{ 34{
35 char tmp[100 + 1]; 35 char tmp[100 + 1];
36 int ret; 36 int ret;
37 37
38 if (strlen (TESTSTRING) != 38 if (strlen(TESTSTRING) !=
39 GNUNET_DISK_fn_write (".testfile", TESTSTRING, strlen (TESTSTRING), 39 GNUNET_DISK_fn_write(".testfile", TESTSTRING, strlen(TESTSTRING),
40 GNUNET_DISK_PERM_USER_READ | 40 GNUNET_DISK_PERM_USER_READ |
41 GNUNET_DISK_PERM_USER_WRITE)) 41 GNUNET_DISK_PERM_USER_WRITE))
42 return 1; 42 return 1;
43 if (GNUNET_OK != GNUNET_DISK_file_test (".testfile")) 43 if (GNUNET_OK != GNUNET_DISK_file_test(".testfile"))
44 return 1; 44 return 1;
45 ret = GNUNET_DISK_fn_read (".testfile", tmp, sizeof (tmp) - 1); 45 ret = GNUNET_DISK_fn_read(".testfile", tmp, sizeof(tmp) - 1);
46 if (ret < 0) 46 if (ret < 0)
47 { 47 {
48 fprintf (stderr, "Error reading file `%s' in testReadWrite\n", ".testfile"); 48 fprintf(stderr, "Error reading file `%s' in testReadWrite\n", ".testfile");
49 return 1; 49 return 1;
50 } 50 }
51 tmp[ret] = '\0'; 51 tmp[ret] = '\0';
52 if (0 != memcmp (tmp, TESTSTRING, strlen (TESTSTRING) + 1)) 52 if (0 != memcmp(tmp, TESTSTRING, strlen(TESTSTRING) + 1))
53 { 53 {
54 fprintf (stderr, "Error in testReadWrite: *%s* != *%s* for file %s\n", tmp, 54 fprintf(stderr, "Error in testReadWrite: *%s* != *%s* for file %s\n", tmp,
55 TESTSTRING, ".testfile"); 55 TESTSTRING, ".testfile");
56 return 1; 56 return 1;
57 } 57 }
58 GNUNET_DISK_file_copy (".testfile", ".testfile2"); 58 GNUNET_DISK_file_copy(".testfile", ".testfile2");
59 memset (tmp, 0, sizeof (tmp)); 59 memset(tmp, 0, sizeof(tmp));
60 ret = GNUNET_DISK_fn_read (".testfile2", tmp, sizeof (tmp) - 1); 60 ret = GNUNET_DISK_fn_read(".testfile2", tmp, sizeof(tmp) - 1);
61 if (ret < 0) 61 if (ret < 0)
62 { 62 {
63 fprintf (stderr, "Error reading file `%s' in testReadWrite\n", 63 fprintf(stderr, "Error reading file `%s' in testReadWrite\n",
64 ".testfile2"); 64 ".testfile2");
65 return 1; 65 return 1;
66 } 66 }
67 tmp[ret] = '\0'; 67 tmp[ret] = '\0';
68 if (0 != memcmp (tmp, TESTSTRING, strlen (TESTSTRING) + 1)) 68 if (0 != memcmp(tmp, TESTSTRING, strlen(TESTSTRING) + 1))
69 { 69 {
70 fprintf (stderr, "Error in testReadWrite: *%s* != *%s* for file %s\n", tmp, 70 fprintf(stderr, "Error in testReadWrite: *%s* != *%s* for file %s\n", tmp,
71 TESTSTRING, ".testfile2"); 71 TESTSTRING, ".testfile2");
72 return 1; 72 return 1;
73 } 73 }
74 74
75 GNUNET_break (0 == unlink (".testfile")); 75 GNUNET_break(0 == unlink(".testfile"));
76 GNUNET_break (0 == unlink (".testfile2")); 76 GNUNET_break(0 == unlink(".testfile2"));
77 if (GNUNET_NO != GNUNET_DISK_file_test (".testfile")) 77 if (GNUNET_NO != GNUNET_DISK_file_test(".testfile"))
78 return 1; 78 return 1;
79 79
80 return 0; 80 return 0;
@@ -82,24 +82,24 @@ testReadWrite ()
82 82
83 83
84static int 84static int
85testOpenClose () 85testOpenClose()
86{ 86{
87 struct GNUNET_DISK_FileHandle *fh; 87 struct GNUNET_DISK_FileHandle *fh;
88 uint64_t size; 88 uint64_t size;
89 89
90 fh = GNUNET_DISK_file_open (".testfile", 90 fh = GNUNET_DISK_file_open(".testfile",
91 GNUNET_DISK_OPEN_READWRITE | 91 GNUNET_DISK_OPEN_READWRITE |
92 GNUNET_DISK_OPEN_CREATE, 92 GNUNET_DISK_OPEN_CREATE,
93 GNUNET_DISK_PERM_USER_READ | 93 GNUNET_DISK_PERM_USER_READ |
94 GNUNET_DISK_PERM_USER_WRITE); 94 GNUNET_DISK_PERM_USER_WRITE);
95 GNUNET_assert (GNUNET_NO == GNUNET_DISK_handle_invalid (fh)); 95 GNUNET_assert(GNUNET_NO == GNUNET_DISK_handle_invalid(fh));
96 GNUNET_break (5 == GNUNET_DISK_file_write (fh, "Hello", 5)); 96 GNUNET_break(5 == GNUNET_DISK_file_write(fh, "Hello", 5));
97 GNUNET_DISK_file_close (fh); 97 GNUNET_DISK_file_close(fh);
98 GNUNET_break (GNUNET_OK == 98 GNUNET_break(GNUNET_OK ==
99 GNUNET_DISK_file_size (".testfile", &size, GNUNET_NO, GNUNET_YES)); 99 GNUNET_DISK_file_size(".testfile", &size, GNUNET_NO, GNUNET_YES));
100 if (size != 5) 100 if (size != 5)
101 return 1; 101 return 1;
102 GNUNET_break (0 == unlink (".testfile")); 102 GNUNET_break(0 == unlink(".testfile"));
103 103
104 return 0; 104 return 0;
105} 105}
@@ -108,116 +108,116 @@ static int ok;
108 108
109 109
110static int 110static int
111scan_callback (void *want, const char *filename) 111scan_callback(void *want, const char *filename)
112{ 112{
113 if (NULL != strstr (filename, want)) 113 if (NULL != strstr(filename, want))
114 ok++; 114 ok++;
115 return GNUNET_OK; 115 return GNUNET_OK;
116} 116}
117 117
118 118
119static int 119static int
120testDirScan () 120testDirScan()
121{ 121{
122 if (GNUNET_OK != 122 if (GNUNET_OK !=
123 GNUNET_DISK_directory_create ("test" DIR_SEPARATOR_STR "entry")) 123 GNUNET_DISK_directory_create("test" DIR_SEPARATOR_STR "entry"))
124 { 124 {
125 GNUNET_break (0); 125 GNUNET_break(0);
126 return 1; 126 return 1;
127 } 127 }
128 if (GNUNET_OK != 128 if (GNUNET_OK !=
129 GNUNET_DISK_directory_create ("test" DIR_SEPARATOR_STR "entry_more")) 129 GNUNET_DISK_directory_create("test" DIR_SEPARATOR_STR "entry_more"))
130 { 130 {
131 GNUNET_break (0); 131 GNUNET_break(0);
132 return 1; 132 return 1;
133 } 133 }
134 GNUNET_DISK_directory_scan ("test", &scan_callback, 134 GNUNET_DISK_directory_scan("test", &scan_callback,
135 "test" DIR_SEPARATOR_STR "entry"); 135 "test" DIR_SEPARATOR_STR "entry");
136 if (GNUNET_OK != GNUNET_DISK_directory_remove ("test")) 136 if (GNUNET_OK != GNUNET_DISK_directory_remove("test"))
137 { 137 {
138 GNUNET_break (0); 138 GNUNET_break(0);
139 return 1; 139 return 1;
140 } 140 }
141 if (ok < 2) 141 if (ok < 2)
142 { 142 {
143 GNUNET_break (0); 143 GNUNET_break(0);
144 return 1; 144 return 1;
145 } 145 }
146 return 0; 146 return 0;
147} 147}
148 148
149 149
150static int 150static int
151iter_callback (void *cls, 151iter_callback(void *cls,
152 const char *filename) 152 const char *filename)
153{ 153{
154 int *i = cls; 154 int *i = cls;
155 155
156 (*i)++; 156 (*i)++;
157 return GNUNET_OK; 157 return GNUNET_OK;
158} 158}
159 159
160 160
161static int 161static int
162testDirIter () 162testDirIter()
163{ 163{
164 int i; 164 int i;
165 165
166 i = 0; 166 i = 0;
167 if (GNUNET_OK != GNUNET_DISK_directory_create ("test/entry")) 167 if (GNUNET_OK != GNUNET_DISK_directory_create("test/entry"))
168 { 168 {
169 GNUNET_break (0); 169 GNUNET_break(0);
170 return 1; 170 return 1;
171 } 171 }
172 if (GNUNET_OK != GNUNET_DISK_directory_create ("test/entry_many")) 172 if (GNUNET_OK != GNUNET_DISK_directory_create("test/entry_many"))
173 { 173 {
174 GNUNET_break (0); 174 GNUNET_break(0);
175 return 1; 175 return 1;
176 } 176 }
177 if (GNUNET_OK != GNUNET_DISK_directory_create ("test/entry_more")) 177 if (GNUNET_OK != GNUNET_DISK_directory_create("test/entry_more"))
178 { 178 {
179 GNUNET_break (0); 179 GNUNET_break(0);
180 return 1; 180 return 1;
181 } 181 }
182 GNUNET_DISK_directory_scan ("test", 182 GNUNET_DISK_directory_scan("test",
183 &iter_callback, 183 &iter_callback,
184 &i); 184 &i);
185 if (GNUNET_OK != GNUNET_DISK_directory_remove ("test")) 185 if (GNUNET_OK != GNUNET_DISK_directory_remove("test"))
186 { 186 {
187 GNUNET_break (0); 187 GNUNET_break(0);
188 return 1; 188 return 1;
189 } 189 }
190 if (i < 3) 190 if (i < 3)
191 { 191 {
192 GNUNET_break (0); 192 GNUNET_break(0);
193 return 1; 193 return 1;
194 } 194 }
195 return 0; 195 return 0;
196} 196}
197 197
198 198
199static int 199static int
200testCanonicalize () 200testCanonicalize()
201{ 201{
202 char *fn = GNUNET_strdup ("ab?><|cd*ef:/g\""); 202 char *fn = GNUNET_strdup("ab?><|cd*ef:/g\"");
203 203
204 GNUNET_DISK_filename_canonicalize (fn); 204 GNUNET_DISK_filename_canonicalize(fn);
205 if (0 != strcmp (fn, "ab____cd_ef__g_")) 205 if (0 != strcmp(fn, "ab____cd_ef__g_"))
206 { 206 {
207 GNUNET_free (fn); 207 GNUNET_free(fn);
208 return 1; 208 return 1;
209 } 209 }
210 GNUNET_free (fn); 210 GNUNET_free(fn);
211 return 0; 211 return 0;
212} 212}
213 213
214 214
215static int 215static int
216testChangeOwner () 216testChangeOwner()
217{ 217{
218#ifndef WINDOWS 218#ifndef WINDOWS
219 GNUNET_log_skip (1, GNUNET_NO); 219 GNUNET_log_skip(1, GNUNET_NO);
220 if (GNUNET_OK == GNUNET_DISK_file_change_owner ("/dev/null", "unknownuser")) 220 if (GNUNET_OK == GNUNET_DISK_file_change_owner("/dev/null", "unknownuser"))
221 return 1; 221 return 1;
222#endif 222#endif
223 return 0; 223 return 0;
@@ -225,66 +225,66 @@ testChangeOwner ()
225 225
226 226
227static int 227static int
228testDirMani () 228testDirMani()
229{ 229{
230 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file ("test/ing")) 230 if (GNUNET_OK != GNUNET_DISK_directory_create_for_file("test/ing"))
231 { 231 {
232 GNUNET_break (0); 232 GNUNET_break(0);
233 return 1; 233 return 1;
234 } 234 }
235 if (GNUNET_NO != GNUNET_DISK_file_test ("test")) 235 if (GNUNET_NO != GNUNET_DISK_file_test("test"))
236 { 236 {
237 GNUNET_break (0); 237 GNUNET_break(0);
238 return 1; 238 return 1;
239 } 239 }
240 if (GNUNET_NO != GNUNET_DISK_file_test ("test/ing")) 240 if (GNUNET_NO != GNUNET_DISK_file_test("test/ing"))
241 { 241 {
242 GNUNET_break (0); 242 GNUNET_break(0);
243 return 1; 243 return 1;
244 } 244 }
245 if (GNUNET_OK != GNUNET_DISK_directory_remove ("test")) 245 if (GNUNET_OK != GNUNET_DISK_directory_remove("test"))
246 { 246 {
247 GNUNET_break (0); 247 GNUNET_break(0);
248 return 1; 248 return 1;
249 } 249 }
250 if (GNUNET_OK != GNUNET_DISK_directory_create ("test")) 250 if (GNUNET_OK != GNUNET_DISK_directory_create("test"))
251 { 251 {
252 GNUNET_break (0); 252 GNUNET_break(0);
253 return 1; 253 return 1;
254 } 254 }
255 if (GNUNET_YES != GNUNET_DISK_directory_test ("test", GNUNET_YES)) 255 if (GNUNET_YES != GNUNET_DISK_directory_test("test", GNUNET_YES))
256 { 256 {
257 GNUNET_break (0); 257 GNUNET_break(0);
258 return 1; 258 return 1;
259 } 259 }
260 if (GNUNET_OK != GNUNET_DISK_directory_remove ("test")) 260 if (GNUNET_OK != GNUNET_DISK_directory_remove("test"))
261 { 261 {
262 GNUNET_break (0); 262 GNUNET_break(0);
263 return 1; 263 return 1;
264 } 264 }
265 return 0; 265 return 0;
266} 266}
267 267
268 268
269int 269int
270main (int argc, char *argv[]) 270main(int argc, char *argv[])
271{ 271{
272 unsigned int failureCount = 0; 272 unsigned int failureCount = 0;
273 273
274 GNUNET_log_setup ("test-disk", "WARNING", NULL); 274 GNUNET_log_setup("test-disk", "WARNING", NULL);
275 failureCount += testReadWrite (); 275 failureCount += testReadWrite();
276 failureCount += testOpenClose (); 276 failureCount += testOpenClose();
277 failureCount += testDirScan (); 277 failureCount += testDirScan();
278 failureCount += testDirIter (); 278 failureCount += testDirIter();
279 failureCount += testCanonicalize (); 279 failureCount += testCanonicalize();
280 failureCount += testChangeOwner (); 280 failureCount += testChangeOwner();
281 failureCount += testDirMani (); 281 failureCount += testDirMani();
282 if (0 != failureCount) 282 if (0 != failureCount)
283 { 283 {
284 fprintf (stderr, 284 fprintf(stderr,
285 "\n%u TESTS FAILED!\n", 285 "\n%u TESTS FAILED!\n",
286 failureCount); 286 failureCount);
287 return -1; 287 return -1;
288 } 288 }
289 return 0; 289 return 0;
290} /* end of main */ 290} /* end of main */
diff --git a/src/util/test_getopt.c b/src/util/test_getopt.c
index d9dd7121f..620605f96 100644
--- a/src/util/test_getopt.c
+++ b/src/util/test_getopt.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_getopt.c 21 * @file util/test_getopt.c
22 * @brief testcase for util/getopt.c 22 * @brief testcase for util/getopt.c
@@ -26,13 +26,14 @@
26 26
27 27
28static int 28static int
29testMinimal () 29testMinimal()
30{ 30{
31 char *const emptyargv[] = {"test", NULL}; 31 char *const emptyargv[] = { "test", NULL };
32 const struct GNUNET_GETOPT_CommandLineOption emptyoptionlist[] = { 32 const struct GNUNET_GETOPT_CommandLineOption emptyoptionlist[] = {
33 GNUNET_GETOPT_OPTION_END}; 33 GNUNET_GETOPT_OPTION_END
34 };
34 35
35 if (1 != GNUNET_GETOPT_run ("test", emptyoptionlist, 1, emptyargv)) 36 if (1 != GNUNET_GETOPT_run("test", emptyoptionlist, 1, emptyargv))
36 return 1; 37 return 1;
37 38
38 return 0; 39 return 0;
@@ -40,142 +41,142 @@ testMinimal ()
40 41
41 42
42static int 43static int
43testVerbose () 44testVerbose()
44{ 45{
45 char *const myargv[] = {"test", "-V", "-V", "more", NULL}; 46 char *const myargv[] = { "test", "-V", "-V", "more", NULL };
46 unsigned int vflags = 0; 47 unsigned int vflags = 0;
47 48
48 const struct GNUNET_GETOPT_CommandLineOption verboseoptionlist[] = 49 const struct GNUNET_GETOPT_CommandLineOption verboseoptionlist[] =
49 {GNUNET_GETOPT_option_verbose (&vflags), GNUNET_GETOPT_OPTION_END}; 50 { GNUNET_GETOPT_option_verbose(&vflags), GNUNET_GETOPT_OPTION_END };
50 51
51 if (3 != GNUNET_GETOPT_run ("test", verboseoptionlist, 4, myargv)) 52 if (3 != GNUNET_GETOPT_run("test", verboseoptionlist, 4, myargv))
52 { 53 {
53 GNUNET_break (0); 54 GNUNET_break(0);
54 return 1; 55 return 1;
55 } 56 }
56 if (vflags != 2) 57 if (vflags != 2)
57 { 58 {
58 GNUNET_break (0); 59 GNUNET_break(0);
59 return 1; 60 return 1;
60 } 61 }
61 return 0; 62 return 0;
62} 63}
63 64
64 65
65static int 66static int
66testVersion () 67testVersion()
67{ 68{
68 char *const myargv[] = {"test_getopt", "-v", NULL}; 69 char *const myargv[] = { "test_getopt", "-v", NULL };
69 const struct GNUNET_GETOPT_CommandLineOption versionoptionlist[] = 70 const struct GNUNET_GETOPT_CommandLineOption versionoptionlist[] =
70 {GNUNET_GETOPT_option_version (PACKAGE_VERSION " " VCS_VERSION), 71 { GNUNET_GETOPT_option_version(PACKAGE_VERSION " " VCS_VERSION),
71 GNUNET_GETOPT_OPTION_END}; 72 GNUNET_GETOPT_OPTION_END };
72 73
73 if (0 != GNUNET_GETOPT_run ("test_getopt", versionoptionlist, 2, myargv)) 74 if (0 != GNUNET_GETOPT_run("test_getopt", versionoptionlist, 2, myargv))
74 { 75 {
75 GNUNET_break (0); 76 GNUNET_break(0);
76 return 1; 77 return 1;
77 } 78 }
78 return 0; 79 return 0;
79} 80}
80 81
81 82
82static int 83static int
83testAbout () 84testAbout()
84{ 85{
85 char *const myargv[] = {"test_getopt", "-h", NULL}; 86 char *const myargv[] = { "test_getopt", "-h", NULL };
86 const struct GNUNET_GETOPT_CommandLineOption aboutoptionlist[] = 87 const struct GNUNET_GETOPT_CommandLineOption aboutoptionlist[] =
87 {GNUNET_GETOPT_option_help ("Testing"), GNUNET_GETOPT_OPTION_END}; 88 { GNUNET_GETOPT_option_help("Testing"), GNUNET_GETOPT_OPTION_END };
88 89
89 if (0 != GNUNET_GETOPT_run ("test_getopt", aboutoptionlist, 2, myargv)) 90 if (0 != GNUNET_GETOPT_run("test_getopt", aboutoptionlist, 2, myargv))
90 { 91 {
91 GNUNET_break (0); 92 GNUNET_break(0);
92 return 1; 93 return 1;
93 } 94 }
94 return 0; 95 return 0;
95} 96}
96 97
97 98
98static int 99static int
99testLogOpts () 100testLogOpts()
100{ 101{
101 char *const myargv[] = 102 char *const myargv[] =
102 {"test_getopt", "-l", "filename", "-L", "WARNING", NULL}; 103 { "test_getopt", "-l", "filename", "-L", "WARNING", NULL };
103 char *level = GNUNET_strdup ("stuff"); 104 char *level = GNUNET_strdup("stuff");
104 char *fn = NULL; 105 char *fn = NULL;
105 106
106 const struct GNUNET_GETOPT_CommandLineOption logoptionlist[] = 107 const struct GNUNET_GETOPT_CommandLineOption logoptionlist[] =
107 {GNUNET_GETOPT_option_logfile (&fn), 108 { GNUNET_GETOPT_option_logfile(&fn),
108 GNUNET_GETOPT_option_loglevel (&level), 109 GNUNET_GETOPT_option_loglevel(&level),
109 GNUNET_GETOPT_OPTION_END}; 110 GNUNET_GETOPT_OPTION_END };
110 111
111 if (5 != GNUNET_GETOPT_run ("test_getopt", logoptionlist, 5, myargv)) 112 if (5 != GNUNET_GETOPT_run("test_getopt", logoptionlist, 5, myargv))
112 { 113 {
113 GNUNET_break (0); 114 GNUNET_break(0);
114 return 1; 115 return 1;
115 } 116 }
116 GNUNET_assert (NULL != fn); 117 GNUNET_assert(NULL != fn);
117 if ((0 != strcmp (level, "WARNING")) || (NULL == strstr (fn, "/filename"))) 118 if ((0 != strcmp(level, "WARNING")) || (NULL == strstr(fn, "/filename")))
118 { 119 {
119 GNUNET_break (0); 120 GNUNET_break(0);
120 GNUNET_free (level); 121 GNUNET_free(level);
121 GNUNET_free (fn); 122 GNUNET_free(fn);
122 return 1; 123 return 1;
123 } 124 }
124 GNUNET_free (level); 125 GNUNET_free(level);
125 GNUNET_free (fn); 126 GNUNET_free(fn);
126 return 0; 127 return 0;
127} 128}
128 129
129 130
130static int 131static int
131testFlagNum () 132testFlagNum()
132{ 133{
133 char *const myargv[] = {"test_getopt", "-f", "-n", "42", "-N", "42", NULL}; 134 char *const myargv[] = { "test_getopt", "-f", "-n", "42", "-N", "42", NULL };
134 int flag = 0; 135 int flag = 0;
135 unsigned int num = 0; 136 unsigned int num = 0;
136 unsigned long long lnum = 0; 137 unsigned long long lnum = 0;
137 138
138 const struct GNUNET_GETOPT_CommandLineOption logoptionlist[] = 139 const struct GNUNET_GETOPT_CommandLineOption logoptionlist[] =
139 {GNUNET_GETOPT_option_flag ('f', "--flag", "helptext", &flag), 140 { GNUNET_GETOPT_option_flag('f', "--flag", "helptext", &flag),
140 GNUNET_GETOPT_option_uint ('n', "--num", "ARG", "helptext", &num), 141 GNUNET_GETOPT_option_uint('n', "--num", "ARG", "helptext", &num),
141 GNUNET_GETOPT_option_ulong ('N', "--lnum", "ARG", "helptext", &lnum), 142 GNUNET_GETOPT_option_ulong('N', "--lnum", "ARG", "helptext", &lnum),
142 GNUNET_GETOPT_OPTION_END}; 143 GNUNET_GETOPT_OPTION_END };
143 144
144 if (6 != GNUNET_GETOPT_run ("test_getopt", logoptionlist, 6, myargv)) 145 if (6 != GNUNET_GETOPT_run("test_getopt", logoptionlist, 6, myargv))
145 { 146 {
146 GNUNET_break (0); 147 GNUNET_break(0);
147 return 1; 148 return 1;
148 } 149 }
149 if ((1 != flag) || (42 != num) || (42 != lnum)) 150 if ((1 != flag) || (42 != num) || (42 != lnum))
150 { 151 {
151 GNUNET_break (0); 152 GNUNET_break(0);
152 return 1; 153 return 1;
153 } 154 }
154 return 0; 155 return 0;
155} 156}
156 157
157 158
158int 159int
159main (int argc, char *argv[]) 160main(int argc, char *argv[])
160{ 161{
161 int errCnt = 0; 162 int errCnt = 0;
162 163
163 GNUNET_log_setup ("test_getopt", "WARNING", NULL); 164 GNUNET_log_setup("test_getopt", "WARNING", NULL);
164 /* suppress output from -h, -v options */ 165 /* suppress output from -h, -v options */
165#ifndef MINGW 166#ifndef MINGW
166 GNUNET_break (0 == close (1)); 167 GNUNET_break(0 == close(1));
167#endif 168#endif
168 if (0 != testMinimal ()) 169 if (0 != testMinimal())
169 errCnt++; 170 errCnt++;
170 if (0 != testVerbose ()) 171 if (0 != testVerbose())
171 errCnt++; 172 errCnt++;
172 if (0 != testVersion ()) 173 if (0 != testVersion())
173 errCnt++; 174 errCnt++;
174 if (0 != testAbout ()) 175 if (0 != testAbout())
175 errCnt++; 176 errCnt++;
176 if (0 != testLogOpts ()) 177 if (0 != testLogOpts())
177 errCnt++; 178 errCnt++;
178 if (0 != testFlagNum ()) 179 if (0 != testFlagNum())
179 errCnt++; 180 errCnt++;
180 return errCnt; 181 return errCnt;
181} 182}
diff --git a/src/util/test_hexcoder.c b/src/util/test_hexcoder.c
index f73989a0e..69e2061cb 100644
--- a/src/util/test_hexcoder.c
+++ b/src/util/test_hexcoder.c
@@ -11,13 +11,13 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 19
20*/ 20 */
21/** 21/**
22 * @author Christian Grothoff 22 * @author Christian Grothoff
23 * @file dns/test_hexcoder.c 23 * @file dns/test_hexcoder.c
@@ -32,23 +32,23 @@
32 32
33 33
34int 34int
35main (int argc, 35main(int argc,
36 char *argv[]) 36 char *argv[])
37{ 37{
38 char buf[strlen (TESTSTRING) + 1]; 38 char buf[strlen(TESTSTRING) + 1];
39 char *ret; 39 char *ret;
40 40
41 GNUNET_log_setup ("test-hexcoder", "WARNING", NULL); 41 GNUNET_log_setup("test-hexcoder", "WARNING", NULL);
42 ret = GNUNET_DNSPARSER_bin_to_hex (TESTSTRING, 42 ret = GNUNET_DNSPARSER_bin_to_hex(TESTSTRING,
43 strlen (TESTSTRING) + 1); 43 strlen(TESTSTRING) + 1);
44 GNUNET_assert (NULL != ret); 44 GNUNET_assert(NULL != ret);
45 GNUNET_assert (sizeof (buf) == 45 GNUNET_assert(sizeof(buf) ==
46 GNUNET_DNSPARSER_hex_to_bin (ret, 46 GNUNET_DNSPARSER_hex_to_bin(ret,
47 buf)); 47 buf));
48 GNUNET_assert (0 == memcmp (TESTSTRING, 48 GNUNET_assert(0 == memcmp(TESTSTRING,
49 buf, 49 buf,
50 sizeof (buf))); 50 sizeof(buf)));
51 GNUNET_free (ret); 51 GNUNET_free(ret);
52 return 0; 52 return 0;
53} 53}
54 54
diff --git a/src/util/test_mq.c b/src/util/test_mq.c
index 9a396bcae..4282f06b7 100644
--- a/src/util/test_mq.c
+++ b/src/util/test_mq.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/test_mq.c 22 * @file util/test_mq.c
@@ -32,15 +32,14 @@
32/** 32/**
33 * How long does the receiver take per message? 33 * How long does the receiver take per message?
34 */ 34 */
35#define RECEIVER_THROTTLE GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 1) 35#define RECEIVER_THROTTLE GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_MILLISECONDS, 1)
36 36
37static unsigned int received_cnt; 37static unsigned int received_cnt;
38 38
39 39
40GNUNET_NETWORK_STRUCT_BEGIN 40GNUNET_NETWORK_STRUCT_BEGIN
41 41
42struct MyMessage 42struct MyMessage {
43{
44 struct GNUNET_MessageHeader header; 43 struct GNUNET_MessageHeader header;
45 uint32_t x GNUNET_PACKED; 44 uint32_t x GNUNET_PACKED;
46}; 45};
@@ -57,28 +56,28 @@ static struct GNUNET_MQ_Handle *cmq;
57 56
58 57
59static void 58static void
60do_shutdown (void *cls) 59do_shutdown(void *cls)
61{ 60{
62 (void) cls; 61 (void)cls;
63 if (NULL != tt) 62 if (NULL != tt)
64 { 63 {
65 GNUNET_SCHEDULER_cancel (tt); 64 GNUNET_SCHEDULER_cancel(tt);
66 tt = NULL; 65 tt = NULL;
67 } 66 }
68 if (NULL != cmq) 67 if (NULL != cmq)
69 { 68 {
70 GNUNET_MQ_destroy (cmq); 69 GNUNET_MQ_destroy(cmq);
71 cmq = NULL; 70 cmq = NULL;
72 } 71 }
73} 72}
74 73
75 74
76static void 75static void
77do_timeout (void *cls) 76do_timeout(void *cls)
78{ 77{
79 (void) cls; 78 (void)cls;
80 tt = NULL; 79 tt = NULL;
81 GNUNET_SCHEDULER_shutdown (); 80 GNUNET_SCHEDULER_shutdown();
82 global_ret = 1; 81 global_ret = 1;
83} 82}
84 83
@@ -93,59 +92,59 @@ do_timeout (void *cls)
93 * @param error error code 92 * @param error error code
94 */ 93 */
95static void 94static void
96error_cb (void *cls, 95error_cb(void *cls,
97 enum GNUNET_MQ_Error error) 96 enum GNUNET_MQ_Error error)
98{ 97{
99 GNUNET_break (0); 98 GNUNET_break(0);
100 global_ret = 3; 99 global_ret = 3;
101 GNUNET_SCHEDULER_shutdown (); 100 GNUNET_SCHEDULER_shutdown();
102} 101}
103 102
104 103
105static void 104static void
106client_continue (void *cls) 105client_continue(void *cls)
107{ 106{
108 struct GNUNET_SERVICE_Client *c = cls; 107 struct GNUNET_SERVICE_Client *c = cls;
109 108
110 dt = NULL; 109 dt = NULL;
111 GNUNET_SERVICE_client_continue (c); 110 GNUNET_SERVICE_client_continue(c);
112} 111}
113 112
114 113
115static void 114static void
116handle_dummy (void *cls, 115handle_dummy(void *cls,
117 const struct MyMessage *msg) 116 const struct MyMessage *msg)
118{ 117{
119 struct GNUNET_SERVICE_Client *c = cls; 118 struct GNUNET_SERVICE_Client *c = cls;
120 119
121 GNUNET_assert (NULL == dt); 120 GNUNET_assert(NULL == dt);
122 /* artificially make receiver slower than sender */ 121 /* artificially make receiver slower than sender */
123 dt = GNUNET_SCHEDULER_add_delayed (RECEIVER_THROTTLE, 122 dt = GNUNET_SCHEDULER_add_delayed(RECEIVER_THROTTLE,
124 &client_continue, 123 &client_continue,
125 c); 124 c);
126 if (received_cnt != ntohl (msg->x)) 125 if (received_cnt != ntohl(msg->x))
127 { 126 {
128 GNUNET_break (0); 127 GNUNET_break(0);
129 global_ret = 4; 128 global_ret = 4;
130 GNUNET_SCHEDULER_shutdown (); 129 GNUNET_SCHEDULER_shutdown();
131 } 130 }
132 received_cnt++; 131 received_cnt++;
133} 132}
134 133
135 134
136static void 135static void
137handle_dummy2 (void *cls, 136handle_dummy2(void *cls,
138 const struct MyMessage *msg) 137 const struct MyMessage *msg)
139{ 138{
140 struct GNUNET_SERVICE_Client *c = cls; 139 struct GNUNET_SERVICE_Client *c = cls;
141 140
142 GNUNET_SERVICE_client_continue (c); 141 GNUNET_SERVICE_client_continue(c);
143 if (NUM_TRANSMISSIONS != received_cnt) 142 if (NUM_TRANSMISSIONS != received_cnt)
144 { 143 {
145 GNUNET_break (0); 144 GNUNET_break(0);
146 global_ret = 5; 145 global_ret = 5;
147 } 146 }
148 GNUNET_SCHEDULER_shutdown (); 147 GNUNET_SCHEDULER_shutdown();
149} 148}
150 149
151 150
@@ -153,19 +152,19 @@ handle_dummy2 (void *cls,
153 * Function called whenever MQ has sent a message. 152 * Function called whenever MQ has sent a message.
154 */ 153 */
155static void 154static void
156notify_sent_cb (void *cls) 155notify_sent_cb(void *cls)
157{ 156{
158 static unsigned int seen; 157 static unsigned int seen;
159 unsigned int *cnt = cls; 158 unsigned int *cnt = cls;
160 159
161 if (seen != *cnt) 160 if (seen != *cnt)
162 { 161 {
163 GNUNET_break (0); 162 GNUNET_break(0);
164 global_ret = 6; 163 global_ret = 6;
165 GNUNET_SCHEDULER_shutdown (); 164 GNUNET_SCHEDULER_shutdown();
166 } 165 }
167 seen++; 166 seen++;
168 GNUNET_free (cnt); 167 GNUNET_free(cnt);
169} 168}
170 169
171 170
@@ -177,47 +176,47 @@ notify_sent_cb (void *cls)
177 * @param sh handle to the newly create service 176 * @param sh handle to the newly create service
178 */ 177 */
179static void 178static void
180run (void *cls, 179run(void *cls,
181 const struct GNUNET_CONFIGURATION_Handle *cfg, 180 const struct GNUNET_CONFIGURATION_Handle *cfg,
182 struct GNUNET_SERVICE_Handle *sh) 181 struct GNUNET_SERVICE_Handle *sh)
183{ 182{
184 struct GNUNET_MQ_MessageHandler ch[] = { 183 struct GNUNET_MQ_MessageHandler ch[] = {
185 GNUNET_MQ_handler_end () 184 GNUNET_MQ_handler_end()
186 }; 185 };
187 struct GNUNET_MQ_Envelope *env; 186 struct GNUNET_MQ_Envelope *env;
188 struct MyMessage *m; 187 struct MyMessage *m;
189 188
190 (void) cls; 189 (void)cls;
191 (void) sh; 190 (void)sh;
192 cmq = GNUNET_CLIENT_connect (cfg, 191 cmq = GNUNET_CLIENT_connect(cfg,
193 "test_client", 192 "test_client",
194 ch, 193 ch,
195 &error_cb, 194 &error_cb,
196 NULL); 195 NULL);
197 GNUNET_SCHEDULER_add_shutdown (&do_shutdown, 196 GNUNET_SCHEDULER_add_shutdown(&do_shutdown,
198 NULL); 197 NULL);
199 tt = GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_MINUTES, 198 tt = GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_MINUTES,
200 &do_timeout, 199 &do_timeout,
201 NULL); 200 NULL);
202 for (unsigned int i=0;i<NUM_TRANSMISSIONS;i++) 201 for (unsigned int i = 0; i < NUM_TRANSMISSIONS; i++)
203 { 202 {
204 unsigned int *cnt; 203 unsigned int *cnt;
205 204
206 cnt = GNUNET_new (unsigned int); 205 cnt = GNUNET_new(unsigned int);
207 *cnt = i; 206 *cnt = i;
208 env = GNUNET_MQ_msg (m, 207 env = GNUNET_MQ_msg(m,
209 GNUNET_MESSAGE_TYPE_DUMMY); 208 GNUNET_MESSAGE_TYPE_DUMMY);
210 GNUNET_MQ_notify_sent (env, 209 GNUNET_MQ_notify_sent(env,
211 &notify_sent_cb, 210 &notify_sent_cb,
212 cnt); 211 cnt);
213 m->x = htonl (i); 212 m->x = htonl(i);
214 GNUNET_MQ_send (cmq, 213 GNUNET_MQ_send(cmq,
215 env); 214 env);
216 } 215 }
217 env = GNUNET_MQ_msg (m, 216 env = GNUNET_MQ_msg(m,
218 GNUNET_MESSAGE_TYPE_DUMMY2); 217 GNUNET_MESSAGE_TYPE_DUMMY2);
219 GNUNET_MQ_send (cmq, 218 GNUNET_MQ_send(cmq,
220 env); 219 env);
221} 220}
222 221
223 222
@@ -230,12 +229,12 @@ run (void *cls,
230 * @return the client-specific (`internal') closure 229 * @return the client-specific (`internal') closure
231 */ 230 */
232static void * 231static void *
233connect_cb (void *cls, 232connect_cb(void *cls,
234 struct GNUNET_SERVICE_Client *c, 233 struct GNUNET_SERVICE_Client *c,
235 struct GNUNET_MQ_Handle *mq) 234 struct GNUNET_MQ_Handle *mq)
236{ 235{
237 (void) cls; 236 (void)cls;
238 (void) mq; 237 (void)mq;
239 return c; 238 return c;
240} 239}
241 240
@@ -248,18 +247,18 @@ connect_cb (void *cls,
248 * @param internal_cls the client-specific (`internal') closure 247 * @param internal_cls the client-specific (`internal') closure
249 */ 248 */
250static void 249static void
251disconnect_cb (void *cls, 250disconnect_cb(void *cls,
252 struct GNUNET_SERVICE_Client *c, 251 struct GNUNET_SERVICE_Client *c,
253 void *internal_cls) 252 void *internal_cls)
254{ 253{
255 (void) cls; 254 (void)cls;
256 (void) c; 255 (void)c;
257 (void) internal_cls; 256 (void)internal_cls;
258} 257}
259 258
260 259
261static void 260static void
262test1 () 261test1()
263{ 262{
264 struct GNUNET_MQ_Envelope *mqm; 263 struct GNUNET_MQ_Envelope *mqm;
265 struct MyMessage *mm; 264 struct MyMessage *mm;
@@ -267,74 +266,74 @@ test1 ()
267 mm = NULL; 266 mm = NULL;
268 mqm = NULL; 267 mqm = NULL;
269 268
270 mqm = GNUNET_MQ_msg (mm, 269 mqm = GNUNET_MQ_msg(mm,
271 GNUNET_MESSAGE_TYPE_DUMMY); 270 GNUNET_MESSAGE_TYPE_DUMMY);
272 GNUNET_assert (NULL != mqm); 271 GNUNET_assert(NULL != mqm);
273 GNUNET_assert (NULL != mm); 272 GNUNET_assert(NULL != mm);
274 GNUNET_assert (GNUNET_MESSAGE_TYPE_DUMMY == ntohs (mm->header.type)); 273 GNUNET_assert(GNUNET_MESSAGE_TYPE_DUMMY == ntohs(mm->header.type));
275 GNUNET_assert (sizeof (struct MyMessage) == ntohs (mm->header.size)); 274 GNUNET_assert(sizeof(struct MyMessage) == ntohs(mm->header.size));
276 GNUNET_MQ_discard (mqm); 275 GNUNET_MQ_discard(mqm);
277} 276}
278 277
279 278
280static void 279static void
281test2 () 280test2()
282{ 281{
283 struct GNUNET_MQ_Envelope *mqm; 282 struct GNUNET_MQ_Envelope *mqm;
284 struct GNUNET_MessageHeader *mh; 283 struct GNUNET_MessageHeader *mh;
285 284
286 mqm = GNUNET_MQ_msg_header (GNUNET_MESSAGE_TYPE_DUMMY); 285 mqm = GNUNET_MQ_msg_header(GNUNET_MESSAGE_TYPE_DUMMY);
287 /* how could the above be checked? */ 286 /* how could the above be checked? */
288 287
289 GNUNET_MQ_discard (mqm); 288 GNUNET_MQ_discard(mqm);
290 289
291 mqm = GNUNET_MQ_msg_header_extra (mh, 290 mqm = GNUNET_MQ_msg_header_extra(mh,
292 20, 291 20,
293 GNUNET_MESSAGE_TYPE_DUMMY); 292 GNUNET_MESSAGE_TYPE_DUMMY);
294 GNUNET_assert (GNUNET_MESSAGE_TYPE_DUMMY == ntohs (mh->type)); 293 GNUNET_assert(GNUNET_MESSAGE_TYPE_DUMMY == ntohs(mh->type));
295 GNUNET_assert (sizeof (struct GNUNET_MessageHeader) + 20 == ntohs (mh->size)); 294 GNUNET_assert(sizeof(struct GNUNET_MessageHeader) + 20 == ntohs(mh->size));
296 GNUNET_MQ_discard (mqm); 295 GNUNET_MQ_discard(mqm);
297} 296}
298 297
299 298
300int 299int
301main (int argc, char **argv) 300main(int argc, char **argv)
302{ 301{
303 char * test_argv[] = { 302 char * test_argv[] = {
304 (char *) "test_client", 303 (char *)"test_client",
305 "-c", 304 "-c",
306 "test_client_data.conf", 305 "test_client_data.conf",
307 NULL 306 NULL
308 }; 307 };
309 struct GNUNET_MQ_MessageHandler mh[] = { 308 struct GNUNET_MQ_MessageHandler mh[] = {
310 GNUNET_MQ_hd_fixed_size (dummy, 309 GNUNET_MQ_hd_fixed_size(dummy,
311 GNUNET_MESSAGE_TYPE_DUMMY, 310 GNUNET_MESSAGE_TYPE_DUMMY,
312 struct MyMessage, 311 struct MyMessage,
313 NULL), 312 NULL),
314 GNUNET_MQ_hd_fixed_size (dummy2, 313 GNUNET_MQ_hd_fixed_size(dummy2,
315 GNUNET_MESSAGE_TYPE_DUMMY2, 314 GNUNET_MESSAGE_TYPE_DUMMY2,
316 struct MyMessage, 315 struct MyMessage,
317 NULL), 316 NULL),
318 GNUNET_MQ_handler_end () 317 GNUNET_MQ_handler_end()
319 }; 318 };
320 319
321 (void) argc; 320 (void)argc;
322 (void) argv; 321 (void)argv;
323 GNUNET_log_setup ("test-mq", 322 GNUNET_log_setup("test-mq",
324 "INFO", 323 "INFO",
325 NULL); 324 NULL);
326 test1 (); 325 test1();
327 test2 (); 326 test2();
328 if (0 != 327 if (0 !=
329 GNUNET_SERVICE_run_ (3, 328 GNUNET_SERVICE_run_(3,
330 test_argv, 329 test_argv,
331 "test_client", 330 "test_client",
332 GNUNET_SERVICE_OPTION_NONE, 331 GNUNET_SERVICE_OPTION_NONE,
333 &run, 332 &run,
334 &connect_cb, 333 &connect_cb,
335 &disconnect_cb, 334 &disconnect_cb,
336 NULL, 335 NULL,
337 mh)) 336 mh))
338 return 1; 337 return 1;
339 return global_ret; 338 return global_ret;
340} 339}
diff --git a/src/util/test_os_network.c b/src/util/test_os_network.c
index fa769de6f..f6b0e3482 100644
--- a/src/util/test_os_network.c
+++ b/src/util/test_os_network.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_os_network.c 21 * @file util/test_os_network.c
22 * @brief testcase for util/os_network.c 22 * @brief testcase for util/os_network.c
@@ -31,13 +31,13 @@
31 * (success). 31 * (success).
32 */ 32 */
33static int 33static int
34proc (void *cls, 34proc(void *cls,
35 const char *name, 35 const char *name,
36 int isDefault, 36 int isDefault,
37 const struct sockaddr *addr, 37 const struct sockaddr *addr,
38 const struct sockaddr *broadcast_addr, 38 const struct sockaddr *broadcast_addr,
39 const struct sockaddr *netmask, 39 const struct sockaddr *netmask,
40 socklen_t addrlen) 40 socklen_t addrlen)
41{ 41{
42 int *ok = cls; 42 int *ok = cls;
43 char buf[INET6_ADDRSTRLEN]; 43 char buf[INET6_ADDRSTRLEN];
@@ -45,45 +45,45 @@ proc (void *cls,
45 45
46 if (NULL == addr) 46 if (NULL == addr)
47 return GNUNET_OK; 47 return GNUNET_OK;
48 if (addrlen == sizeof (struct sockaddr_in)) 48 if (addrlen == sizeof(struct sockaddr_in))
49 protocol = "IPv4"; 49 protocol = "IPv4";
50 else 50 else
51 protocol = "IPv6"; 51 protocol = "IPv6";
52 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 52 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
53 "%s Address `%s'\n", 53 "%s Address `%s'\n",
54 protocol, 54 protocol,
55 GNUNET_a2s ((const struct sockaddr *) addr, 55 GNUNET_a2s((const struct sockaddr *)addr,
56 addrlen) ); 56 addrlen));
57 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 57 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
58 "Netmask `%s'\n", 58 "Netmask `%s'\n",
59 GNUNET_a2s ((const struct sockaddr *) netmask, 59 GNUNET_a2s((const struct sockaddr *)netmask,
60 addrlen) ); 60 addrlen));
61 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 61 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
62 "`%s'\n", 62 "`%s'\n",
63 GNUNET_a2s ((const struct sockaddr *) broadcast_addr, 63 GNUNET_a2s((const struct sockaddr *)broadcast_addr,
64 addrlen) ); 64 addrlen));
65 inet_ntop (addr->sa_family, 65 inet_ntop(addr->sa_family,
66 (addr->sa_family == 66 (addr->sa_family ==
67 AF_INET) ? (void *) &((struct sockaddr_in *) addr)->sin_addr 67 AF_INET) ? (void *)&((struct sockaddr_in *)addr)->sin_addr
68 : (void *) &((struct sockaddr_in6 *) addr)->sin6_addr, buf, 68 : (void *)&((struct sockaddr_in6 *)addr)->sin6_addr, buf,
69 sizeof (buf)); 69 sizeof(buf));
70 if ((0 == strcmp ("::1", buf)) || (0 == strcmp ("127.0.0.1", buf))) 70 if ((0 == strcmp("::1", buf)) || (0 == strcmp("127.0.0.1", buf)))
71 *ok = 0; 71 *ok = 0;
72 return GNUNET_OK; 72 return GNUNET_OK;
73} 73}
74 74
75 75
76int 76int
77main (int argc, char *argv[]) 77main(int argc, char *argv[])
78{ 78{
79 int ret; 79 int ret;
80 80
81 GNUNET_log_setup ("test-os-network", 81 GNUNET_log_setup("test-os-network",
82 "WARNING", 82 "WARNING",
83 NULL); 83 NULL);
84 ret = 1; 84 ret = 1;
85 GNUNET_OS_network_interfaces_list (&proc, 85 GNUNET_OS_network_interfaces_list(&proc,
86 &ret); 86 &ret);
87 return ret; 87 return ret;
88} 88}
89 89
diff --git a/src/util/test_os_start_process.c b/src/util/test_os_start_process.c
index 826e5744c..4efbe91af 100644
--- a/src/util/test_os_start_process.c
+++ b/src/util/test_os_start_process.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_os_start_process.c 21 * @file util/test_os_start_process.c
22 * @brief testcase for os start process code 22 * @brief testcase for os start process code
@@ -48,8 +48,7 @@ static struct GNUNET_DISK_PipeHandle *hello_pipe_stdout;
48 48
49static struct GNUNET_SCHEDULER_Task * die_task; 49static struct GNUNET_SCHEDULER_Task * die_task;
50 50
51struct read_context 51struct read_context {
52{
53 char buf[16]; 52 char buf[16];
54 int buf_offset; 53 int buf_offset;
55 const struct GNUNET_DISK_FileHandle *stdout_read_handle; 54 const struct GNUNET_DISK_FileHandle *stdout_read_handle;
@@ -60,126 +59,126 @@ static struct read_context rc;
60 59
61 60
62static void 61static void
63end_task (void *cls) 62end_task(void *cls)
64{ 63{
65 if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG)) 64 if (0 != GNUNET_OS_process_kill(proc, GNUNET_TERM_SIG))
66 { 65 {
67 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); 66 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
68 } 67 }
69 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (proc)); 68 GNUNET_assert(GNUNET_OK == GNUNET_OS_process_wait(proc));
70 GNUNET_OS_process_destroy (proc); 69 GNUNET_OS_process_destroy(proc);
71 proc = NULL; 70 proc = NULL;
72 GNUNET_DISK_pipe_close (hello_pipe_stdout); 71 GNUNET_DISK_pipe_close(hello_pipe_stdout);
73 GNUNET_DISK_pipe_close (hello_pipe_stdin); 72 GNUNET_DISK_pipe_close(hello_pipe_stdin);
74} 73}
75 74
76 75
77static void 76static void
78read_call (void *cls) 77read_call(void *cls)
79{ 78{
80 int bytes; 79 int bytes;
81 80
82 bytes = GNUNET_DISK_file_read (rc.stdout_read_handle, 81 bytes = GNUNET_DISK_file_read(rc.stdout_read_handle,
83 &rc.buf[rc.buf_offset], 82 &rc.buf[rc.buf_offset],
84 sizeof (rc.buf) - rc.buf_offset); 83 sizeof(rc.buf) - rc.buf_offset);
85 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 84 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
86 "bytes is %d\n", 85 "bytes is %d\n",
87 bytes); 86 bytes);
88 87
89 if (bytes < 1) 88 if (bytes < 1)
90 { 89 {
91 GNUNET_break (0); 90 GNUNET_break(0);
92 ok = 1; 91 ok = 1;
93 GNUNET_SCHEDULER_cancel (die_task); 92 GNUNET_SCHEDULER_cancel(die_task);
94 (void) GNUNET_SCHEDULER_add_now (&end_task, NULL); 93 (void)GNUNET_SCHEDULER_add_now(&end_task, NULL);
95 return; 94 return;
96 } 95 }
97 96
98 ok = strncmp (rc.buf, test_phrase, strlen (test_phrase)); 97 ok = strncmp(rc.buf, test_phrase, strlen(test_phrase));
99 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 98 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
100 "read %s\n", 99 "read %s\n",
101 &rc.buf[rc.buf_offset]); 100 &rc.buf[rc.buf_offset]);
102 rc.buf_offset += bytes; 101 rc.buf_offset += bytes;
103 102
104 if (0 == ok) 103 if (0 == ok)
105 { 104 {
106 GNUNET_SCHEDULER_cancel (die_task); 105 GNUNET_SCHEDULER_cancel(die_task);
107 (void) GNUNET_SCHEDULER_add_now (&end_task, NULL); 106 (void)GNUNET_SCHEDULER_add_now(&end_task, NULL);
108 return; 107 return;
109 } 108 }
110 109
111 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 110 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
112 rc.stdout_read_handle, 111 rc.stdout_read_handle,
113 &read_call, 112 &read_call,
114 NULL); 113 NULL);
115} 114}
116 115
117 116
118static void 117static void
119run_task (void *cls) 118run_task(void *cls)
120{ 119{
121 char *fn; 120 char *fn;
122 const struct GNUNET_DISK_FileHandle *stdout_read_handle; 121 const struct GNUNET_DISK_FileHandle *stdout_read_handle;
123 const struct GNUNET_DISK_FileHandle *wh; 122 const struct GNUNET_DISK_FileHandle *wh;
124 123
125#if !WINDOWS 124#if !WINDOWS
126 GNUNET_asprintf (&fn, "cat"); 125 GNUNET_asprintf(&fn, "cat");
127#else 126#else
128 GNUNET_asprintf (&fn, "w32cat"); 127 GNUNET_asprintf(&fn, "w32cat");
129#endif 128#endif
130 129
131 hello_pipe_stdin = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO); 130 hello_pipe_stdin = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
132 hello_pipe_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 131 hello_pipe_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
133 132
134 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL)) 133 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL))
135 { 134 {
136 GNUNET_break (0); 135 GNUNET_break(0);
137 ok = 1; 136 ok = 1;
138 GNUNET_free (fn); 137 GNUNET_free(fn);
139 return; 138 return;
140 } 139 }
141 140
142 proc = 141 proc =
143 GNUNET_OS_start_process (GNUNET_NO, GNUNET_OS_INHERIT_STD_ERR, 142 GNUNET_OS_start_process(GNUNET_NO, GNUNET_OS_INHERIT_STD_ERR,
144 hello_pipe_stdin, hello_pipe_stdout, NULL, 143 hello_pipe_stdin, hello_pipe_stdout, NULL,
145 fn, 144 fn,
146 "test_gnunet_echo_hello", "-", NULL); 145 "test_gnunet_echo_hello", "-", NULL);
147 GNUNET_free (fn); 146 GNUNET_free(fn);
148 147
149 /* Close the write end of the read pipe */ 148 /* Close the write end of the read pipe */
150 GNUNET_DISK_pipe_close_end (hello_pipe_stdout, GNUNET_DISK_PIPE_END_WRITE); 149 GNUNET_DISK_pipe_close_end(hello_pipe_stdout, GNUNET_DISK_PIPE_END_WRITE);
151 /* Close the read end of the write pipe */ 150 /* Close the read end of the write pipe */
152 GNUNET_DISK_pipe_close_end (hello_pipe_stdin, GNUNET_DISK_PIPE_END_READ); 151 GNUNET_DISK_pipe_close_end(hello_pipe_stdin, GNUNET_DISK_PIPE_END_READ);
153 152
154 wh = GNUNET_DISK_pipe_handle (hello_pipe_stdin, GNUNET_DISK_PIPE_END_WRITE); 153 wh = GNUNET_DISK_pipe_handle(hello_pipe_stdin, GNUNET_DISK_PIPE_END_WRITE);
155 154
156 /* Write the test_phrase to the cat process */ 155 /* Write the test_phrase to the cat process */
157 if (GNUNET_DISK_file_write (wh, test_phrase, strlen (test_phrase) + 1) != 156 if (GNUNET_DISK_file_write(wh, test_phrase, strlen(test_phrase) + 1) !=
158 strlen (test_phrase) + 1) 157 strlen(test_phrase) + 1)
159 { 158 {
160 GNUNET_break (0); 159 GNUNET_break(0);
161 ok = 1; 160 ok = 1;
162 return; 161 return;
163 } 162 }
164 163
165 /* Close the write end to end the cycle! */ 164 /* Close the write end to end the cycle! */
166 GNUNET_DISK_pipe_close_end (hello_pipe_stdin, GNUNET_DISK_PIPE_END_WRITE); 165 GNUNET_DISK_pipe_close_end(hello_pipe_stdin, GNUNET_DISK_PIPE_END_WRITE);
167 166
168 stdout_read_handle = 167 stdout_read_handle =
169 GNUNET_DISK_pipe_handle (hello_pipe_stdout, GNUNET_DISK_PIPE_END_READ); 168 GNUNET_DISK_pipe_handle(hello_pipe_stdout, GNUNET_DISK_PIPE_END_READ);
170 169
171 die_task = 170 die_task =
172 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply 171 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply
173 (GNUNET_TIME_UNIT_MINUTES, 1), 172 (GNUNET_TIME_UNIT_MINUTES, 1),
174 &end_task, 173 &end_task,
175 NULL); 174 NULL);
176 175
177 memset (&rc, 0, sizeof (rc)); 176 memset(&rc, 0, sizeof(rc));
178 rc.stdout_read_handle = stdout_read_handle; 177 rc.stdout_read_handle = stdout_read_handle;
179 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 178 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
180 stdout_read_handle, 179 stdout_read_handle,
181 &read_call, 180 &read_call,
182 NULL); 181 NULL);
183} 182}
184 183
185 184
@@ -188,10 +187,10 @@ run_task (void *cls)
188 * checks that "ok" is correct at the end. 187 * checks that "ok" is correct at the end.
189 */ 188 */
190static int 189static int
191check_run () 190check_run()
192{ 191{
193 ok = 1; 192 ok = 1;
194 GNUNET_SCHEDULER_run (&run_task, &ok); 193 GNUNET_SCHEDULER_run(&run_task, &ok);
195 return ok; 194 return ok;
196} 195}
197 196
@@ -200,40 +199,40 @@ check_run ()
200 * Test killing via pipe. 199 * Test killing via pipe.
201 */ 200 */
202static int 201static int
203check_kill () 202check_kill()
204{ 203{
205 char *fn; 204 char *fn;
206 205
207 hello_pipe_stdin = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO); 206 hello_pipe_stdin = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
208 hello_pipe_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 207 hello_pipe_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
209 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL)) 208 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL))
210 { 209 {
211 return 1; 210 return 1;
212 } 211 }
213 fn = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver"); 212 fn = GNUNET_OS_get_libexec_binary_path("gnunet-service-resolver");
214 proc = 213 proc =
215 GNUNET_OS_start_process (GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR, 214 GNUNET_OS_start_process(GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR,
216 hello_pipe_stdin, 215 hello_pipe_stdin,
217 hello_pipe_stdout, 216 hello_pipe_stdout,
218 NULL, 217 NULL,
219 fn, 218 fn,
220 "gnunet-service-resolver", "-", 219 "gnunet-service-resolver", "-",
221 NULL); 220 NULL);
222 if (NULL == proc) 221 if (NULL == proc)
223 { 222 {
224 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 223 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
225 "Failed to launch gnunet-service-resolver. Is your system setup correct?\n"); 224 "Failed to launch gnunet-service-resolver. Is your system setup correct?\n");
226 return 77; 225 return 77;
227 } 226 }
228 sleep (1); /* give process time to start, so we actually use the pipe-kill mechanism! */ 227 sleep(1); /* give process time to start, so we actually use the pipe-kill mechanism! */
229 GNUNET_free (fn); 228 GNUNET_free(fn);
230 if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG)) 229 if (0 != GNUNET_OS_process_kill(proc, GNUNET_TERM_SIG))
231 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); 230 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
232 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (proc)); 231 GNUNET_assert(GNUNET_OK == GNUNET_OS_process_wait(proc));
233 GNUNET_OS_process_destroy (proc); 232 GNUNET_OS_process_destroy(proc);
234 proc = NULL; 233 proc = NULL;
235 GNUNET_DISK_pipe_close (hello_pipe_stdout); 234 GNUNET_DISK_pipe_close(hello_pipe_stdout);
236 GNUNET_DISK_pipe_close (hello_pipe_stdin); 235 GNUNET_DISK_pipe_close(hello_pipe_stdin);
237 return 0; 236 return 0;
238} 237}
239 238
@@ -242,55 +241,55 @@ check_kill ()
242 * Test killing via pipe. 241 * Test killing via pipe.
243 */ 242 */
244static int 243static int
245check_instant_kill () 244check_instant_kill()
246{ 245{
247 char *fn; 246 char *fn;
248 247
249 hello_pipe_stdin = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO); 248 hello_pipe_stdin = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_YES, GNUNET_NO);
250 hello_pipe_stdout = GNUNET_DISK_pipe (GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES); 249 hello_pipe_stdout = GNUNET_DISK_pipe(GNUNET_YES, GNUNET_YES, GNUNET_NO, GNUNET_YES);
251 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL)) 250 if ((hello_pipe_stdout == NULL) || (hello_pipe_stdin == NULL))
252 { 251 {
253 return 1; 252 return 1;
254 } 253 }
255 fn = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver"); 254 fn = GNUNET_OS_get_libexec_binary_path("gnunet-service-resolver");
256 proc = 255 proc =
257 GNUNET_OS_start_process (GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR, 256 GNUNET_OS_start_process(GNUNET_YES, GNUNET_OS_INHERIT_STD_ERR,
258 hello_pipe_stdin, hello_pipe_stdout, NULL, 257 hello_pipe_stdin, hello_pipe_stdout, NULL,
259 fn, 258 fn,
260 "gnunet-service-resolver", "-", NULL); 259 "gnunet-service-resolver", "-", NULL);
261 if (NULL == proc) 260 if (NULL == proc)
262 { 261 {
263 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 262 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
264 "Failed to launch gnunet-service-resolver. Is your system setup correct?\n"); 263 "Failed to launch gnunet-service-resolver. Is your system setup correct?\n");
265 return 77; 264 return 77;
266 } 265 }
267 if (0 != GNUNET_OS_process_kill (proc, 266 if (0 != GNUNET_OS_process_kill(proc,
268 GNUNET_TERM_SIG)) 267 GNUNET_TERM_SIG))
269 { 268 {
270 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); 269 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
271 } 270 }
272 GNUNET_free (fn); 271 GNUNET_free(fn);
273 GNUNET_assert (GNUNET_OK == GNUNET_OS_process_wait (proc)); 272 GNUNET_assert(GNUNET_OK == GNUNET_OS_process_wait(proc));
274 GNUNET_OS_process_destroy (proc); 273 GNUNET_OS_process_destroy(proc);
275 proc = NULL; 274 proc = NULL;
276 GNUNET_DISK_pipe_close (hello_pipe_stdout); 275 GNUNET_DISK_pipe_close(hello_pipe_stdout);
277 GNUNET_DISK_pipe_close (hello_pipe_stdin); 276 GNUNET_DISK_pipe_close(hello_pipe_stdin);
278 return 0; 277 return 0;
279} 278}
280 279
281 280
282int 281int
283main (int argc, char *argv[]) 282main(int argc, char *argv[])
284{ 283{
285 int ret; 284 int ret;
286 285
287 GNUNET_log_setup ("test-os-start-process", 286 GNUNET_log_setup("test-os-start-process",
288 "WARNING", 287 "WARNING",
289 NULL); 288 NULL);
290 ret = 0; 289 ret = 0;
291 ret |= check_run (); 290 ret |= check_run();
292 ret |= check_kill (); 291 ret |= check_kill();
293 ret |= check_instant_kill (); 292 ret |= check_instant_kill();
294 return ret; 293 return ret;
295} 294}
296 295
diff --git a/src/util/test_peer.c b/src/util/test_peer.c
index b059f2cf3..46a803e39 100644
--- a/src/util/test_peer.c
+++ b/src/util/test_peer.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_peer.c 21 * @file util/test_peer.c
22 * @brief testcase for peer.c 22 * @brief testcase for peer.c
@@ -36,102 +36,102 @@ static struct GNUNET_PeerIdentity pidArr[NUMBER_OF_PEERS];
36 36
37 37
38static void 38static void
39generatePeerIdList () 39generatePeerIdList()
40{ 40{
41 for (unsigned int i = 0; i < NUMBER_OF_PEERS; i++) 41 for (unsigned int i = 0; i < NUMBER_OF_PEERS; i++)
42 { 42 {
43 gcry_randomize (&pidArr[i], 43 gcry_randomize(&pidArr[i],
44 sizeof (struct GNUNET_PeerIdentity), 44 sizeof(struct GNUNET_PeerIdentity),
45 GCRY_STRONG_RANDOM); 45 GCRY_STRONG_RANDOM);
46 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 46 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
47 "Peer %u: %s\n", 47 "Peer %u: %s\n",
48 i, 48 i,
49 GNUNET_i2s (&pidArr[i])); 49 GNUNET_i2s(&pidArr[i]));
50 } 50 }
51} 51}
52 52
53 53
54static int 54static int
55check () 55check()
56{ 56{
57 GNUNET_PEER_Id pid; 57 GNUNET_PEER_Id pid;
58 struct GNUNET_PeerIdentity res; 58 struct GNUNET_PeerIdentity res;
59 GNUNET_PEER_Id ids[] = { 1, 2, 3 }; 59 GNUNET_PEER_Id ids[] = { 1, 2, 3 };
60 60
61 GNUNET_assert (0 == GNUNET_PEER_intern (NULL)); 61 GNUNET_assert(0 == GNUNET_PEER_intern(NULL));
62 /* Insert Peers into PeerEntry table and hashmap */ 62 /* Insert Peers into PeerEntry table and hashmap */
63 for (unsigned int i = 0; i < NUMBER_OF_PEERS; i++) 63 for (unsigned int i = 0; i < NUMBER_OF_PEERS; i++)
64 {
65 pid = GNUNET_PEER_intern (&pidArr[i]);
66 if (pid != (i + 1))
67 { 64 {
68 fprintf (stderr, "%s", "Unexpected Peer ID returned by intern function\n"); 65 pid = GNUNET_PEER_intern(&pidArr[i]);
69 return 1; 66 if (pid != (i + 1))
67 {
68 fprintf(stderr, "%s", "Unexpected Peer ID returned by intern function\n");
69 return 1;
70 }
70 } 71 }
71 }
72 72
73 /* Referencing the first 3 peers once again */ 73 /* Referencing the first 3 peers once again */
74 for (unsigned int i = 0; i < 3; i++) 74 for (unsigned int i = 0; i < 3; i++)
75 {
76 pid = GNUNET_PEER_intern (&pidArr[i]);
77 if (pid != (i + 1))
78 { 75 {
79 fprintf (stderr, "%s", "Unexpected Peer ID returned by intern function\n"); 76 pid = GNUNET_PEER_intern(&pidArr[i]);
80 return 1; 77 if (pid != (i + 1))
78 {
79 fprintf(stderr, "%s", "Unexpected Peer ID returned by intern function\n");
80 return 1;
81 }
81 } 82 }
82 }
83 83
84 /* Dereferencing the first 3 peers once [decrementing their reference count] */ 84 /* Dereferencing the first 3 peers once [decrementing their reference count] */
85 GNUNET_PEER_decrement_rcs (ids, 3); 85 GNUNET_PEER_decrement_rcs(ids, 3);
86 86
87 /* re-referencing the first 3 peers using the change_rc function */ 87 /* re-referencing the first 3 peers using the change_rc function */
88 for (unsigned int i = 1; i <= 3; i++) 88 for (unsigned int i = 1; i <= 3; i++)
89 GNUNET_PEER_change_rc (i, 1); 89 GNUNET_PEER_change_rc(i, 1);
90 90
91 /* Removing the second Peer from the PeerEntry hash map */ 91 /* Removing the second Peer from the PeerEntry hash map */
92 GNUNET_PEER_change_rc (2, -2); 92 GNUNET_PEER_change_rc(2, -2);
93 93
94 /* convert the pid of the first PeerEntry into that of the third */ 94 /* convert the pid of the first PeerEntry into that of the third */
95 GNUNET_PEER_resolve (1, 95 GNUNET_PEER_resolve(1,
96 &res); 96 &res);
97 GNUNET_assert (0 == 97 GNUNET_assert(0 ==
98 GNUNET_memcmp (&res, 98 GNUNET_memcmp(&res,
99 &pidArr[0])); 99 &pidArr[0]));
100 100
101 /* 101 /*
102 * Attempt to convert pid = 0 (which is reserved) 102 * Attempt to convert pid = 0 (which is reserved)
103 * into a peer identity object, the peer identity memory 103 * into a peer identity object, the peer identity memory
104 * is expected to be set to zero 104 * is expected to be set to zero
105 */ 105 */
106 GNUNET_log_skip (1, GNUNET_YES); 106 GNUNET_log_skip(1, GNUNET_YES);
107 GNUNET_PEER_resolve (0, &res); 107 GNUNET_PEER_resolve(0, &res);
108 GNUNET_assert (0 == 108 GNUNET_assert(0 ==
109 GNUNET_is_zero (&res)); 109 GNUNET_is_zero(&res));
110 110
111 /* Removing peer entries 1 and 3 from table using the list decrement function */ 111 /* Removing peer entries 1 and 3 from table using the list decrement function */
112 /* If count = 0, nothing should be done whatsoever */ 112 /* If count = 0, nothing should be done whatsoever */
113 GNUNET_PEER_decrement_rcs (ids, 0); 113 GNUNET_PEER_decrement_rcs(ids, 0);
114 114
115 ids[1] = 3; 115 ids[1] = 3;
116 GNUNET_PEER_decrement_rcs (ids, 2); 116 GNUNET_PEER_decrement_rcs(ids, 2);
117 GNUNET_PEER_decrement_rcs (ids, 2); 117 GNUNET_PEER_decrement_rcs(ids, 2);
118 118
119 return 0; 119 return 0;
120} 120}
121 121
122 122
123int 123int
124main () 124main()
125{ 125{
126 GNUNET_log_setup ("test-peer", 126 GNUNET_log_setup("test-peer",
127 "ERROR", 127 "ERROR",
128 NULL); 128 NULL);
129 for (unsigned int i = 0; i < 1; i++) 129 for (unsigned int i = 0; i < 1; i++)
130 { 130 {
131 generatePeerIdList (); 131 generatePeerIdList();
132 if (0 != check ()) 132 if (0 != check())
133 return 1; 133 return 1;
134 } 134 }
135 return 0; 135 return 0;
136} 136}
137 137
diff --git a/src/util/test_plugin.c b/src/util/test_plugin.c
index 04dcdf213..98e6173d5 100644
--- a/src/util/test_plugin.c
+++ b/src/util/test_plugin.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_plugin.c 21 * @file util/test_plugin.c
22 * @brief testcase for plugin.c 22 * @brief testcase for plugin.c
@@ -26,42 +26,42 @@
26 26
27 27
28static void 28static void
29test_cb (void *cls, const char *libname, void *lib_ret) 29test_cb(void *cls, const char *libname, void *lib_ret)
30{ 30{
31 void *ret; 31 void *ret;
32 32
33 GNUNET_assert (0 == strcmp (cls, "test")); 33 GNUNET_assert(0 == strcmp(cls, "test"));
34 GNUNET_assert (0 == strcmp (lib_ret, "Hello")); 34 GNUNET_assert(0 == strcmp(lib_ret, "Hello"));
35 ret = GNUNET_PLUGIN_unload (libname, "out"); 35 ret = GNUNET_PLUGIN_unload(libname, "out");
36 GNUNET_assert (NULL != ret); 36 GNUNET_assert(NULL != ret);
37 GNUNET_assert (0 == strcmp (ret, "World")); 37 GNUNET_assert(0 == strcmp(ret, "World"));
38 free (ret); 38 free(ret);
39} 39}
40 40
41 41
42int 42int
43main (int argc, char *argv[]) 43main(int argc, char *argv[])
44{ 44{
45 void *ret; 45 void *ret;
46 46
47 GNUNET_log_setup ("test-plugin", "WARNING", NULL); 47 GNUNET_log_setup("test-plugin", "WARNING", NULL);
48 GNUNET_log_skip (1, GNUNET_NO); 48 GNUNET_log_skip(1, GNUNET_NO);
49 ret = GNUNET_PLUGIN_load ("libgnunet_plugin_missing", NULL); 49 ret = GNUNET_PLUGIN_load("libgnunet_plugin_missing", NULL);
50 GNUNET_log_skip (0, GNUNET_NO); 50 GNUNET_log_skip(0, GNUNET_NO);
51 if (ret != NULL) 51 if (ret != NULL)
52 return 1; 52 return 1;
53 ret = GNUNET_PLUGIN_load ("libgnunet_plugin_test", "in"); 53 ret = GNUNET_PLUGIN_load("libgnunet_plugin_test", "in");
54 if (ret == NULL) 54 if (ret == NULL)
55 return 1; 55 return 1;
56 if (0 != strcmp (ret, "Hello")) 56 if (0 != strcmp(ret, "Hello"))
57 return 2; 57 return 2;
58 ret = GNUNET_PLUGIN_unload ("libgnunet_plugin_test", "out"); 58 ret = GNUNET_PLUGIN_unload("libgnunet_plugin_test", "out");
59 if (ret == NULL) 59 if (ret == NULL)
60 return 3; 60 return 3;
61 if (0 != strcmp (ret, "World")) 61 if (0 != strcmp(ret, "World"))
62 return 4; 62 return 4;
63 free (ret); 63 free(ret);
64 GNUNET_PLUGIN_load_all ("libgnunet_plugin_tes", "in", &test_cb, "test"); 64 GNUNET_PLUGIN_load_all("libgnunet_plugin_tes", "in", &test_cb, "test");
65 return 0; 65 return 0;
66} 66}
67 67
diff --git a/src/util/test_plugin_plug.c b/src/util/test_plugin_plug.c
index deb36b0a0..f719a075f 100644
--- a/src/util/test_plugin_plug.c
+++ b/src/util/test_plugin_plug.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_plugin_plug.c 21 * @file util/test_plugin_plug.c
22 * @brief plugin for testing 22 * @brief plugin for testing
@@ -24,18 +24,18 @@
24#include "platform.h" 24#include "platform.h"
25 25
26void * 26void *
27libgnunet_plugin_test_init (void *arg) 27libgnunet_plugin_test_init(void *arg)
28{ 28{
29 if (0 == strcmp (arg, "in")) 29 if (0 == strcmp(arg, "in"))
30 return "Hello"; 30 return "Hello";
31 return NULL; 31 return NULL;
32} 32}
33 33
34void * 34void *
35libgnunet_plugin_test_done (void *arg) 35libgnunet_plugin_test_done(void *arg)
36{ 36{
37 if (0 == strcmp (arg, "out")) 37 if (0 == strcmp(arg, "out"))
38 return strdup ("World"); 38 return strdup("World");
39 return NULL; 39 return NULL;
40} 40}
41 41
diff --git a/src/util/test_program.c b/src/util/test_program.c
index a9b3b064a..983610f2e 100644
--- a/src/util/test_program.c
+++ b/src/util/test_program.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_program.c 21 * @file util/test_program.c
22 * @brief tests for program.c 22 * @brief tests for program.c
@@ -34,23 +34,23 @@ static int setme2;
34 * Main function that will be run. 34 * Main function that will be run.
35 */ 35 */
36static void 36static void
37runner (void *cls, 37runner(void *cls,
38 char *const *args, 38 char *const *args,
39 const char *cfgfile, 39 const char *cfgfile,
40 const struct GNUNET_CONFIGURATION_Handle *cfg) 40 const struct GNUNET_CONFIGURATION_Handle *cfg)
41{ 41{
42 int *ok = cls; 42 int *ok = cls;
43 43
44 GNUNET_assert (setme1 == 1); 44 GNUNET_assert(setme1 == 1);
45 GNUNET_assert (0 == strcmp (args[0], "extra")); 45 GNUNET_assert(0 == strcmp(args[0], "extra"));
46 GNUNET_assert (args[1] == NULL); 46 GNUNET_assert(args[1] == NULL);
47 GNUNET_assert (NULL != strstr (cfgfile, "/test_program_data.conf")); 47 GNUNET_assert(NULL != strstr(cfgfile, "/test_program_data.conf"));
48 *ok = 0; 48 *ok = 0;
49} 49}
50 50
51 51
52int 52int
53main (int argc, char *argv[]) 53main(int argc, char *argv[])
54{ 54{
55 int ok = 1; 55 int ok = 1;
56 char *const argvx[] = { 56 char *const argvx[] = {
@@ -64,72 +64,72 @@ main (int argc, char *argv[])
64 NULL 64 NULL
65 }; 65 };
66 struct GNUNET_GETOPT_CommandLineOption options1[] = { 66 struct GNUNET_GETOPT_CommandLineOption options1[] = {
67 GNUNET_GETOPT_option_flag ('n', 67 GNUNET_GETOPT_option_flag('n',
68 "name", 68 "name",
69 "description", 69 "description",
70 &setme1), 70 &setme1),
71 GNUNET_GETOPT_OPTION_END 71 GNUNET_GETOPT_OPTION_END
72 }; 72 };
73 struct GNUNET_GETOPT_CommandLineOption options2[] = { 73 struct GNUNET_GETOPT_CommandLineOption options2[] = {
74 GNUNET_GETOPT_option_flag ('n', 74 GNUNET_GETOPT_option_flag('n',
75 "name", 75 "name",
76 "description", 76 "description",
77 &setme1), 77 &setme1),
78 GNUNET_GETOPT_option_flag ('N', 78 GNUNET_GETOPT_option_flag('N',
79 "number", 79 "number",
80 "description", 80 "description",
81 &setme2), 81 &setme2),
82 GNUNET_GETOPT_OPTION_END 82 GNUNET_GETOPT_OPTION_END
83 }; 83 };
84 struct GNUNET_GETOPT_CommandLineOption options3[] = { 84 struct GNUNET_GETOPT_CommandLineOption options3[] = {
85 GNUNET_GETOPT_option_flag ('N', 85 GNUNET_GETOPT_option_flag('N',
86 "number", 86 "number",
87 "description", 87 "description",
88 &setme1), 88 &setme1),
89 GNUNET_GETOPT_option_flag ('n', 89 GNUNET_GETOPT_option_flag('n',
90 "name", 90 "name",
91 "description", 91 "description",
92 &setme2), 92 &setme2),
93 GNUNET_GETOPT_OPTION_END 93 GNUNET_GETOPT_OPTION_END
94 }; 94 };
95 struct GNUNET_GETOPT_CommandLineOption options4[] = { 95 struct GNUNET_GETOPT_CommandLineOption options4[] = {
96 GNUNET_GETOPT_option_flag ('n', 96 GNUNET_GETOPT_option_flag('n',
97 "name", 97 "name",
98 "description", 98 "description",
99 &setme1), 99 &setme1),
100 GNUNET_GETOPT_option_flag ('n', 100 GNUNET_GETOPT_option_flag('n',
101 "name", 101 "name",
102 "description", 102 "description",
103 &setme2), 103 &setme2),
104 GNUNET_GETOPT_OPTION_END 104 GNUNET_GETOPT_OPTION_END
105 }; 105 };
106 106
107 107
108 GNUNET_log_setup ("test_program", 108 GNUNET_log_setup("test_program",
109 "WARNING", 109 "WARNING",
110 NULL); 110 NULL);
111 GNUNET_assert (GNUNET_OK == 111 GNUNET_assert(GNUNET_OK ==
112 GNUNET_PROGRAM_run (7, argvx, 112 GNUNET_PROGRAM_run(7, argvx,
113 "test_program", 113 "test_program",
114 "A test", 114 "A test",
115 options1, 115 options1,
116 &runner, &ok)); 116 &runner, &ok));
117 117
118 GNUNET_assert (GNUNET_OK == 118 GNUNET_assert(GNUNET_OK ==
119 GNUNET_PROGRAM_run (7, argvx, 119 GNUNET_PROGRAM_run(7, argvx,
120 "test_program", "A test", 120 "test_program", "A test",
121 options2, 121 options2,
122 &runner, &ok)); 122 &runner, &ok));
123 GNUNET_assert (GNUNET_OK == 123 GNUNET_assert(GNUNET_OK ==
124 GNUNET_PROGRAM_run (7, argvx, 124 GNUNET_PROGRAM_run(7, argvx,
125 "test_program", "A test", 125 "test_program", "A test",
126 options3, 126 options3,
127 &runner, &ok)); 127 &runner, &ok));
128 GNUNET_assert (GNUNET_OK == 128 GNUNET_assert(GNUNET_OK ==
129 GNUNET_PROGRAM_run (7, argvx, 129 GNUNET_PROGRAM_run(7, argvx,
130 "test_program", "A test", 130 "test_program", "A test",
131 options4, 131 options4,
132 &runner, &ok)); 132 &runner, &ok));
133 133
134 return ok; 134 return ok;
135} 135}
diff --git a/src/util/test_regex.c b/src/util/test_regex.c
index b47314084..c2306b971 100644
--- a/src/util/test_regex.c
+++ b/src/util/test_regex.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file tun/test_regex.c 21 * @file tun/test_regex.c
22 * @brief simple test for regex.c iptoregex functions 22 * @brief simple test for regex.c iptoregex functions
@@ -32,12 +32,12 @@
32 32
33 33
34static int 34static int
35test_iptoregex (const char *ipv4, 35test_iptoregex(const char *ipv4,
36 uint16_t port, 36 uint16_t port,
37 const char *expectedv4, 37 const char *expectedv4,
38 const char *ipv6, 38 const char *ipv6,
39 uint16_t port6, 39 uint16_t port6,
40 const char *expectedv6) 40 const char *expectedv6)
41{ 41{
42 int error = 0; 42 int error = 0;
43 43
@@ -46,136 +46,136 @@ test_iptoregex (const char *ipv4,
46 char rxv4[GNUNET_TUN_IPV4_REGEXLEN]; 46 char rxv4[GNUNET_TUN_IPV4_REGEXLEN];
47 char rxv6[GNUNET_TUN_IPV6_REGEXLEN]; 47 char rxv6[GNUNET_TUN_IPV6_REGEXLEN];
48 48
49 GNUNET_assert (1 == inet_pton (AF_INET, ipv4, &a)); 49 GNUNET_assert(1 == inet_pton(AF_INET, ipv4, &a));
50 GNUNET_TUN_ipv4toregexsearch (&a, port, rxv4); 50 GNUNET_TUN_ipv4toregexsearch(&a, port, rxv4);
51 51
52 if (0 != strcmp (rxv4, expectedv4)) 52 if (0 != strcmp(rxv4, expectedv4))
53 { 53 {
54 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 54 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
55 "Expected: %s but got: %s\n", 55 "Expected: %s but got: %s\n",
56 expectedv4, 56 expectedv4,
57 rxv4); 57 rxv4);
58 error++; 58 error++;
59 } 59 }
60 60
61 GNUNET_assert (1 == inet_pton (AF_INET6, ipv6, &b)); 61 GNUNET_assert(1 == inet_pton(AF_INET6, ipv6, &b));
62 GNUNET_TUN_ipv6toregexsearch (&b, port6, rxv6); 62 GNUNET_TUN_ipv6toregexsearch(&b, port6, rxv6);
63 if (0 != strcmp (rxv6, expectedv6)) 63 if (0 != strcmp(rxv6, expectedv6))
64 { 64 {
65 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 65 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
66 "Expected: %s but got: %s\n", 66 "Expected: %s but got: %s\n",
67 expectedv6, rxv6); 67 expectedv6, rxv6);
68 error++; 68 error++;
69 } 69 }
70 return error; 70 return error;
71} 71}
72 72
73 73
74static int 74static int
75test_policy4toregex (const char *policy, 75test_policy4toregex(const char *policy,
76 const char *regex) 76 const char *regex)
77{ 77{
78 char *r; 78 char *r;
79 int ret; 79 int ret;
80 80
81 ret = 0; 81 ret = 0;
82 r = GNUNET_TUN_ipv4policy2regex (policy); 82 r = GNUNET_TUN_ipv4policy2regex(policy);
83 if (NULL == r) 83 if (NULL == r)
84 { 84 {
85 GNUNET_break (0); 85 GNUNET_break(0);
86 return 1; 86 return 1;
87 } 87 }
88 if (0 != strcmp (regex, r)) 88 if (0 != strcmp(regex, r))
89 { 89 {
90 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 90 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
91 "Expected: `%s' but got: `%s'\n", 91 "Expected: `%s' but got: `%s'\n",
92 regex, r); 92 regex, r);
93 ret = 2; 93 ret = 2;
94 } 94 }
95 GNUNET_free (r); 95 GNUNET_free(r);
96 return ret; 96 return ret;
97} 97}
98 98
99 99
100static int 100static int
101test_policy6toregex (const char *policy, 101test_policy6toregex(const char *policy,
102 const char *regex) 102 const char *regex)
103{ 103{
104 char *r; 104 char *r;
105 int ret; 105 int ret;
106 106
107 ret = 0; 107 ret = 0;
108 r = GNUNET_TUN_ipv6policy2regex (policy); 108 r = GNUNET_TUN_ipv6policy2regex(policy);
109 if (NULL == r) 109 if (NULL == r)
110 { 110 {
111 GNUNET_break (0); 111 GNUNET_break(0);
112 return 1; 112 return 1;
113 } 113 }
114 if (0 != strcmp (regex, r)) 114 if (0 != strcmp(regex, r))
115 { 115 {
116 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 116 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
117 "Expected: `%s' but got: `%s'\n", 117 "Expected: `%s' but got: `%s'\n",
118 regex, r); 118 regex, r);
119 ret = 2; 119 ret = 2;
120 } 120 }
121 GNUNET_free (r); 121 GNUNET_free(r);
122 return ret; 122 return ret;
123} 123}
124 124
125 125
126int 126int
127main (int argc, char *argv[]) 127main(int argc, char *argv[])
128{ 128{
129 int error; 129 int error;
130 char *r; 130 char *r;
131 131
132 GNUNET_log_setup ("test-regex", "WARNING", NULL); 132 GNUNET_log_setup("test-regex", "WARNING", NULL);
133 error = 0; 133 error = 0;
134 134
135 /* this is just a performance test ... */ 135 /* this is just a performance test ... */
136 r = GNUNET_TUN_ipv4policy2regex ("1.2.3.4/16:!25;"); 136 r = GNUNET_TUN_ipv4policy2regex("1.2.3.4/16:!25;");
137 GNUNET_break (NULL != r); 137 GNUNET_break(NULL != r);
138 GNUNET_free (r); 138 GNUNET_free(r);
139 139
140 error += 140 error +=
141 test_iptoregex ("192.1.2.3", 2086, 141 test_iptoregex("192.1.2.3", 2086,
142 "4-0826-C0010203", 142 "4-0826-C0010203",
143 "FFFF::1", 8080, 143 "FFFF::1", 8080,
144 "6-1F90-FFFF0000000000000000000000000001"); 144 "6-1F90-FFFF0000000000000000000000000001");
145 error += 145 error +=
146 test_iptoregex ("187.238.255.0", 80, 146 test_iptoregex("187.238.255.0", 80,
147 "4-0050-BBEEFF00", 147 "4-0050-BBEEFF00",
148 "E1E1:73F9:51BE::0", 49, 148 "E1E1:73F9:51BE::0", 49,
149 "6-0031-E1E173F951BE00000000000000000000"); 149 "6-0031-E1E173F951BE00000000000000000000");
150 error += 150 error +=
151 test_policy4toregex ("192.1.2.0/24:80;", 151 test_policy4toregex("192.1.2.0/24:80;",
152 "4-0050-C00102" DOT DOT); 152 "4-0050-C00102" DOT DOT);
153 error += 153 error +=
154 test_policy4toregex ("192.1.0.0/16;", 154 test_policy4toregex("192.1.0.0/16;",
155 "4-" DOT DOT DOT DOT "-C001" DOT DOT DOT DOT); 155 "4-" DOT DOT DOT DOT "-C001" DOT DOT DOT DOT);
156 error += 156 error +=
157 test_policy4toregex ("192.1.0.0/16:80-81;", 157 test_policy4toregex("192.1.0.0/16:80-81;",
158 "4-(0050|0051)-C001" DOT DOT DOT DOT); 158 "4-(0050|0051)-C001" DOT DOT DOT DOT);
159 error += 159 error +=
160 test_policy4toregex ("192.1.0.0/8:!3-65535;", 160 test_policy4toregex("192.1.0.0/8:!3-65535;",
161 "4-000(0|1|2)-C0" DOT DOT DOT DOT DOT DOT); 161 "4-000(0|1|2)-C0" DOT DOT DOT DOT DOT DOT);
162 error += 162 error +=
163 test_policy4toregex ("192.1.0.0/8:!25-56;", 163 test_policy4toregex("192.1.0.0/8:!25-56;",
164 "4-(0(0(0"DOT"|1(0|1|2|3|4|5|6|7|8)|3(9|A|B|C|D|E|F)|(4|5|6|7|8|9|A|B|C|D|E|F)"DOT")|(1|2|3|4|5|6|7|8|9|A|B|C|D|E|F)"DOT DOT")|(1|2|3|4|5|6|7|8|9|A|B|C|D|E|F)"DOT DOT DOT")-C0"DOT DOT DOT DOT DOT DOT); 164 "4-(0(0(0"DOT "|1(0|1|2|3|4|5|6|7|8)|3(9|A|B|C|D|E|F)|(4|5|6|7|8|9|A|B|C|D|E|F)"DOT ")|(1|2|3|4|5|6|7|8|9|A|B|C|D|E|F)"DOT DOT ")|(1|2|3|4|5|6|7|8|9|A|B|C|D|E|F)"DOT DOT DOT ")-C0"DOT DOT DOT DOT DOT DOT);
165 error += 165 error +=
166 test_policy6toregex ("E1E1::1;", 166 test_policy6toregex("E1E1::1;",
167 "6-"DOT DOT DOT DOT"-E1E10000000000000000000000000001"); 167 "6-"DOT DOT DOT DOT "-E1E10000000000000000000000000001");
168 error += 168 error +=
169 test_policy6toregex ("E1E1:ABCD::1/120;", 169 test_policy6toregex("E1E1:ABCD::1/120;",
170 "6-"DOT DOT DOT DOT"-E1E1ABCD0000000000000000000000" DOT DOT); 170 "6-"DOT DOT DOT DOT "-E1E1ABCD0000000000000000000000" DOT DOT);
171 error += 171 error +=
172 test_policy6toregex ("E1E1:ABCD::ABCD/126;", 172 test_policy6toregex("E1E1:ABCD::ABCD/126;",
173 "6-"DOT DOT DOT DOT"-E1E1ABCD00000000000000000000ABC(C|D|E|F)"); 173 "6-"DOT DOT DOT DOT "-E1E1ABCD00000000000000000000ABC(C|D|E|F)");
174 error += 174 error +=
175 test_policy6toregex ("E1E1:ABCD::ABCD/127;", 175 test_policy6toregex("E1E1:ABCD::ABCD/127;",
176 "6-"DOT DOT DOT DOT"-E1E1ABCD00000000000000000000ABC(C|D)"); 176 "6-"DOT DOT DOT DOT "-E1E1ABCD00000000000000000000ABC(C|D)");
177 error += 177 error +=
178 test_policy6toregex ("E1E1:ABCD::ABCD/128:80;", 178 test_policy6toregex("E1E1:ABCD::ABCD/128:80;",
179 "6-0050-E1E1ABCD00000000000000000000ABCD"); 179 "6-0050-E1E1ABCD00000000000000000000ABCD");
180 return error; 180 return error;
181} 181}
diff --git a/src/util/test_resolver_api.c b/src/util/test_resolver_api.c
index f4184aa84..ea26c4ee6 100644
--- a/src/util/test_resolver_api.c
+++ b/src/util/test_resolver_api.c
@@ -1,19 +1,19 @@
1/* 1/*
2 This file is part of GNUnet. 2 This file is part of GNUnet.
3 Copyright (C) 2009 GNUnet e.V. 3 Copyright (C) 2009 GNUnet e.V.
4 4
5 GNUnet is free software: you can redistribute it and/or modify it 5 GNUnet is free software: you can redistribute it and/or modify it
6 under the terms of the GNU Affero General Public License as published 6 under the terms of the GNU Affero General Public License as published
7 by the Free Software Foundation, either version 3 of the License, 7 by the Free Software Foundation, either version 3 of the License,
8 or (at your option) any later version. 8 or (at your option) any later version.
9 9
10 GNUnet is distributed in the hope that it will be useful, but 10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19 */ 19 */
@@ -36,308 +36,307 @@ static int disable_rootserver_check;
36 * For more information have a look at IANA's website http://www.root-servers.org/ 36 * For more information have a look at IANA's website http://www.root-servers.org/
37 */ 37 */
38#define ROOTSERVER_NAME "a.root-servers.net" 38#define ROOTSERVER_NAME "a.root-servers.net"
39#define ROOTSERVER_IP "198.41.0.4" 39#define ROOTSERVER_IP "198.41.0.4"
40 40
41 41
42static void 42static void
43check_hostname (void *cls, 43check_hostname(void *cls,
44 const struct sockaddr *sa, 44 const struct sockaddr *sa,
45 socklen_t salen) 45 socklen_t salen)
46{ 46{
47 int *ok = cls; 47 int *ok = cls;
48 48
49 if (0 == salen) 49 if (0 == salen)
50 { 50 {
51 (*ok) &= ~8; 51 (*ok) &= ~8;
52 return; 52 return;
53 } 53 }
54 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 54 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
55 "Got IP address `%s' for our host.\n", 55 "Got IP address `%s' for our host.\n",
56 GNUNET_a2s (sa, salen)); 56 GNUNET_a2s(sa, salen));
57} 57}
58 58
59 59
60static void 60static void
61check_localhost_num (void *cls, 61check_localhost_num(void *cls,
62 const char *hostname) 62 const char *hostname)
63{ 63{
64 int *ok = cls; 64 int *ok = cls;
65 65
66 if (hostname == NULL) 66 if (hostname == NULL)
67 return; 67 return;
68 if (0 == strcmp (hostname, "127.0.0.1")) 68 if (0 == strcmp(hostname, "127.0.0.1"))
69 { 69 {
70 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 70 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
71 "Received correct hostname `%s'.\n", 71 "Received correct hostname `%s'.\n",
72 hostname); 72 hostname);
73 (*ok) &= ~4; 73 (*ok) &= ~4;
74 } 74 }
75 else 75 else
76 { 76 {
77 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 77 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
78 "Received invalid hostname `%s'.\n", 78 "Received invalid hostname `%s'.\n",
79 hostname); 79 hostname);
80 GNUNET_break (0); 80 GNUNET_break(0);
81 } 81 }
82} 82}
83 83
84 84
85static void 85static void
86check_localhost (void *cls, 86check_localhost(void *cls,
87 const char *hostname) 87 const char *hostname)
88{ 88{
89 int *ok = cls; 89 int *ok = cls;
90 90
91 if (NULL == hostname) 91 if (NULL == hostname)
92 return; 92 return;
93 if (0 == strcmp (hostname, "localhost")) 93 if (0 == strcmp(hostname, "localhost"))
94 { 94 {
95 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 95 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
96 "Received correct hostname `%s'.\n", 96 "Received correct hostname `%s'.\n",
97 hostname); 97 hostname);
98 (*ok) &= ~2; 98 (*ok) &= ~2;
99 } 99 }
100 else 100 else
101 { 101 {
102 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 102 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
103 "Received unexpected hostname `%s', expected `localhost' (this could be OK).\n", 103 "Received unexpected hostname `%s', expected `localhost' (this could be OK).\n",
104 hostname); 104 hostname);
105 } 105 }
106} 106}
107 107
108 108
109static void 109static void
110check_127 (void *cls, const struct sockaddr *sa, socklen_t salen) 110check_127(void *cls, const struct sockaddr *sa, socklen_t salen)
111{ 111{
112 int *ok = cls; 112 int *ok = cls;
113 const struct sockaddr_in *sai = (const struct sockaddr_in *) sa; 113 const struct sockaddr_in *sai = (const struct sockaddr_in *)sa;
114 114
115 if (NULL == sa) 115 if (NULL == sa)
116 return; 116 return;
117 GNUNET_assert (sizeof (struct sockaddr_in) == salen); 117 GNUNET_assert(sizeof(struct sockaddr_in) == salen);
118 if (sai->sin_addr.s_addr == htonl (INADDR_LOOPBACK)) 118 if (sai->sin_addr.s_addr == htonl(INADDR_LOOPBACK))
119 { 119 {
120 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 120 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
121 "Received correct address.\n"); 121 "Received correct address.\n");
122 (*ok) &= ~1; 122 (*ok) &= ~1;
123 } 123 }
124 else 124 else
125 { 125 {
126 char buf[INET_ADDRSTRLEN]; 126 char buf[INET_ADDRSTRLEN];
127 127
128 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 128 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
129 "Received incorrect address `%s'.\n", 129 "Received incorrect address `%s'.\n",
130 inet_ntop (AF_INET, 130 inet_ntop(AF_INET,
131 &sai->sin_addr, 131 &sai->sin_addr,
132 buf, 132 buf,
133 sizeof (buf))); 133 sizeof(buf)));
134 GNUNET_break (0); 134 GNUNET_break(0);
135 } 135 }
136} 136}
137 137
138 138
139static void 139static void
140check_rootserver_ip (void *cls, const struct sockaddr *sa, socklen_t salen) 140check_rootserver_ip(void *cls, const struct sockaddr *sa, socklen_t salen)
141{ 141{
142 int *ok = cls; 142 int *ok = cls;
143 const struct sockaddr_in *sai = (const struct sockaddr_in *) sa; 143 const struct sockaddr_in *sai = (const struct sockaddr_in *)sa;
144 144
145 if (NULL == sa) 145 if (NULL == sa)
146 return; 146 return;
147 GNUNET_assert (sizeof (struct sockaddr_in) == salen); 147 GNUNET_assert(sizeof(struct sockaddr_in) == salen);
148 148
149 if (0 == strcmp (inet_ntoa (sai->sin_addr), ROOTSERVER_IP)) 149 if (0 == strcmp(inet_ntoa(sai->sin_addr), ROOTSERVER_IP))
150 { 150 {
151 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 151 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
152 "Received correct rootserver ip address.\n"); 152 "Received correct rootserver ip address.\n");
153 (*ok) &= ~1; 153 (*ok) &= ~1;
154 } 154 }
155 else 155 else
156 { 156 {
157 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 157 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
158 "Received incorrect rootserver ip address.\n"); 158 "Received incorrect rootserver ip address.\n");
159 GNUNET_break (0); 159 GNUNET_break(0);
160 } 160 }
161} 161}
162 162
163 163
164static void 164static void
165check_rootserver_name (void *cls, 165check_rootserver_name(void *cls,
166 const char *hostname) 166 const char *hostname)
167{ 167{
168 int *ok = cls; 168 int *ok = cls;
169 169
170 if (NULL == hostname) 170 if (NULL == hostname)
171 return; 171 return;
172 172
173 if (0 == strcmp (hostname, ROOTSERVER_NAME)) 173 if (0 == strcmp(hostname, ROOTSERVER_NAME))
174 { 174 {
175 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 175 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
176 "Received correct rootserver hostname `%s'.\n", 176 "Received correct rootserver hostname `%s'.\n",
177 hostname); 177 hostname);
178 (*ok) &= ~2; 178 (*ok) &= ~2;
179 } 179 }
180 else 180 else
181 { 181 {
182 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 182 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
183 "Received invalid rootserver hostname `%s', expected `%s'\n", 183 "Received invalid rootserver hostname `%s', expected `%s'\n",
184 hostname, 184 hostname,
185 ROOTSERVER_NAME); 185 ROOTSERVER_NAME);
186 GNUNET_break (disable_rootserver_check); 186 GNUNET_break(disable_rootserver_check);
187 } 187 }
188} 188}
189 189
190 190
191static void 191static void
192run (void *cls, char *const *args, const char *cfgfile, 192run(void *cls, char *const *args, const char *cfgfile,
193 const struct GNUNET_CONFIGURATION_Handle *cfg) 193 const struct GNUNET_CONFIGURATION_Handle *cfg)
194{ 194{
195 int *ok = cls; 195 int *ok = cls;
196 struct sockaddr_in sa; 196 struct sockaddr_in sa;
197 struct GNUNET_TIME_Relative timeout = 197 struct GNUNET_TIME_Relative timeout =
198 GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 30); 198 GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 30);
199 int count_ips = 0; 199 int count_ips = 0;
200 char *own_fqdn; 200 char *own_fqdn;
201 const char *rootserver_name = ROOTSERVER_NAME; 201 const char *rootserver_name = ROOTSERVER_NAME;
202 struct hostent *rootserver; 202 struct hostent *rootserver;
203 struct in_addr rootserver_addr; 203 struct in_addr rootserver_addr;
204 204
205 memset (&sa, 0, sizeof (sa)); 205 memset(&sa, 0, sizeof(sa));
206 sa.sin_family = AF_INET; 206 sa.sin_family = AF_INET;
207#if HAVE_SOCKADDR_IN_SIN_LEN 207#if HAVE_SOCKADDR_IN_SIN_LEN
208 sa.sin_len = (u_char) sizeof (sa); 208 sa.sin_len = (u_char)sizeof(sa);
209#endif 209#endif
210 sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 210 sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
211 211
212 /* 212 /*
213 * Looking up our own fqdn 213 * Looking up our own fqdn
214 */ 214 */
215 own_fqdn = GNUNET_RESOLVER_local_fqdn_get (); 215 own_fqdn = GNUNET_RESOLVER_local_fqdn_get();
216 /* can't really check, only thing we can safely 216 /* can't really check, only thing we can safely
217 compare against is our own identical logic... */ 217 compare against is our own identical logic... */
218 GNUNET_free_non_null (own_fqdn); 218 GNUNET_free_non_null(own_fqdn);
219 219
220 /* 220 /*
221 * Testing non-local DNS resolution 221 * Testing non-local DNS resolution
222 * DNS rootserver to test: a.root-servers.net - 198.41.0.4 222 * DNS rootserver to test: a.root-servers.net - 198.41.0.4
223 */ 223 */
224 224
225 rootserver = gethostbyname (rootserver_name); 225 rootserver = gethostbyname(rootserver_name);
226 if (NULL == rootserver) 226 if (NULL == rootserver)
227 { 227 {
228 /* Error: resolving ip addresses does not work */ 228 /* Error: resolving ip addresses does not work */
229 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 229 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
230 _("gethostbyname() could not lookup IP address: %s\n"), 230 _("gethostbyname() could not lookup IP address: %s\n"),
231 hstrerror (h_errno)); 231 hstrerror(h_errno));
232 fprintf (stderr, 232 fprintf(stderr,
233 "%s", 233 "%s",
234 "System seems to be off-line, will not run all DNS tests\n"); 234 "System seems to be off-line, will not run all DNS tests\n");
235 *ok = 0; /* mark test as passing anyway */ 235 *ok = 0; /* mark test as passing anyway */
236 return; 236 return;
237 } 237 }
238 238
239 /* Counting returned IP addresses */ 239 /* Counting returned IP addresses */
240 while (NULL != rootserver->h_addr_list[count_ips]) 240 while (NULL != rootserver->h_addr_list[count_ips])
241 count_ips++; 241 count_ips++;
242 if (count_ips > 1) 242 if (count_ips > 1)
243 { 243 {
244 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 244 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
245 "IP received range for root name server, but a root name server has only 1 IP\n"); 245 "IP received range for root name server, but a root name server has only 1 IP\n");
246 GNUNET_break (0); 246 GNUNET_break(0);
247 } 247 }
248 248
249 /* Comparing to resolved address to the address the root name server should have */ 249 /* Comparing to resolved address to the address the root name server should have */
250 if (0 != 250 if (0 !=
251 strcmp (inet_ntoa (*(struct in_addr *) rootserver->h_addr_list[0]), 251 strcmp(inet_ntoa(*(struct in_addr *)rootserver->h_addr_list[0]),
252 ROOTSERVER_IP)) 252 ROOTSERVER_IP))
253 { 253 {
254 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 254 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
255 "IP received and IP for root name server differ\n"); 255 "IP received and IP for root name server differ\n");
256 GNUNET_break (0); 256 GNUNET_break(0);
257 } 257 }
258 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 258 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
259 "System's own forward name resolution is working\n"); 259 "System's own forward name resolution is working\n");
260 /* Resolve the same using GNUNET */ 260 /* Resolve the same using GNUNET */
261 GNUNET_RESOLVER_ip_get (ROOTSERVER_NAME, AF_INET, timeout, 261 GNUNET_RESOLVER_ip_get(ROOTSERVER_NAME, AF_INET, timeout,
262 &check_rootserver_ip, cls); 262 &check_rootserver_ip, cls);
263 GNUNET_RESOLVER_ip_get (ROOTSERVER_NAME, AF_INET, timeout, 263 GNUNET_RESOLVER_ip_get(ROOTSERVER_NAME, AF_INET, timeout,
264 &check_rootserver_ip, cls); 264 &check_rootserver_ip, cls);
265 265
266 /* 266 /*
267 * Success: forward lookups work as expected 267 * Success: forward lookups work as expected
268 * Next step: reverse lookups 268 * Next step: reverse lookups
269 */ 269 */
270 if (1 != inet_pton (AF_INET, 270 if (1 != inet_pton(AF_INET,
271 ROOTSERVER_IP, 271 ROOTSERVER_IP,
272 &rootserver_addr)) 272 &rootserver_addr))
273 { 273 {
274 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 274 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
275 "Could not transform root name server IP address\n"); 275 "Could not transform root name server IP address\n");
276 GNUNET_break (0); 276 GNUNET_break(0);
277 } 277 }
278 278
279 rootserver = 279 rootserver =
280 gethostbyaddr ((const void *) &rootserver_addr, 280 gethostbyaddr((const void *)&rootserver_addr,
281 sizeof (rootserver_addr), 281 sizeof(rootserver_addr),
282 AF_INET); 282 AF_INET);
283 if (NULL == rootserver) 283 if (NULL == rootserver)
284 {
285 /* Error: resolving IP addresses does not work */
286 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
287 "gethostbyaddr() could not lookup hostname: %s\n",
288 hstrerror (h_errno));
289 disable_rootserver_check = GNUNET_YES;
290 }
291 else
292 {
293 if (0 != strcmp (rootserver->h_name,
294 ROOTSERVER_NAME))
295 { 284 {
296 GNUNET_log (GNUNET_ERROR_TYPE_WARNING, 285 /* Error: resolving IP addresses does not work */
297 "Received hostname and hostname for root name server differ\n"); 286 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
287 "gethostbyaddr() could not lookup hostname: %s\n",
288 hstrerror(h_errno));
298 disable_rootserver_check = GNUNET_YES; 289 disable_rootserver_check = GNUNET_YES;
299 } 290 }
300 } 291 else
292 {
293 if (0 != strcmp(rootserver->h_name,
294 ROOTSERVER_NAME))
295 {
296 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
297 "Received hostname and hostname for root name server differ\n");
298 disable_rootserver_check = GNUNET_YES;
299 }
300 }
301 301
302 GNUNET_log (GNUNET_ERROR_TYPE_INFO, 302 GNUNET_log(GNUNET_ERROR_TYPE_INFO,
303 "System's own reverse name resolution is working\n"); 303 "System's own reverse name resolution is working\n");
304 /* Resolve the same using GNUNET */ 304 /* Resolve the same using GNUNET */
305 memset (&sa, 0, sizeof (sa)); 305 memset(&sa, 0, sizeof(sa));
306 sa.sin_family = AF_INET; 306 sa.sin_family = AF_INET;
307#if HAVE_SOCKADDR_IN_SIN_LEN 307#if HAVE_SOCKADDR_IN_SIN_LEN
308 sa.sin_len = (u_char) sizeof (sa); 308 sa.sin_len = (u_char)sizeof(sa);
309#endif 309#endif
310#ifndef MINGW 310#ifndef MINGW
311 inet_aton (ROOTSERVER_IP, &sa.sin_addr); 311 inet_aton(ROOTSERVER_IP, &sa.sin_addr);
312#else 312#else
313 sa.sin_addr.S_un.S_addr = inet_addr (ROOTSERVER_IP); 313 sa.sin_addr.S_un.S_addr = inet_addr(ROOTSERVER_IP);
314#endif 314#endif
315 GNUNET_RESOLVER_hostname_get ((const struct sockaddr *) &sa, 315 GNUNET_RESOLVER_hostname_get((const struct sockaddr *)&sa,
316 sizeof (struct sockaddr), GNUNET_YES, timeout, 316 sizeof(struct sockaddr), GNUNET_YES, timeout,
317 &check_rootserver_name, cls); 317 &check_rootserver_name, cls);
318 318
319 memset (&sa, 0, sizeof (sa)); 319 memset(&sa, 0, sizeof(sa));
320 sa.sin_family = AF_INET; 320 sa.sin_family = AF_INET;
321#if HAVE_SOCKADDR_IN_SIN_LEN 321#if HAVE_SOCKADDR_IN_SIN_LEN
322 sa.sin_len = (u_char) sizeof (sa); 322 sa.sin_len = (u_char)sizeof(sa);
323#endif 323#endif
324 sa.sin_addr.s_addr = htonl (INADDR_LOOPBACK); 324 sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
325
326 GNUNET_RESOLVER_ip_get ("localhost", AF_INET, timeout, &check_127, cls);
327 GNUNET_RESOLVER_hostname_get ((const struct sockaddr *) &sa,
328 sizeof (struct sockaddr), GNUNET_YES, timeout,
329 &check_localhost, cls);
330 325
331 GNUNET_RESOLVER_hostname_get ((const struct sockaddr *) &sa, 326 GNUNET_RESOLVER_ip_get("localhost", AF_INET, timeout, &check_127, cls);
332 sizeof (struct sockaddr), GNUNET_NO, timeout, 327 GNUNET_RESOLVER_hostname_get((const struct sockaddr *)&sa,
333 &check_localhost_num, cls); 328 sizeof(struct sockaddr), GNUNET_YES, timeout,
334 GNUNET_RESOLVER_hostname_resolve (AF_UNSPEC, timeout, &check_hostname, cls); 329 &check_localhost, cls);
335 330
331 GNUNET_RESOLVER_hostname_get((const struct sockaddr *)&sa,
332 sizeof(struct sockaddr), GNUNET_NO, timeout,
333 &check_localhost_num, cls);
334 GNUNET_RESOLVER_hostname_resolve(AF_UNSPEC, timeout, &check_hostname, cls);
336} 335}
337 336
338 337
339int 338int
340main (int argc, char *argv[]) 339main(int argc, char *argv[])
341{ 340{
342 int ok = 1 + 2 + 4 + 8; 341 int ok = 1 + 2 + 4 + 8;
343 char *fn; 342 char *fn;
@@ -346,34 +345,34 @@ main (int argc, char *argv[])
346 "test-resolver-api", "-c", "test_resolver_api_data.conf", NULL 345 "test-resolver-api", "-c", "test_resolver_api_data.conf", NULL
347 }; 346 };
348 struct GNUNET_GETOPT_CommandLineOption options[] = 347 struct GNUNET_GETOPT_CommandLineOption options[] =
349 { GNUNET_GETOPT_OPTION_END }; 348 { GNUNET_GETOPT_OPTION_END };
350 349
351 GNUNET_log_setup ("test-resolver-api", 350 GNUNET_log_setup("test-resolver-api",
352 "WARNING", 351 "WARNING",
353 NULL); 352 NULL);
354 fn = GNUNET_OS_get_libexec_binary_path ("gnunet-service-resolver"); 353 fn = GNUNET_OS_get_libexec_binary_path("gnunet-service-resolver");
355 proc = GNUNET_OS_start_process (GNUNET_YES, 354 proc = GNUNET_OS_start_process(GNUNET_YES,
356 GNUNET_OS_INHERIT_STD_OUT_AND_ERR, 355 GNUNET_OS_INHERIT_STD_OUT_AND_ERR,
357 NULL, NULL, NULL, 356 NULL, NULL, NULL,
358 fn, 357 fn,
359 "gnunet-service-resolver", 358 "gnunet-service-resolver",
360 "-c", "test_resolver_api_data.conf", NULL); 359 "-c", "test_resolver_api_data.conf", NULL);
361 GNUNET_assert (NULL != proc); 360 GNUNET_assert(NULL != proc);
362 GNUNET_free (fn); 361 GNUNET_free(fn);
363 GNUNET_assert (GNUNET_OK == 362 GNUNET_assert(GNUNET_OK ==
364 GNUNET_PROGRAM_run ((sizeof (argvx) / sizeof (char *)) - 1, 363 GNUNET_PROGRAM_run((sizeof(argvx) / sizeof(char *)) - 1,
365 argvx, "test-resolver-api", "nohelp", 364 argvx, "test-resolver-api", "nohelp",
366 options, &run, &ok)); 365 options, &run, &ok));
367 if (0 != GNUNET_OS_process_kill (proc, GNUNET_TERM_SIG)) 366 if (0 != GNUNET_OS_process_kill(proc, GNUNET_TERM_SIG))
368 { 367 {
369 GNUNET_log_strerror (GNUNET_ERROR_TYPE_WARNING, "kill"); 368 GNUNET_log_strerror(GNUNET_ERROR_TYPE_WARNING, "kill");
370 ok = 1; 369 ok = 1;
371 } 370 }
372 GNUNET_OS_process_wait (proc); 371 GNUNET_OS_process_wait(proc);
373 GNUNET_OS_process_destroy (proc); 372 GNUNET_OS_process_destroy(proc);
374 proc = NULL; 373 proc = NULL;
375 if (0 != ok) 374 if (0 != ok)
376 fprintf (stderr, "Missed some resolutions: %u\n", ok); 375 fprintf(stderr, "Missed some resolutions: %u\n", ok);
377 return ok; 376 return ok;
378} 377}
379 378
diff --git a/src/util/test_scheduler.c b/src/util/test_scheduler.c
index 234a2aae1..236bb4e76 100644
--- a/src/util/test_scheduler.c
+++ b/src/util/test_scheduler.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_scheduler.c 21 * @file util/test_scheduler.c
22 * @brief tests for the scheduler 22 * @brief tests for the scheduler
@@ -33,135 +33,135 @@ static struct GNUNET_SCHEDULER_Task *never_run_task;
33 33
34 34
35static void 35static void
36task2 (void *cls) 36task2(void *cls)
37{ 37{
38 int *ok = cls; 38 int *ok = cls;
39 39
40 /* t3 should be ready (albeit with lower priority) */ 40 /* t3 should be ready (albeit with lower priority) */
41 GNUNET_assert (1 == 41 GNUNET_assert(1 ==
42 GNUNET_SCHEDULER_get_load (GNUNET_SCHEDULER_PRIORITY_COUNT)); 42 GNUNET_SCHEDULER_get_load(GNUNET_SCHEDULER_PRIORITY_COUNT));
43 GNUNET_assert (2 == *ok); 43 GNUNET_assert(2 == *ok);
44 (*ok) = 3; 44 (*ok) = 3;
45} 45}
46 46
47 47
48static void 48static void
49task3 (void *cls) 49task3(void *cls)
50{ 50{
51 int *ok = cls; 51 int *ok = cls;
52 52
53 GNUNET_assert (3 == *ok); 53 GNUNET_assert(3 == *ok);
54 (*ok) = 4; 54 (*ok) = 4;
55} 55}
56 56
57 57
58static void 58static void
59taskWrt (void *cls) 59taskWrt(void *cls)
60{ 60{
61 static char c; 61 static char c;
62 int *ok = cls; 62 int *ok = cls;
63 const struct GNUNET_SCHEDULER_TaskContext *tc; 63 const struct GNUNET_SCHEDULER_TaskContext *tc;
64 64
65 tc = GNUNET_SCHEDULER_get_task_context (); 65 tc = GNUNET_SCHEDULER_get_task_context();
66 GNUNET_assert (6 == *ok); 66 GNUNET_assert(6 == *ok);
67 GNUNET_assert (GNUNET_NETWORK_fdset_handle_isset (tc->write_ready, fds[1])); 67 GNUNET_assert(GNUNET_NETWORK_fdset_handle_isset(tc->write_ready, fds[1]));
68 (*ok) = 7; 68 (*ok) = 7;
69 GNUNET_assert (1 == GNUNET_DISK_file_write (fds[1], &c, 1)); 69 GNUNET_assert(1 == GNUNET_DISK_file_write(fds[1], &c, 1));
70} 70}
71 71
72 72
73static void 73static void
74taskNeverRun (void *cls) 74taskNeverRun(void *cls)
75{ 75{
76 GNUNET_assert (0); 76 GNUNET_assert(0);
77} 77}
78 78
79 79
80static void 80static void
81taskLastRd (void *cls) 81taskLastRd(void *cls)
82{ 82{
83 int *ok = cls; 83 int *ok = cls;
84 84
85 GNUNET_assert (8 == *ok); 85 GNUNET_assert(8 == *ok);
86 (*ok) = 0; 86 (*ok) = 0;
87} 87}
88 88
89 89
90static void 90static void
91taskLastSig (void *cls) 91taskLastSig(void *cls)
92{ 92{
93 int *ok = cls; 93 int *ok = cls;
94 94
95 GNUNET_SCHEDULER_cancel (never_run_task); 95 GNUNET_SCHEDULER_cancel(never_run_task);
96 GNUNET_assert (9 == *ok); 96 GNUNET_assert(9 == *ok);
97 (*ok) = 0; 97 (*ok) = 0;
98} 98}
99 99
100 100
101static void 101static void
102taskLastShutdown (void *cls) 102taskLastShutdown(void *cls)
103{ 103{
104 int *ok = cls; 104 int *ok = cls;
105 105
106 GNUNET_assert (10 == *ok); 106 GNUNET_assert(10 == *ok);
107 (*ok) = 0; 107 (*ok) = 0;
108} 108}
109 109
110 110
111static void 111static void
112taskRd (void *cls) 112taskRd(void *cls)
113{ 113{
114 static char c; 114 static char c;
115 int *ok = cls; 115 int *ok = cls;
116 const struct GNUNET_SCHEDULER_TaskContext *tc; 116 const struct GNUNET_SCHEDULER_TaskContext *tc;
117 117
118 tc = GNUNET_SCHEDULER_get_task_context (); 118 tc = GNUNET_SCHEDULER_get_task_context();
119 GNUNET_assert (7 == *ok); 119 GNUNET_assert(7 == *ok);
120 GNUNET_assert (GNUNET_NETWORK_fdset_handle_isset (tc->read_ready, fds[0])); 120 GNUNET_assert(GNUNET_NETWORK_fdset_handle_isset(tc->read_ready, fds[0]));
121 GNUNET_assert (1 == GNUNET_DISK_file_read (fds[0], &c, 1)); 121 GNUNET_assert(1 == GNUNET_DISK_file_read(fds[0], &c, 1));
122 (*ok) = 8; 122 (*ok) = 8;
123 GNUNET_SCHEDULER_add_shutdown (&taskLastRd, 123 GNUNET_SCHEDULER_add_shutdown(&taskLastRd,
124 cls); 124 cls);
125 GNUNET_SCHEDULER_shutdown (); 125 GNUNET_SCHEDULER_shutdown();
126} 126}
127 127
128 128
129static void 129static void
130task4 (void *cls) 130task4(void *cls)
131{ 131{
132 int *ok = cls; 132 int *ok = cls;
133 133
134 GNUNET_assert (4 == *ok); 134 GNUNET_assert(4 == *ok);
135 (*ok) = 6; 135 (*ok) = 6;
136 p = GNUNET_DISK_pipe (GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO); 136 p = GNUNET_DISK_pipe(GNUNET_NO, GNUNET_NO, GNUNET_NO, GNUNET_NO);
137 GNUNET_assert (NULL != p); 137 GNUNET_assert(NULL != p);
138 fds[0] = GNUNET_DISK_pipe_handle (p, GNUNET_DISK_PIPE_END_READ); 138 fds[0] = GNUNET_DISK_pipe_handle(p, GNUNET_DISK_PIPE_END_READ);
139 fds[1] = GNUNET_DISK_pipe_handle (p, GNUNET_DISK_PIPE_END_WRITE); 139 fds[1] = GNUNET_DISK_pipe_handle(p, GNUNET_DISK_PIPE_END_WRITE);
140 GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, 140 GNUNET_SCHEDULER_add_read_file(GNUNET_TIME_UNIT_FOREVER_REL,
141 fds[0], 141 fds[0],
142 &taskRd, 142 &taskRd,
143 cls);
144 GNUNET_SCHEDULER_add_write_file(GNUNET_TIME_UNIT_FOREVER_REL,
145 fds[1],
146 &taskWrt,
143 cls); 147 cls);
144 GNUNET_SCHEDULER_add_write_file (GNUNET_TIME_UNIT_FOREVER_REL,
145 fds[1],
146 &taskWrt,
147 cls);
148} 148}
149 149
150 150
151static void 151static void
152task1 (void *cls) 152task1(void *cls)
153{ 153{
154 int *ok = cls; 154 int *ok = cls;
155 155
156 GNUNET_assert (1 == *ok); 156 GNUNET_assert(1 == *ok);
157 (*ok) = 2; 157 (*ok) = 2;
158 GNUNET_SCHEDULER_add_now (&task3, cls); 158 GNUNET_SCHEDULER_add_now(&task3, cls);
159 GNUNET_SCHEDULER_add_with_priority (GNUNET_SCHEDULER_PRIORITY_UI, 159 GNUNET_SCHEDULER_add_with_priority(GNUNET_SCHEDULER_PRIORITY_UI,
160 &task2, 160 &task2,
161 cls); 161 cls);
162 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, 162 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
163 &task4, 163 &task4,
164 cls); 164 cls);
165} 165}
166 166
167 167
@@ -170,27 +170,27 @@ task1 (void *cls)
170 * checks that "ok" is correct at the end. 170 * checks that "ok" is correct at the end.
171 */ 171 */
172static int 172static int
173check () 173check()
174{ 174{
175 int ok; 175 int ok;
176 176
177 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 177 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
178 "[Check scheduling]\n"); 178 "[Check scheduling]\n");
179 ok = 1; 179 ok = 1;
180 GNUNET_SCHEDULER_run (&task1, &ok); 180 GNUNET_SCHEDULER_run(&task1, &ok);
181 return ok; 181 return ok;
182} 182}
183 183
184 184
185static void 185static void
186taskShutdown (void *cls) 186taskShutdown(void *cls)
187{ 187{
188 int *ok = cls; 188 int *ok = cls;
189 189
190 GNUNET_assert (1 == *ok); 190 GNUNET_assert(1 == *ok);
191 *ok = 10; 191 *ok = 10;
192 GNUNET_SCHEDULER_add_shutdown (&taskLastShutdown, cls); 192 GNUNET_SCHEDULER_add_shutdown(&taskLastShutdown, cls);
193 GNUNET_SCHEDULER_shutdown (); 193 GNUNET_SCHEDULER_shutdown();
194} 194}
195 195
196 196
@@ -199,33 +199,33 @@ taskShutdown (void *cls)
199 * checks that "ok" is correct at the end. 199 * checks that "ok" is correct at the end.
200 */ 200 */
201static int 201static int
202checkShutdown () 202checkShutdown()
203{ 203{
204 int ok; 204 int ok;
205 205
206 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 206 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
207 "[Check shutdown]\n"); 207 "[Check shutdown]\n");
208 ok = 1; 208 ok = 1;
209 GNUNET_SCHEDULER_run (&taskShutdown, &ok); 209 GNUNET_SCHEDULER_run(&taskShutdown, &ok);
210 return ok; 210 return ok;
211} 211}
212 212
213 213
214#ifndef MINGW 214#ifndef MINGW
215static void 215static void
216taskSig (void *cls) 216taskSig(void *cls)
217{ 217{
218 int *ok = cls; 218 int *ok = cls;
219 219
220 GNUNET_assert (1 == *ok); 220 GNUNET_assert(1 == *ok);
221 *ok = 9; 221 *ok = 9;
222 GNUNET_SCHEDULER_add_shutdown (&taskLastSig, cls); 222 GNUNET_SCHEDULER_add_shutdown(&taskLastSig, cls);
223 never_run_task = 223 never_run_task =
224 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_SECONDS, 5), 224 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply(GNUNET_TIME_UNIT_SECONDS, 5),
225 &taskNeverRun, 225 &taskNeverRun,
226 NULL); 226 NULL);
227 GNUNET_break (0 == kill (getpid (), 227 GNUNET_break(0 == kill(getpid(),
228 GNUNET_TERM_SIG)); 228 GNUNET_TERM_SIG));
229} 229}
230 230
231 231
@@ -234,27 +234,27 @@ taskSig (void *cls)
234 * checks that "ok" is correct at the end. 234 * checks that "ok" is correct at the end.
235 */ 235 */
236static int 236static int
237checkSignal () 237checkSignal()
238{ 238{
239 int ok; 239 int ok;
240 240
241 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 241 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
242 "[Check signal handling]\n"); 242 "[Check signal handling]\n");
243 ok = 1; 243 ok = 1;
244 GNUNET_SCHEDULER_run (&taskSig, &ok); 244 GNUNET_SCHEDULER_run(&taskSig, &ok);
245 return ok; 245 return ok;
246} 246}
247#endif 247#endif
248 248
249 249
250static void 250static void
251taskCancel (void *cls) 251taskCancel(void *cls)
252{ 252{
253 int *ok = cls; 253 int *ok = cls;
254 254
255 GNUNET_assert (1 == *ok); 255 GNUNET_assert(1 == *ok);
256 *ok = 0; 256 *ok = 0;
257 GNUNET_SCHEDULER_cancel (GNUNET_SCHEDULER_add_now (&taskNeverRun, NULL)); 257 GNUNET_SCHEDULER_cancel(GNUNET_SCHEDULER_add_now(&taskNeverRun, NULL));
258} 258}
259 259
260 260
@@ -263,31 +263,31 @@ taskCancel (void *cls)
263 * checks that "ok" is correct at the end. 263 * checks that "ok" is correct at the end.
264 */ 264 */
265static int 265static int
266checkCancel () 266checkCancel()
267{ 267{
268 int ok; 268 int ok;
269 269
270 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 270 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
271 "[Check task cancellation]\n"); 271 "[Check task cancellation]\n");
272 ok = 1; 272 ok = 1;
273 GNUNET_SCHEDULER_run (&taskCancel, &ok); 273 GNUNET_SCHEDULER_run(&taskCancel, &ok);
274 return ok; 274 return ok;
275} 275}
276 276
277 277
278int 278int
279main (int argc, char *argv[]) 279main(int argc, char *argv[])
280{ 280{
281 int ret = 0; 281 int ret = 0;
282 282
283 GNUNET_log_setup ("test_scheduler", "WARNING", NULL); 283 GNUNET_log_setup("test_scheduler", "WARNING", NULL);
284 ret += check (); 284 ret += check();
285 ret += checkCancel (); 285 ret += checkCancel();
286#ifndef MINGW 286#ifndef MINGW
287 ret += checkSignal (); 287 ret += checkSignal();
288#endif 288#endif
289 ret += checkShutdown (); 289 ret += checkShutdown();
290 GNUNET_DISK_pipe_close (p); 290 GNUNET_DISK_pipe_close(p);
291 291
292 return ret; 292 return ret;
293} 293}
diff --git a/src/util/test_scheduler_delay.c b/src/util/test_scheduler_delay.c
index 1ec86c647..c72ee7b19 100644
--- a/src/util/test_scheduler_delay.c
+++ b/src/util/test_scheduler_delay.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_scheduler_delay.c 21 * @file util/test_scheduler_delay.c
22 * @brief testcase for delay of scheduler, measures how 22 * @brief testcase for delay of scheduler, measures how
@@ -43,51 +43,51 @@ static unsigned long long cumDelta;
43 * @param cls closure 43 * @param cls closure
44 */ 44 */
45static void 45static void
46test_task (void *cls) 46test_task(void *cls)
47{ 47{
48 struct GNUNET_TIME_Absolute now; 48 struct GNUNET_TIME_Absolute now;
49 49
50 now = GNUNET_TIME_absolute_get (); 50 now = GNUNET_TIME_absolute_get();
51 if (now.abs_value_us > target.abs_value_us) 51 if (now.abs_value_us > target.abs_value_us)
52 cumDelta += (now.abs_value_us - target.abs_value_us); 52 cumDelta += (now.abs_value_us - target.abs_value_us);
53 else 53 else
54 cumDelta += (target.abs_value_us - now.abs_value_us); 54 cumDelta += (target.abs_value_us - now.abs_value_us);
55 target = 55 target =
56 GNUNET_TIME_relative_to_absolute (GNUNET_TIME_relative_multiply 56 GNUNET_TIME_relative_to_absolute(GNUNET_TIME_relative_multiply
57 (GNUNET_TIME_UNIT_MICROSECONDS, i)); 57 (GNUNET_TIME_UNIT_MICROSECONDS, i));
58 fprintf (stderr, "%s", "."); 58 fprintf(stderr, "%s", ".");
59 if (i > MAXV) 59 if (i > MAXV)
60 { 60 {
61 fprintf (stderr, "%s", "\n"); 61 fprintf(stderr, "%s", "\n");
62 return; 62 return;
63 } 63 }
64 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_relative_multiply 64 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_relative_multiply
65 (GNUNET_TIME_UNIT_MICROSECONDS, i), 65 (GNUNET_TIME_UNIT_MICROSECONDS, i),
66 &test_task, 66 &test_task,
67 NULL); 67 NULL);
68 i += INCR; 68 i += INCR;
69} 69}
70 70
71 71
72int 72int
73main (int argc, char *argv[]) 73main(int argc, char *argv[])
74{ 74{
75 GNUNET_log_setup ("test-scheduler-delay", 75 GNUNET_log_setup("test-scheduler-delay",
76 "WARNING", 76 "WARNING",
77 NULL); 77 NULL);
78 target = GNUNET_TIME_absolute_get (); 78 target = GNUNET_TIME_absolute_get();
79 GNUNET_SCHEDULER_run (&test_task, NULL); 79 GNUNET_SCHEDULER_run(&test_task, NULL);
80 fprintf (stdout, 80 fprintf(stdout,
81 "Sleep precision: %llu microseconds (average delta). ", 81 "Sleep precision: %llu microseconds (average delta). ",
82 cumDelta / (MAXV / INCR)); 82 cumDelta / (MAXV / INCR));
83 if (cumDelta <= 500 * MAXV / INCR) 83 if (cumDelta <= 500 * MAXV / INCR)
84 fprintf (stdout, "%s", "Timer precision is excellent.\n"); 84 fprintf(stdout, "%s", "Timer precision is excellent.\n");
85 else if (cumDelta <= 5000 * MAXV / INCR) /* 5 ms average deviation */ 85 else if (cumDelta <= 5000 * MAXV / INCR) /* 5 ms average deviation */
86 fprintf (stdout, "%s", "Timer precision is good.\n"); 86 fprintf(stdout, "%s", "Timer precision is good.\n");
87 else if (cumDelta > 25000 * MAXV / INCR) 87 else if (cumDelta > 25000 * MAXV / INCR)
88 fprintf (stdout, "%s", "Timer precision is awful.\n"); 88 fprintf(stdout, "%s", "Timer precision is awful.\n");
89 else 89 else
90 fprintf (stdout, "%s", "Timer precision is acceptable.\n"); 90 fprintf(stdout, "%s", "Timer precision is acceptable.\n");
91 return 0; 91 return 0;
92} 92}
93 93
diff --git a/src/util/test_service.c b/src/util/test_service.c
index dc8bc59c1..c0b02872f 100644
--- a/src/util/test_service.c
+++ b/src/util/test_service.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_service.c 21 * @file util/test_service.c
22 * @brief tests for service.c 22 * @brief tests for service.c
@@ -43,20 +43,20 @@ static struct GNUNET_SCHEDULER_Task *tt;
43 43
44 44
45static void 45static void
46handle_recv (void *cls, 46handle_recv(void *cls,
47 const struct GNUNET_MessageHeader *message) 47 const struct GNUNET_MessageHeader *message)
48{ 48{
49 struct GNUNET_SERVICE_Client *client = cls; 49 struct GNUNET_SERVICE_Client *client = cls;
50 50
51 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 51 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
52 "Received client message...\n"); 52 "Received client message...\n");
53 GNUNET_SERVICE_client_continue (client); 53 GNUNET_SERVICE_client_continue(client);
54 global_ret = 2; 54 global_ret = 2;
55 if (NULL != mq) 55 if (NULL != mq)
56 { 56 {
57 GNUNET_MQ_destroy (mq); 57 GNUNET_MQ_destroy(mq);
58 mq = NULL; 58 mq = NULL;
59 } 59 }
60} 60}
61 61
62 62
@@ -69,9 +69,9 @@ handle_recv (void *cls,
69 * @return @a c so we have the client handle in the future 69 * @return @a c so we have the client handle in the future
70 */ 70 */
71static void * 71static void *
72connect_cb (void *cls, 72connect_cb(void *cls,
73 struct GNUNET_SERVICE_Client *c, 73 struct GNUNET_SERVICE_Client *c,
74 struct GNUNET_MQ_Handle *mq) 74 struct GNUNET_MQ_Handle *mq)
75{ 75{
76 /* FIXME: in the future, do something with mq 76 /* FIXME: in the future, do something with mq
77 to test sending messages to the client! */ 77 to test sending messages to the client! */
@@ -85,37 +85,37 @@ connect_cb (void *cls,
85 * @param cls our service name 85 * @param cls our service name
86 * @param c disconnecting client 86 * @param c disconnecting client
87 * @param internal_cls must match @a c 87 * @param internal_cls must match @a c
88 */ 88 */
89static void 89static void
90disconnect_cb (void *cls, 90disconnect_cb(void *cls,
91 struct GNUNET_SERVICE_Client *c, 91 struct GNUNET_SERVICE_Client *c,
92 void *internal_cls) 92 void *internal_cls)
93{ 93{
94 GNUNET_assert (c == internal_cls); 94 GNUNET_assert(c == internal_cls);
95 if (2 == global_ret) 95 if (2 == global_ret)
96 {
97 GNUNET_SCHEDULER_shutdown ();
98 global_ret = 0;
99 if (NULL != tt)
100 { 96 {
101 GNUNET_SCHEDULER_cancel (tt); 97 GNUNET_SCHEDULER_shutdown();
102 tt = NULL; 98 global_ret = 0;
99 if (NULL != tt)
100 {
101 GNUNET_SCHEDULER_cancel(tt);
102 tt = NULL;
103 }
103 } 104 }
104 }
105} 105}
106 106
107 107
108static void 108static void
109timeout_task (void *cls) 109timeout_task(void *cls)
110{ 110{
111 tt = NULL; 111 tt = NULL;
112 if (NULL != mq) 112 if (NULL != mq)
113 { 113 {
114 GNUNET_MQ_destroy (mq); 114 GNUNET_MQ_destroy(mq);
115 mq = NULL; 115 mq = NULL;
116 } 116 }
117 global_ret = 33; 117 global_ret = 33;
118 GNUNET_SCHEDULER_shutdown (); 118 GNUNET_SCHEDULER_shutdown();
119} 119}
120 120
121 121
@@ -128,28 +128,28 @@ timeout_task (void *cls)
128 * @param sh handle to the service 128 * @param sh handle to the service
129 */ 129 */
130static void 130static void
131service_init (void *cls, 131service_init(void *cls,
132 const struct GNUNET_CONFIGURATION_Handle *cfg, 132 const struct GNUNET_CONFIGURATION_Handle *cfg,
133 struct GNUNET_SERVICE_Handle *sh) 133 struct GNUNET_SERVICE_Handle *sh)
134{ 134{
135 const char *service_name = cls; 135 const char *service_name = cls;
136 struct GNUNET_MQ_Envelope *env; 136 struct GNUNET_MQ_Envelope *env;
137 struct GNUNET_MessageHeader *msg; 137 struct GNUNET_MessageHeader *msg;
138 138
139 GNUNET_assert (NULL == tt); 139 GNUNET_assert(NULL == tt);
140 tt = GNUNET_SCHEDULER_add_delayed (TIMEOUT, 140 tt = GNUNET_SCHEDULER_add_delayed(TIMEOUT,
141 &timeout_task, 141 &timeout_task,
142 NULL); 142 NULL);
143 mq = GNUNET_CLIENT_connect (cfg, 143 mq = GNUNET_CLIENT_connect(cfg,
144 service_name, 144 service_name,
145 NULL, 145 NULL,
146 NULL, 146 NULL,
147 NULL); 147 NULL);
148 GNUNET_assert (NULL != mq); 148 GNUNET_assert(NULL != mq);
149 env = GNUNET_MQ_msg (msg, 149 env = GNUNET_MQ_msg(msg,
150 MY_TYPE); 150 MY_TYPE);
151 GNUNET_MQ_send (mq, 151 GNUNET_MQ_send(mq,
152 env); 152 env);
153} 153}
154 154
155 155
@@ -160,78 +160,78 @@ service_init (void *cls,
160 * @param sname name of the service to run 160 * @param sname name of the service to run
161 */ 161 */
162static int 162static int
163check (const char *sname) 163check(const char *sname)
164{ 164{
165 struct GNUNET_MQ_MessageHandler myhandlers[] = { 165 struct GNUNET_MQ_MessageHandler myhandlers[] = {
166 GNUNET_MQ_hd_fixed_size (recv, 166 GNUNET_MQ_hd_fixed_size(recv,
167 MY_TYPE, 167 MY_TYPE,
168 struct GNUNET_MessageHeader, 168 struct GNUNET_MessageHeader,
169 NULL), 169 NULL),
170 GNUNET_MQ_handler_end () 170 GNUNET_MQ_handler_end()
171 }; 171 };
172 char *const argv[] = { 172 char *const argv[] = {
173 (char *) sname, 173 (char *)sname,
174 "-c", 174 "-c",
175 "test_service_data.conf", 175 "test_service_data.conf",
176 NULL 176 NULL
177 }; 177 };
178 178
179 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 179 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
180 "Starting `%s' service\n", 180 "Starting `%s' service\n",
181 sname); 181 sname);
182 global_ret = 1; 182 global_ret = 1;
183 GNUNET_assert (0 == 183 GNUNET_assert(0 ==
184 GNUNET_SERVICE_run_ (3, 184 GNUNET_SERVICE_run_(3,
185 argv, 185 argv,
186 sname, 186 sname,
187 GNUNET_SERVICE_OPTION_NONE, 187 GNUNET_SERVICE_OPTION_NONE,
188 &service_init, 188 &service_init,
189 &connect_cb, 189 &connect_cb,
190 &disconnect_cb, 190 &disconnect_cb,
191 (void *) sname, 191 (void *)sname,
192 myhandlers)); 192 myhandlers));
193 return global_ret; 193 return global_ret;
194} 194}
195 195
196 196
197int 197int
198main (int argc, 198main(int argc,
199 char *argv[]) 199 char *argv[])
200{ 200{
201 int ret = 0; 201 int ret = 0;
202 struct GNUNET_NETWORK_Handle *s = NULL; 202 struct GNUNET_NETWORK_Handle *s = NULL;
203 203
204 GNUNET_log_setup ("test-service", 204 GNUNET_log_setup("test-service",
205 "WARNING", 205 "WARNING",
206 NULL); 206 NULL);
207 ret += check ("test_service"); 207 ret += check("test_service");
208 ret += check ("test_service"); 208 ret += check("test_service");
209#ifndef MINGW 209#ifndef MINGW
210 s = GNUNET_NETWORK_socket_create (PF_INET6, 210 s = GNUNET_NETWORK_socket_create(PF_INET6,
211 SOCK_STREAM, 211 SOCK_STREAM,
212 0); 212 0);
213#endif 213#endif
214 if (NULL == s) 214 if (NULL == s)
215 {
216 if ( (errno == ENOBUFS) ||
217 (errno == ENOMEM) ||
218 (errno == ENFILE) ||
219 (errno == EACCES) )
220 { 215 {
221 GNUNET_log_strerror (GNUNET_ERROR_TYPE_ERROR, 216 if ((errno == ENOBUFS) ||
222 "socket"); 217 (errno == ENOMEM) ||
223 return 1; 218 (errno == ENFILE) ||
219 (errno == EACCES))
220 {
221 GNUNET_log_strerror(GNUNET_ERROR_TYPE_ERROR,
222 "socket");
223 return 1;
224 }
225 fprintf(stderr,
226 "IPv6 support seems to not be available (%s), not testing it!\n",
227 strerror(errno));
224 } 228 }
225 fprintf (stderr,
226 "IPv6 support seems to not be available (%s), not testing it!\n",
227 strerror (errno));
228 }
229 else 229 else
230 { 230 {
231 GNUNET_break (GNUNET_OK == 231 GNUNET_break(GNUNET_OK ==
232 GNUNET_NETWORK_socket_close (s)); 232 GNUNET_NETWORK_socket_close(s));
233 ret += check ("test_service6"); 233 ret += check("test_service6");
234 } 234 }
235 return ret; 235 return ret;
236} 236}
237 237
diff --git a/src/util/test_socks.c b/src/util/test_socks.c
index 89a350feb..dc5847d14 100644
--- a/src/util/test_socks.c
+++ b/src/util/test_socks.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_socks.c 21 * @file util/test_socks.c
22 * @brief tests for socks.c 22 * @brief tests for socks.c
@@ -37,26 +37,25 @@ static struct GNUNET_CONFIGURATION_Handle *cfg;
37 37
38#define MY_TYPE 130 38#define MY_TYPE 130
39 39
40struct CopyContext 40struct CopyContext {
41{
42 struct GNUNET_SERVER_Client *client; 41 struct GNUNET_SERVER_Client *client;
43 struct GNUNET_MessageHeader *cpy; 42 struct GNUNET_MessageHeader *cpy;
44}; 43};
45 44
46static size_t 45static size_t
47copy_msg (void *cls, size_t size, void *buf) 46copy_msg(void *cls, size_t size, void *buf)
48{ 47{
49 struct CopyContext *ctx = cls; 48 struct CopyContext *ctx = cls;
50 struct GNUNET_MessageHeader *cpy = ctx->cpy; 49 struct GNUNET_MessageHeader *cpy = ctx->cpy;
51 50
52 GNUNET_assert (sizeof (struct GNUNET_MessageHeader) == ntohs (cpy->size)); 51 GNUNET_assert(sizeof(struct GNUNET_MessageHeader) == ntohs(cpy->size));
53 GNUNET_assert (size >= ntohs (cpy->size)); 52 GNUNET_assert(size >= ntohs(cpy->size));
54 GNUNET_memcpy (buf, cpy, ntohs (cpy->size)); 53 GNUNET_memcpy(buf, cpy, ntohs(cpy->size));
55 GNUNET_SERVER_receive_done (ctx->client, GNUNET_OK); 54 GNUNET_SERVER_receive_done(ctx->client, GNUNET_OK);
56 GNUNET_free (cpy); 55 GNUNET_free(cpy);
57 GNUNET_free (ctx); 56 GNUNET_free(ctx);
58 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Message bounced back to client\n"); 57 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG, "Message bounced back to client\n");
59 return sizeof (struct GNUNET_MessageHeader); 58 return sizeof(struct GNUNET_MessageHeader);
60} 59}
61 60
62 61
@@ -64,46 +63,46 @@ copy_msg (void *cls, size_t size, void *buf)
64 * Callback that just bounces the message back to the sender. 63 * Callback that just bounces the message back to the sender.
65 */ 64 */
66static void 65static void
67echo_cb (void *cls, struct GNUNET_SERVER_Client *client, 66echo_cb(void *cls, struct GNUNET_SERVER_Client *client,
68 const struct GNUNET_MessageHeader *message) 67 const struct GNUNET_MessageHeader *message)
69{ 68{
70 struct CopyContext *cc; 69 struct CopyContext *cc;
71 struct GNUNET_MessageHeader *cpy; 70 struct GNUNET_MessageHeader *cpy;
72 71
73 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 72 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
74 "Receiving message from client, bouncing back\n"); 73 "Receiving message from client, bouncing back\n");
75 GNUNET_assert (sizeof (struct GNUNET_MessageHeader) == ntohs (message->size)); 74 GNUNET_assert(sizeof(struct GNUNET_MessageHeader) == ntohs(message->size));
76 cc = GNUNET_new (struct CopyContext); 75 cc = GNUNET_new(struct CopyContext);
77 cc->client = client; 76 cc->client = client;
78 cpy = GNUNET_malloc (ntohs (message->size)); 77 cpy = GNUNET_malloc(ntohs(message->size));
79 GNUNET_memcpy (cpy, message, ntohs (message->size)); 78 GNUNET_memcpy(cpy, message, ntohs(message->size));
80 cc->cpy = cpy; 79 cc->cpy = cpy;
81 GNUNET_assert (NULL != 80 GNUNET_assert(NULL !=
82 GNUNET_SERVER_notify_transmit_ready (client, 81 GNUNET_SERVER_notify_transmit_ready(client,
83 ntohs (message->size), 82 ntohs(message->size),
84 GNUNET_TIME_UNIT_SECONDS, 83 GNUNET_TIME_UNIT_SECONDS,
85 &copy_msg, cc)); 84 &copy_msg, cc));
86} 85}
87 86
88 87
89static struct GNUNET_SERVER_MessageHandler handlers[] = { 88static struct GNUNET_SERVER_MessageHandler handlers[] = {
90 {&echo_cb, NULL, MY_TYPE, sizeof (struct GNUNET_MessageHeader)}, 89 { &echo_cb, NULL, MY_TYPE, sizeof(struct GNUNET_MessageHeader) },
91 {NULL, NULL, 0, 0} 90 { NULL, NULL, 0, 0 }
92}; 91};
93 92
94 93
95static void 94static void
96handle_bounce (void *cls, 95handle_bounce(void *cls,
97 const struct GNUNET_MessageHeader *got) 96 const struct GNUNET_MessageHeader *got)
98{ 97{
99 int *ok = cls; 98 int *ok = cls;
100 99
101 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 100 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
102 "Receiving bounce, checking content\n"); 101 "Receiving bounce, checking content\n");
103 GNUNET_assert (NULL != got); 102 GNUNET_assert(NULL != got);
104 GNUNET_MQ_destroy (mq); 103 GNUNET_MQ_destroy(mq);
105 mq = NULL; 104 mq = NULL;
106 GNUNET_SERVER_destroy (server); 105 GNUNET_SERVER_destroy(server);
107 server = NULL; 106 server = NULL;
108 *ok = 0; 107 *ok = 0;
109} 108}
@@ -118,15 +117,15 @@ handle_bounce (void *cls,
118 * @param error error code 117 * @param error error code
119 */ 118 */
120static void 119static void
121mq_error_handler (void *cls, 120mq_error_handler(void *cls,
122 enum GNUNET_MQ_Error error) 121 enum GNUNET_MQ_Error error)
123{ 122{
124 GNUNET_assert (0); /* should never happen */ 123 GNUNET_assert(0); /* should never happen */
125} 124}
126 125
127 126
128static void 127static void
129task (void *cls) 128task(void *cls)
130{ 129{
131 struct sockaddr_in sa; 130 struct sockaddr_in sa;
132 struct sockaddr *sap[2]; 131 struct sockaddr *sap[2];
@@ -134,121 +133,121 @@ task (void *cls)
134 struct GNUNET_MQ_Envelope *env; 133 struct GNUNET_MQ_Envelope *env;
135 struct GNUNET_MessageHeader *msg; 134 struct GNUNET_MessageHeader *msg;
136 struct GNUNET_MQ_MessageHandler chandlers[] = { 135 struct GNUNET_MQ_MessageHandler chandlers[] = {
137 GNUNET_MQ_hd_fixed_size (bounce, 136 GNUNET_MQ_hd_fixed_size(bounce,
138 MY_TYPE, 137 MY_TYPE,
139 struct GNUNET_MessageHeader, 138 struct GNUNET_MessageHeader,
140 cls), 139 cls),
141 GNUNET_MQ_handler_end () 140 GNUNET_MQ_handler_end()
142 }; 141 };
143 142
144 /* test IPC between client and server */ 143 /* test IPC between client and server */
145 sap[0] = (struct sockaddr *) &sa; 144 sap[0] = (struct sockaddr *)&sa;
146 slens[0] = sizeof (sa); 145 slens[0] = sizeof(sa);
147 sap[1] = NULL; 146 sap[1] = NULL;
148 slens[1] = 0; 147 slens[1] = 0;
149 memset (&sa, 0, sizeof (sa)); 148 memset(&sa, 0, sizeof(sa));
150#if HAVE_SOCKADDR_IN_SIN_LEN 149#if HAVE_SOCKADDR_IN_SIN_LEN
151 sa.sin_len = sizeof (sa); 150 sa.sin_len = sizeof(sa);
152#endif 151#endif
153 sa.sin_family = AF_INET; 152 sa.sin_family = AF_INET;
154 sa.sin_port = htons (PORT); 153 sa.sin_port = htons(PORT);
155 server = 154 server =
156 GNUNET_SERVER_create (NULL, NULL, sap, slens, 155 GNUNET_SERVER_create(NULL, NULL, sap, slens,
157 GNUNET_TIME_relative_multiply 156 GNUNET_TIME_relative_multiply
158 (GNUNET_TIME_UNIT_MILLISECONDS, 10000), GNUNET_NO); 157 (GNUNET_TIME_UNIT_MILLISECONDS, 10000), GNUNET_NO);
159 GNUNET_assert (server != NULL); 158 GNUNET_assert(server != NULL);
160 handlers[0].callback_cls = cls; 159 handlers[0].callback_cls = cls;
161 handlers[1].callback_cls = cls; 160 handlers[1].callback_cls = cls;
162 GNUNET_SERVER_add_handlers (server, handlers); 161 GNUNET_SERVER_add_handlers(server, handlers);
163 mq = GNUNET_CLIENT_connect (cfg, 162 mq = GNUNET_CLIENT_connect(cfg,
164 MYNAME, 163 MYNAME,
165 chandlers, 164 chandlers,
166 &mq_error_handler, 165 &mq_error_handler,
167 NULL); 166 NULL);
168 GNUNET_assert (NULL != mq); 167 GNUNET_assert(NULL != mq);
169 env = GNUNET_MQ_msg (msg, 168 env = GNUNET_MQ_msg(msg,
170 MY_TYPE); 169 MY_TYPE);
171 GNUNET_MQ_send (mq, 170 GNUNET_MQ_send(mq,
172 env); 171 env);
173} 172}
174 173
175 174
176int 175int
177main (int argc, char *argv[]) 176main(int argc, char *argv[])
178{ 177{
179 int ok; 178 int ok;
180 int status; 179 int status;
181 const char *socksport = "1081"; 180 const char *socksport = "1081";
182 181
183 GNUNET_log_setup ("test_client", 182 GNUNET_log_setup("test_client",
184 "WARNING", 183 "WARNING",
185 NULL); 184 NULL);
186 185
187 pid_t pid = fork(); 186 pid_t pid = fork();
188 GNUNET_assert (pid >= 0); 187 GNUNET_assert(pid >= 0);
189 if (pid == 0) 188 if (pid == 0)
190 { 189 {
191 execlp ("ssh", 190 execlp("ssh",
192 "ssh","-D",socksport, 191 "ssh", "-D", socksport,
193 "-o","BatchMode yes", 192 "-o", "BatchMode yes",
194 "-o","UserKnownHostsFile /tmp/gnunet_test_socks_ssh_garbage", 193 "-o", "UserKnownHostsFile /tmp/gnunet_test_socks_ssh_garbage",
195 "-o","StrictHostKeyChecking no", 194 "-o", "StrictHostKeyChecking no",
196 "127.0.0.1","-N",(char*)NULL); 195 "127.0.0.1", "-N", (char*)NULL);
197 perror ("execlp (\"ssh\",\"ssh\",...,\"-D\",\"1081\",\"127.0.0.1\",\"-N\") "); 196 perror("execlp (\"ssh\",\"ssh\",...,\"-D\",\"1081\",\"127.0.0.1\",\"-N\") ");
198 printf ("" 197 printf(""
199"Please ensure you have ssh installed and have sshd installed and running :\n" 198 "Please ensure you have ssh installed and have sshd installed and running :\n"
200"\tsudo apt-get install openssh-client openssh-server\n" 199 "\tsudo apt-get install openssh-client openssh-server\n"
201"If you run Tor as a network proxy then Tor might prevent ssh from connecting\n" 200 "If you run Tor as a network proxy then Tor might prevent ssh from connecting\n"
202"to localhost. Please either run make check from an unproxied user, or else\n" 201 "to localhost. Please either run make check from an unproxied user, or else\n"
203"add these lines to the beginning of your ~/.ssh/config file :" 202 "add these lines to the beginning of your ~/.ssh/config file :"
204"\tHost 127.0.0.1 localhost\n" 203 "\tHost 127.0.0.1 localhost\n"
205"\t CheckHostIP no\n" 204 "\t CheckHostIP no\n"
206"\t Protocol 2\n" 205 "\t Protocol 2\n"
207"\t ProxyCommand nc 127.0.0.1 22\n"); 206 "\t ProxyCommand nc 127.0.0.1 22\n");
208 kill (getppid(), SIGALRM); 207 kill(getppid(), SIGALRM);
209 return 1; 208 return 1;
210 } 209 }
211 if (0 != sleep (1)) 210 if (0 != sleep(1))
212 { 211 {
213 /* sleep interrupted, likely SIGALRM, failure to 212 /* sleep interrupted, likely SIGALRM, failure to
214 launch child, terminate */ 213 launch child, terminate */
215 printf ("" 214 printf(""
216"Please ensure you have ssh installed and have sshd installed and running :\n" 215 "Please ensure you have ssh installed and have sshd installed and running :\n"
217"\tsudo apt-get install openssh-client openssh-server\n" 216 "\tsudo apt-get install openssh-client openssh-server\n"
218"If you run Tor as a network proxy then Tor might prevent ssh from connecting\n" 217 "If you run Tor as a network proxy then Tor might prevent ssh from connecting\n"
219"to localhost. Please either run make check from an unproxied user, or else\n" 218 "to localhost. Please either run make check from an unproxied user, or else\n"
220"add these lines to the beginning of your ~/.ssh/config file :" 219 "add these lines to the beginning of your ~/.ssh/config file :"
221"\tHost 127.0.0.1 localhost\n" 220 "\tHost 127.0.0.1 localhost\n"
222"\t CheckHostIP no\n" 221 "\t CheckHostIP no\n"
223"\t Protocol 2\n" 222 "\t Protocol 2\n"
224"\t ProxyCommand nc 127.0.0.1 22\n"); 223 "\t ProxyCommand nc 127.0.0.1 22\n");
225 return 77; 224 return 77;
226 } 225 }
227 /* check if child exec()ed but died */ 226 /* check if child exec()ed but died */
228 if (0 != waitpid (pid, &status, WNOHANG)) 227 if (0 != waitpid(pid, &status, WNOHANG))
229 { 228 {
230 printf ("" 229 printf(""
231"If you run Tor as a network proxy then Tor might prevent ssh from connecting\n" 230 "If you run Tor as a network proxy then Tor might prevent ssh from connecting\n"
232"to localhost. Please either run make check from an unproxied user, or else\n" 231 "to localhost. Please either run make check from an unproxied user, or else\n"
233"add these lines to the beginning of your ~/.ssh/config file :" 232 "add these lines to the beginning of your ~/.ssh/config file :"
234"\tHost 127.0.0.1 localhost\n" 233 "\tHost 127.0.0.1 localhost\n"
235"\t CheckHostIP no\n" 234 "\t CheckHostIP no\n"
236"\t Protocol 2\n" 235 "\t Protocol 2\n"
237"\t ProxyCommand nc 127.0.0.1 22\n"); 236 "\t ProxyCommand nc 127.0.0.1 22\n");
238 return 77; 237 return 77;
239 } 238 }
240 239
241 cfg = GNUNET_CONFIGURATION_create (); 240 cfg = GNUNET_CONFIGURATION_create();
242 GNUNET_CONFIGURATION_set_value_string (cfg, MYNAME, "SOCKSHOST", "127.0.0.1"); 241 GNUNET_CONFIGURATION_set_value_string(cfg, MYNAME, "SOCKSHOST", "127.0.0.1");
243 GNUNET_CONFIGURATION_set_value_string (cfg, MYNAME, "SOCKSPORT", socksport); 242 GNUNET_CONFIGURATION_set_value_string(cfg, MYNAME, "SOCKSPORT", socksport);
244 GNUNET_CONFIGURATION_set_value_number (cfg, MYNAME, "PORT", PORT); 243 GNUNET_CONFIGURATION_set_value_number(cfg, MYNAME, "PORT", PORT);
245 GNUNET_CONFIGURATION_set_value_string (cfg, MYNAME, "HOSTNAME", "127.0.0.1"); 244 GNUNET_CONFIGURATION_set_value_string(cfg, MYNAME, "HOSTNAME", "127.0.0.1");
246 ok = 1; 245 ok = 1;
247 GNUNET_SCHEDULER_run (&task, &ok); 246 GNUNET_SCHEDULER_run(&task, &ok);
248 GNUNET_CONFIGURATION_destroy (cfg); 247 GNUNET_CONFIGURATION_destroy(cfg);
249 248
250 GNUNET_break (0 == kill (pid, SIGTERM)); 249 GNUNET_break(0 == kill(pid, SIGTERM));
251 GNUNET_break (pid == waitpid (pid, &status, 0)); 250 GNUNET_break(pid == waitpid(pid, &status, 0));
252 return ok; 251 return ok;
253} 252}
254 253
diff --git a/src/util/test_speedup.c b/src/util/test_speedup.c
index a46d83dc3..eacc879df 100644
--- a/src/util/test_speedup.c
+++ b/src/util/test_speedup.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_speedup.c 21 * @file util/test_speedup.c
22 * @brief testcase for speedup.c 22 * @brief testcase for speedup.c
@@ -47,19 +47,19 @@ static unsigned int cycles;
47 * @param tc scheduler context, unused 47 * @param tc scheduler context, unused
48 */ 48 */
49static void 49static void
50run (void *cls) 50run(void *cls)
51{ 51{
52 cycles++; 52 cycles++;
53 fprintf (stderr, "..%u", cycles); 53 fprintf(stderr, "..%u", cycles);
54 if (cycles <= 5) 54 if (cycles <= 5)
55 { 55 {
56 GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_SECONDS, 56 GNUNET_SCHEDULER_add_delayed(GNUNET_TIME_UNIT_SECONDS,
57 &run, 57 &run,
58 NULL); 58 NULL);
59 return; 59 return;
60 } 60 }
61 end = GNUNET_TIME_absolute_get(); 61 end = GNUNET_TIME_absolute_get();
62 fprintf (stderr, "\n"); 62 fprintf(stderr, "\n");
63 fflush(stdout); 63 fflush(stdout);
64} 64}
65 65
@@ -68,23 +68,23 @@ run (void *cls)
68 * 68 *
69 */ 69 */
70static void 70static void
71check (void *cls, 71check(void *cls,
72 char *const *args, 72 char *const *args,
73 const char *cfgfile, 73 const char *cfgfile,
74 const struct GNUNET_CONFIGURATION_Handle *cfg) 74 const struct GNUNET_CONFIGURATION_Handle *cfg)
75{ 75{
76 fprintf (stderr, "0"); 76 fprintf(stderr, "0");
77 fflush (stdout); 77 fflush(stdout);
78 GNUNET_SCHEDULER_add_now (&run, NULL); 78 GNUNET_SCHEDULER_add_now(&run, NULL);
79} 79}
80 80
81 81
82int 82int
83main (int argc, char *argv[]) 83main(int argc, char *argv[])
84{ 84{
85 static char *const argvn[] = { 85 static char *const argvn[] = {
86 "test-speedup", 86 "test-speedup",
87 "-c", "test_speedup_data.conf", 87 "-c", "test_speedup_data.conf",
88 NULL 88 NULL
89 }; 89 };
90 static struct GNUNET_GETOPT_CommandLineOption options[] = { 90 static struct GNUNET_GETOPT_CommandLineOption options[] = {
@@ -94,30 +94,30 @@ main (int argc, char *argv[])
94 time_t end_real; 94 time_t end_real;
95 struct GNUNET_TIME_Relative delta; 95 struct GNUNET_TIME_Relative delta;
96 96
97 start_real = time (NULL); 97 start_real = time(NULL);
98 start = GNUNET_TIME_absolute_get(); 98 start = GNUNET_TIME_absolute_get();
99 GNUNET_PROGRAM_run ((sizeof (argvn) / sizeof (char *)) - 1, argvn, "test-speedup", 99 GNUNET_PROGRAM_run((sizeof(argvn) / sizeof(char *)) - 1, argvn, "test-speedup",
100 "nohelp", options, &check, NULL); 100 "nohelp", options, &check, NULL);
101 101
102 end_real = time (NULL); 102 end_real = time(NULL);
103 delta = GNUNET_TIME_absolute_get_difference (start, end); 103 delta = GNUNET_TIME_absolute_get_difference(start, end);
104 104
105 if (delta.rel_value_us > ((end_real - start_real) * 1500LL * 1000LL)) 105 if (delta.rel_value_us > ((end_real - start_real) * 1500LL * 1000LL))
106 { 106 {
107 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 107 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
108 "Execution time in GNUnet time: %s\n", 108 "Execution time in GNUnet time: %s\n",
109 GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES)); 109 GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_YES));
110 GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, 110 GNUNET_log(GNUNET_ERROR_TYPE_DEBUG,
111 "Execution time in system time: %llu ms\n", 111 "Execution time in system time: %llu ms\n",
112 (unsigned long long) ((end_real - start_real) * 1000LL)); 112 (unsigned long long)((end_real - start_real) * 1000LL));
113 return 0; 113 return 0;
114 } 114 }
115 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 115 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
116 "Execution time in GNUnet time: %s\n", 116 "Execution time in GNUnet time: %s\n",
117 GNUNET_STRINGS_relative_time_to_string (delta, GNUNET_YES)); 117 GNUNET_STRINGS_relative_time_to_string(delta, GNUNET_YES));
118 GNUNET_log (GNUNET_ERROR_TYPE_ERROR, 118 GNUNET_log(GNUNET_ERROR_TYPE_ERROR,
119 "Execution time in system time: %llu ms\n", 119 "Execution time in system time: %llu ms\n",
120 (unsigned long long) ((end_real - start_real) * 1000LL)); 120 (unsigned long long)((end_real - start_real) * 1000LL));
121 return 1; 121 return 1;
122} 122}
123 123
diff --git a/src/util/test_strings.c b/src/util/test_strings.c
index 9e4e808ef..4a7861965 100644
--- a/src/util/test_strings.c
+++ b/src/util/test_strings.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_strings.c 21 * @file util/test_strings.c
22 * @brief testcase for strings.c 22 * @brief testcase for strings.c
@@ -25,12 +25,12 @@
25#include "gnunet_util_lib.h" 25#include "gnunet_util_lib.h"
26 26
27 27
28#define WANT(a,b) if (0 != strcmp(a,b)) { fprintf(stderr, "Got `%s', wanted `%s'\n", b, a); GNUNET_free(b); GNUNET_break(0); return 1;} else { GNUNET_free (b); } 28#define WANT(a, b) if (0 != strcmp(a, b)) { fprintf(stderr, "Got `%s', wanted `%s'\n", b, a); GNUNET_free(b); GNUNET_break(0); return 1; } else { GNUNET_free(b); }
29#define WANTNF(a,b) do { if (0 != strcmp(a,b)) { fprintf(stderr, "Got `%s', wanted `%s'\n", b, a); GNUNET_break(0); return 1;} } while (0) 29#define WANTNF(a, b) do { if (0 != strcmp(a, b)) { fprintf(stderr, "Got `%s', wanted `%s'\n", b, a); GNUNET_break(0); return 1; } } while (0)
30#define WANTB(a,b,l) if (0 != memcmp(a,b,l)) { GNUNET_break(0); return 1;} else { } 30#define WANTB(a, b, l) if (0 != memcmp(a, b, l)) { GNUNET_break(0); return 1; } else { }
31 31
32int 32int
33main (int argc, char *argv[]) 33main(int argc, char *argv[])
34{ 34{
35 char buf[128]; 35 char buf[128];
36 char *r; 36 char *r;
@@ -42,103 +42,103 @@ main (int argc, char *argv[])
42 struct GNUNET_TIME_Relative rtx; 42 struct GNUNET_TIME_Relative rtx;
43 const char *hdir; 43 const char *hdir;
44 44
45 GNUNET_log_setup ("test_strings", "ERROR", NULL); 45 GNUNET_log_setup("test_strings", "ERROR", NULL);
46 sprintf (buf, "4 %s", _( /* size unit */ "b")); 46 sprintf(buf, "4 %s", _(/* size unit */ "b"));
47 b = GNUNET_STRINGS_byte_size_fancy (4); 47 b = GNUNET_STRINGS_byte_size_fancy(4);
48 WANT (buf, b); 48 WANT(buf, b);
49 sprintf (buf, "10 %s", _( /* size unit */ "KiB")); 49 sprintf(buf, "10 %s", _(/* size unit */ "KiB"));
50 b = GNUNET_STRINGS_byte_size_fancy (10240); 50 b = GNUNET_STRINGS_byte_size_fancy(10240);
51 WANT (buf, b); 51 WANT(buf, b);
52 sprintf (buf, "10 %s", _( /* size unit */ "TiB")); 52 sprintf(buf, "10 %s", _(/* size unit */ "TiB"));
53 b = GNUNET_STRINGS_byte_size_fancy (10240LL * 1024LL * 1024LL * 1024LL); 53 b = GNUNET_STRINGS_byte_size_fancy(10240LL * 1024LL * 1024LL * 1024LL);
54 WANT (buf, b); 54 WANT(buf, b);
55 sprintf (buf, "4 %s", _( /* time unit */ "ms")); 55 sprintf(buf, "4 %s", _(/* time unit */ "ms"));
56 bc = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_relative_multiply 56 bc = GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_relative_multiply
57 (GNUNET_TIME_UNIT_MILLISECONDS, 57 (GNUNET_TIME_UNIT_MILLISECONDS,
58 4), GNUNET_YES); 58 4), GNUNET_YES);
59 WANTNF (buf, bc); 59 WANTNF(buf, bc);
60 sprintf (buf, "7 %s", _( /* time unit */ "s")); 60 sprintf(buf, "7 %s", _(/* time unit */ "s"));
61 bc = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_relative_multiply 61 bc = GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_relative_multiply
62 (GNUNET_TIME_UNIT_MILLISECONDS, 62 (GNUNET_TIME_UNIT_MILLISECONDS,
63 7 * 1000), GNUNET_YES); 63 7 * 1000), GNUNET_YES);
64 WANTNF (buf, bc); 64 WANTNF(buf, bc);
65 sprintf (buf, "7 %s", _( /* time unit */ "h")); 65 sprintf(buf, "7 %s", _(/* time unit */ "h"));
66 bc = GNUNET_STRINGS_relative_time_to_string (GNUNET_TIME_relative_multiply 66 bc = GNUNET_STRINGS_relative_time_to_string(GNUNET_TIME_relative_multiply
67 (GNUNET_TIME_UNIT_MILLISECONDS, 67 (GNUNET_TIME_UNIT_MILLISECONDS,
68 7 * 60 * 60 * 1000), GNUNET_YES); 68 7 * 60 * 60 * 1000), GNUNET_YES);
69 WANTNF (buf, bc); 69 WANTNF(buf, bc);
70#ifndef MINGW 70#ifndef MINGW
71 hdir = getenv ("HOME"); 71 hdir = getenv("HOME");
72#else 72#else
73 hdir = getenv ("USERPROFILE"); 73 hdir = getenv("USERPROFILE");
74#endif 74#endif
75 GNUNET_snprintf (buf, sizeof (buf), "%s%s", hdir, DIR_SEPARATOR_STR); 75 GNUNET_snprintf(buf, sizeof(buf), "%s%s", hdir, DIR_SEPARATOR_STR);
76 b = GNUNET_STRINGS_filename_expand ("~"); 76 b = GNUNET_STRINGS_filename_expand("~");
77 GNUNET_assert (b != NULL); 77 GNUNET_assert(b != NULL);
78 WANT (buf, b); 78 WANT(buf, b);
79 GNUNET_STRINGS_buffer_fill (buf, sizeof (buf), 3, "a", "btx", "c"); 79 GNUNET_STRINGS_buffer_fill(buf, sizeof(buf), 3, "a", "btx", "c");
80 WANTB ("a\0btx\0c", buf, 8); 80 WANTB("a\0btx\0c", buf, 8);
81 if (6 != GNUNET_STRINGS_buffer_tokenize (buf, sizeof (buf), 2, &r, &b)) 81 if (6 != GNUNET_STRINGS_buffer_tokenize(buf, sizeof(buf), 2, &r, &b))
82 return 1; 82 return 1;
83 r = GNUNET_strdup (r); 83 r = GNUNET_strdup(r);
84 WANT ("a", r); 84 WANT("a", r);
85 b = GNUNET_strdup (b); 85 b = GNUNET_strdup(b);
86 WANT ("btx", b); 86 WANT("btx", b);
87 if (0 != GNUNET_STRINGS_buffer_tokenize (buf, 2, 2, &r, &b)) 87 if (0 != GNUNET_STRINGS_buffer_tokenize(buf, 2, 2, &r, &b))
88 return 1; 88 return 1;
89 at.abs_value_us = 5000000; 89 at.abs_value_us = 5000000;
90 bc = GNUNET_STRINGS_absolute_time_to_string (at); 90 bc = GNUNET_STRINGS_absolute_time_to_string(at);
91 /* bc should be something like "Wed Dec 31 17:00:05 1969" 91 /* bc should be something like "Wed Dec 31 17:00:05 1969"
92 * where the details of the day and hour depend on the timezone; 92 * where the details of the day and hour depend on the timezone;
93 * however, the "0:05 19" should always be there; hence: */ 93 * however, the "0:05 19" should always be there; hence: */
94 if (NULL == strstr (bc, "0:05 19")) 94 if (NULL == strstr(bc, "0:05 19"))
95 { 95 {
96 fprintf (stderr, "Got %s\n", bc); 96 fprintf(stderr, "Got %s\n", bc);
97 GNUNET_break (0); 97 GNUNET_break(0);
98 return 1; 98 return 1;
99 } 99 }
100 b = GNUNET_STRINGS_to_utf8 ("TEST", 4, "ASCII"); 100 b = GNUNET_STRINGS_to_utf8("TEST", 4, "ASCII");
101 WANT ("TEST", b); 101 WANT("TEST", b);
102 102
103 at = GNUNET_TIME_UNIT_FOREVER_ABS; 103 at = GNUNET_TIME_UNIT_FOREVER_ABS;
104 bc = GNUNET_STRINGS_absolute_time_to_string (at); 104 bc = GNUNET_STRINGS_absolute_time_to_string(at);
105 GNUNET_assert (GNUNET_OK == 105 GNUNET_assert(GNUNET_OK ==
106 GNUNET_STRINGS_fancy_time_to_absolute (bc, &atx)); 106 GNUNET_STRINGS_fancy_time_to_absolute(bc, &atx));
107 GNUNET_assert (atx.abs_value_us == at.abs_value_us); 107 GNUNET_assert(atx.abs_value_us == at.abs_value_us);
108 108
109 at.abs_value_us = 50000000000; 109 at.abs_value_us = 50000000000;
110 bc = GNUNET_STRINGS_absolute_time_to_string (at); 110 bc = GNUNET_STRINGS_absolute_time_to_string(at);
111 111
112 GNUNET_assert (GNUNET_OK == 112 GNUNET_assert(GNUNET_OK ==
113 GNUNET_STRINGS_fancy_time_to_absolute (bc, &atx)); 113 GNUNET_STRINGS_fancy_time_to_absolute(bc, &atx));
114 114
115 if (atx.abs_value_us != at.abs_value_us) 115 if (atx.abs_value_us != at.abs_value_us)
116 {
117#ifdef WINDOWS
118 DWORD tzv;
119 TIME_ZONE_INFORMATION tzi;
120 tzv = GetTimeZoneInformation (&tzi);
121 if (TIME_ZONE_ID_INVALID != tzv)
122 { 116 {
123 atx.abs_value_us -= 1000LL * 1000LL * tzi.Bias * 60LL; 117#ifdef WINDOWS
124 } 118 DWORD tzv;
125 if (atx.abs_value_us == at.abs_value_us) 119 TIME_ZONE_INFORMATION tzi;
126 fprintf (stderr, 120 tzv = GetTimeZoneInformation(&tzi);
127 "WARNING: GNUNET_STRINGS_fancy_time_to_absolute() miscalculates timezone!\n"); 121 if (TIME_ZONE_ID_INVALID != tzv)
122 {
123 atx.abs_value_us -= 1000LL * 1000LL * tzi.Bias * 60LL;
124 }
125 if (atx.abs_value_us == at.abs_value_us)
126 fprintf(stderr,
127 "WARNING: GNUNET_STRINGS_fancy_time_to_absolute() miscalculates timezone!\n");
128#endif 128#endif
129 GNUNET_assert (0); 129 GNUNET_assert(0);
130 } 130 }
131 131
132 GNUNET_log_skip (2, GNUNET_NO); 132 GNUNET_log_skip(2, GNUNET_NO);
133 b = GNUNET_STRINGS_to_utf8 ("TEST", 4, "unknown"); 133 b = GNUNET_STRINGS_to_utf8("TEST", 4, "unknown");
134 GNUNET_log_skip (0, GNUNET_YES); 134 GNUNET_log_skip(0, GNUNET_YES);
135 WANT ("TEST", b); 135 WANT("TEST", b);
136 136
137 GNUNET_assert (GNUNET_OK == 137 GNUNET_assert(GNUNET_OK ==
138 GNUNET_STRINGS_fancy_time_to_relative ("15m", &rt)); 138 GNUNET_STRINGS_fancy_time_to_relative("15m", &rt));
139 GNUNET_assert (GNUNET_OK == 139 GNUNET_assert(GNUNET_OK ==
140 GNUNET_STRINGS_fancy_time_to_relative ("15 m", &rtx)); 140 GNUNET_STRINGS_fancy_time_to_relative("15 m", &rtx));
141 GNUNET_assert (rt.rel_value_us == rtx.rel_value_us); 141 GNUNET_assert(rt.rel_value_us == rtx.rel_value_us);
142 142
143 return 0; 143 return 0;
144} 144}
diff --git a/src/util/test_strings_to_data.c b/src/util/test_strings_to_data.c
index f7d20441f..d719e950a 100644
--- a/src/util/test_strings_to_data.c
+++ b/src/util/test_strings_to_data.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_strings_to_data.c 21 * @file util/test_strings_to_data.c
22 * @brief testcase for strings.c 22 * @brief testcase for strings.c
@@ -26,7 +26,7 @@
26 26
27 27
28int 28int
29main (int argc, char *argv[]) 29main(int argc, char *argv[])
30{ 30{
31 char buf[1024]; 31 char buf[1024];
32 char *end; 32 char *end;
@@ -35,26 +35,27 @@ main (int argc, char *argv[])
35 unsigned int i; 35 unsigned int i;
36 int ret = 0; 36 int ret = 0;
37 37
38 GNUNET_log_setup ("util", "DEBUG", NULL); 38 GNUNET_log_setup("util", "DEBUG", NULL);
39 for (i=0;i<sizeof(src);i++) 39 for (i = 0; i < sizeof(src); i++)
40 {
41 memset (src, i, sizeof (src));
42 memset (dst, i+1, sizeof (dst));
43
44 end = GNUNET_STRINGS_data_to_string (&src, i, buf, sizeof (buf));
45 GNUNET_assert (NULL != end);
46 end[0] = '\0';
47 if (GNUNET_OK !=
48 GNUNET_STRINGS_string_to_data (buf, strlen (buf), dst, i))
49 {
50 fprintf (stderr, "%u failed decode (%u bytes)\n", i, (unsigned int) strlen (buf));
51 ret = 1;
52 } else if (0 != memcmp (src, dst, i))
53 { 40 {
54 fprintf (stderr, "%u wrong decode (%u bytes)\n", i, (unsigned int) strlen (buf)); 41 memset(src, i, sizeof(src));
55 ret = 1; 42 memset(dst, i + 1, sizeof(dst));
43
44 end = GNUNET_STRINGS_data_to_string(&src, i, buf, sizeof(buf));
45 GNUNET_assert(NULL != end);
46 end[0] = '\0';
47 if (GNUNET_OK !=
48 GNUNET_STRINGS_string_to_data(buf, strlen(buf), dst, i))
49 {
50 fprintf(stderr, "%u failed decode (%u bytes)\n", i, (unsigned int)strlen(buf));
51 ret = 1;
52 }
53 else if (0 != memcmp(src, dst, i))
54 {
55 fprintf(stderr, "%u wrong decode (%u bytes)\n", i, (unsigned int)strlen(buf));
56 ret = 1;
57 }
56 } 58 }
57 }
58 return ret; 59 return ret;
59} 60}
60 61
diff --git a/src/util/test_time.c b/src/util/test_time.c
index 6f4a6332b..b46cac34d 100644
--- a/src/util/test_time.c
+++ b/src/util/test_time.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20/** 20/**
21 * @file util/test_time.c 21 * @file util/test_time.c
22 * @brief testcase for time.c 22 * @brief testcase for time.c
@@ -26,7 +26,7 @@
26 26
27 27
28int 28int
29main (int argc, char *argv[]) 29main(int argc, char *argv[])
30{ 30{
31 struct GNUNET_TIME_Absolute now; 31 struct GNUNET_TIME_Absolute now;
32 struct GNUNET_TIME_AbsoluteNBO nown; 32 struct GNUNET_TIME_AbsoluteNBO nown;
@@ -41,212 +41,212 @@ main (int argc, char *argv[])
41 struct GNUNET_TIME_RelativeNBO reln; 41 struct GNUNET_TIME_RelativeNBO reln;
42 unsigned int i; 42 unsigned int i;
43 43
44 GNUNET_log_setup ("test-time", "WARNING", NULL); 44 GNUNET_log_setup("test-time", "WARNING", NULL);
45 forever = GNUNET_TIME_UNIT_FOREVER_ABS; 45 forever = GNUNET_TIME_UNIT_FOREVER_ABS;
46 relForever = GNUNET_TIME_UNIT_FOREVER_REL; 46 relForever = GNUNET_TIME_UNIT_FOREVER_REL;
47 relUnit = GNUNET_TIME_UNIT_MILLISECONDS; 47 relUnit = GNUNET_TIME_UNIT_MILLISECONDS;
48 zero.abs_value_us = 0; 48 zero.abs_value_us = 0;
49 49
50 last = now = GNUNET_TIME_absolute_get (); 50 last = now = GNUNET_TIME_absolute_get();
51 while (now.abs_value_us == last.abs_value_us) 51 while (now.abs_value_us == last.abs_value_us)
52 now = GNUNET_TIME_absolute_get (); 52 now = GNUNET_TIME_absolute_get();
53 GNUNET_assert (now.abs_value_us > last.abs_value_us); 53 GNUNET_assert(now.abs_value_us > last.abs_value_us);
54 54
55 /* test overflow checking in multiply */ 55 /* test overflow checking in multiply */
56 rel = GNUNET_TIME_UNIT_MILLISECONDS; 56 rel = GNUNET_TIME_UNIT_MILLISECONDS;
57 GNUNET_log_skip (1, GNUNET_NO); 57 GNUNET_log_skip(1, GNUNET_NO);
58 for (i = 0; i < 55; i++) 58 for (i = 0; i < 55; i++)
59 rel = GNUNET_TIME_relative_multiply (rel, 2); 59 rel = GNUNET_TIME_relative_multiply(rel, 2);
60 GNUNET_log_skip (0, GNUNET_NO); 60 GNUNET_log_skip(0, GNUNET_NO);
61 GNUNET_assert (rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us); 61 GNUNET_assert(rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us);
62 /*check zero */ 62 /*check zero */
63 rel.rel_value_us = (UINT64_MAX) - 1024; 63 rel.rel_value_us = (UINT64_MAX)-1024;
64 GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value_us == 64 GNUNET_assert(GNUNET_TIME_UNIT_ZERO.rel_value_us ==
65 GNUNET_TIME_relative_multiply (rel, 0).rel_value_us); 65 GNUNET_TIME_relative_multiply(rel, 0).rel_value_us);
66 66
67 /* test infinity-check for relative to absolute */ 67 /* test infinity-check for relative to absolute */
68 GNUNET_log_skip (1, GNUNET_NO); 68 GNUNET_log_skip(1, GNUNET_NO);
69 last = GNUNET_TIME_relative_to_absolute (rel); 69 last = GNUNET_TIME_relative_to_absolute(rel);
70 GNUNET_assert (last.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us); 70 GNUNET_assert(last.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us);
71 GNUNET_log_skip (0, GNUNET_YES); 71 GNUNET_log_skip(0, GNUNET_YES);
72 72
73 /* check relative to absolute */ 73 /* check relative to absolute */
74 rel.rel_value_us = 1000000; 74 rel.rel_value_us = 1000000;
75 GNUNET_assert (GNUNET_TIME_absolute_get ().abs_value_us < 75 GNUNET_assert(GNUNET_TIME_absolute_get().abs_value_us <
76 GNUNET_TIME_relative_to_absolute (rel).abs_value_us); 76 GNUNET_TIME_relative_to_absolute(rel).abs_value_us);
77 /*check forever */ 77 /*check forever */
78 rel.rel_value_us = UINT64_MAX; 78 rel.rel_value_us = UINT64_MAX;
79 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us == 79 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us ==
80 GNUNET_TIME_relative_to_absolute (rel).abs_value_us); 80 GNUNET_TIME_relative_to_absolute(rel).abs_value_us);
81 /* check overflow for r2a */ 81 /* check overflow for r2a */
82 rel.rel_value_us = (UINT64_MAX) - 1024; 82 rel.rel_value_us = (UINT64_MAX)-1024;
83 GNUNET_log_skip (1, GNUNET_NO); 83 GNUNET_log_skip(1, GNUNET_NO);
84 last = GNUNET_TIME_relative_to_absolute (rel); 84 last = GNUNET_TIME_relative_to_absolute(rel);
85 GNUNET_log_skip (0, GNUNET_NO); 85 GNUNET_log_skip(0, GNUNET_NO);
86 GNUNET_assert (last.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us); 86 GNUNET_assert(last.abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us);
87 87
88 /* check overflow for relative add */ 88 /* check overflow for relative add */
89 GNUNET_log_skip (1, GNUNET_NO); 89 GNUNET_log_skip(1, GNUNET_NO);
90 rel = GNUNET_TIME_relative_add (rel, rel); 90 rel = GNUNET_TIME_relative_add(rel, rel);
91 GNUNET_log_skip (0, GNUNET_NO); 91 GNUNET_log_skip(0, GNUNET_NO);
92 GNUNET_assert (rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us); 92 GNUNET_assert(rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us);
93 93
94 GNUNET_log_skip (1, GNUNET_NO); 94 GNUNET_log_skip(1, GNUNET_NO);
95 rel = GNUNET_TIME_relative_add (relForever, relForever); 95 rel = GNUNET_TIME_relative_add(relForever, relForever);
96 GNUNET_log_skip (0, GNUNET_NO); 96 GNUNET_log_skip(0, GNUNET_NO);
97 GNUNET_assert (rel.rel_value_us == relForever.rel_value_us); 97 GNUNET_assert(rel.rel_value_us == relForever.rel_value_us);
98 98
99 GNUNET_log_skip (1, GNUNET_NO); 99 GNUNET_log_skip(1, GNUNET_NO);
100 rel = GNUNET_TIME_relative_add (relUnit, relUnit); 100 rel = GNUNET_TIME_relative_add(relUnit, relUnit);
101 GNUNET_assert (rel.rel_value_us == 2 * relUnit.rel_value_us); 101 GNUNET_assert(rel.rel_value_us == 2 * relUnit.rel_value_us);
102 102
103 /* check relation check in get_duration */ 103 /* check relation check in get_duration */
104 future.abs_value_us = now.abs_value_us + 1000000; 104 future.abs_value_us = now.abs_value_us + 1000000;
105 GNUNET_assert (GNUNET_TIME_absolute_get_difference (now, future).rel_value_us == 105 GNUNET_assert(GNUNET_TIME_absolute_get_difference(now, future).rel_value_us ==
106 1000000); 106 1000000);
107 GNUNET_assert (GNUNET_TIME_absolute_get_difference (future, now).rel_value_us == 107 GNUNET_assert(GNUNET_TIME_absolute_get_difference(future, now).rel_value_us ==
108 0); 108 0);
109 109
110 GNUNET_assert (GNUNET_TIME_absolute_get_difference (zero, forever).rel_value_us 110 GNUNET_assert(GNUNET_TIME_absolute_get_difference(zero, forever).rel_value_us
111 == forever.abs_value_us); 111 == forever.abs_value_us);
112 112
113 past.abs_value_us = now.abs_value_us - 1000000; 113 past.abs_value_us = now.abs_value_us - 1000000;
114 rel = GNUNET_TIME_absolute_get_duration (future); 114 rel = GNUNET_TIME_absolute_get_duration(future);
115 GNUNET_assert (rel.rel_value_us == 0); 115 GNUNET_assert(rel.rel_value_us == 0);
116 rel = GNUNET_TIME_absolute_get_duration (past); 116 rel = GNUNET_TIME_absolute_get_duration(past);
117 GNUNET_assert (rel.rel_value_us >= 1000000); 117 GNUNET_assert(rel.rel_value_us >= 1000000);
118 118
119 /* check get remaining */ 119 /* check get remaining */
120 rel = GNUNET_TIME_absolute_get_remaining (now); 120 rel = GNUNET_TIME_absolute_get_remaining(now);
121 GNUNET_assert (rel.rel_value_us == 0); 121 GNUNET_assert(rel.rel_value_us == 0);
122 rel = GNUNET_TIME_absolute_get_remaining (past); 122 rel = GNUNET_TIME_absolute_get_remaining(past);
123 GNUNET_assert (rel.rel_value_us == 0); 123 GNUNET_assert(rel.rel_value_us == 0);
124 rel = GNUNET_TIME_absolute_get_remaining (future); 124 rel = GNUNET_TIME_absolute_get_remaining(future);
125 GNUNET_assert (rel.rel_value_us > 0); 125 GNUNET_assert(rel.rel_value_us > 0);
126 GNUNET_assert (rel.rel_value_us <= 1000000); 126 GNUNET_assert(rel.rel_value_us <= 1000000);
127 forever = GNUNET_TIME_UNIT_FOREVER_ABS; 127 forever = GNUNET_TIME_UNIT_FOREVER_ABS;
128 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == 128 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
129 GNUNET_TIME_absolute_get_remaining (forever).rel_value_us); 129 GNUNET_TIME_absolute_get_remaining(forever).rel_value_us);
130 130
131 /* check endianess */ 131 /* check endianess */
132 reln = GNUNET_TIME_relative_hton (rel); 132 reln = GNUNET_TIME_relative_hton(rel);
133 GNUNET_assert (rel.rel_value_us == GNUNET_TIME_relative_ntoh (reln).rel_value_us); 133 GNUNET_assert(rel.rel_value_us == GNUNET_TIME_relative_ntoh(reln).rel_value_us);
134 nown = GNUNET_TIME_absolute_hton (now); 134 nown = GNUNET_TIME_absolute_hton(now);
135 GNUNET_assert (now.abs_value_us == GNUNET_TIME_absolute_ntoh (nown).abs_value_us); 135 GNUNET_assert(now.abs_value_us == GNUNET_TIME_absolute_ntoh(nown).abs_value_us);
136 136
137 /* check absolute addition */ 137 /* check absolute addition */
138 future = GNUNET_TIME_absolute_add (now, GNUNET_TIME_UNIT_SECONDS); 138 future = GNUNET_TIME_absolute_add(now, GNUNET_TIME_UNIT_SECONDS);
139 GNUNET_assert (future.abs_value_us == now.abs_value_us + 1000 * 1000LL); 139 GNUNET_assert(future.abs_value_us == now.abs_value_us + 1000 * 1000LL);
140 140
141 future = GNUNET_TIME_absolute_add (forever, GNUNET_TIME_UNIT_ZERO); 141 future = GNUNET_TIME_absolute_add(forever, GNUNET_TIME_UNIT_ZERO);
142 GNUNET_assert (future.abs_value_us == forever.abs_value_us); 142 GNUNET_assert(future.abs_value_us == forever.abs_value_us);
143 143
144 rel.rel_value_us = (UINT64_MAX) - 1024; 144 rel.rel_value_us = (UINT64_MAX)-1024;
145 now.abs_value_us = rel.rel_value_us; 145 now.abs_value_us = rel.rel_value_us;
146 future = GNUNET_TIME_absolute_add (now, rel); 146 future = GNUNET_TIME_absolute_add(now, rel);
147 GNUNET_assert (future.abs_value_us == forever.abs_value_us); 147 GNUNET_assert(future.abs_value_us == forever.abs_value_us);
148 148
149 /* check zero */ 149 /* check zero */
150 future = GNUNET_TIME_absolute_add (now, GNUNET_TIME_UNIT_ZERO); 150 future = GNUNET_TIME_absolute_add(now, GNUNET_TIME_UNIT_ZERO);
151 GNUNET_assert (future.abs_value_us == now.abs_value_us); 151 GNUNET_assert(future.abs_value_us == now.abs_value_us);
152 152
153 GNUNET_assert (forever.abs_value_us == 153 GNUNET_assert(forever.abs_value_us ==
154 GNUNET_TIME_absolute_subtract (forever, 154 GNUNET_TIME_absolute_subtract(forever,
155 GNUNET_TIME_UNIT_MINUTES).abs_value_us); 155 GNUNET_TIME_UNIT_MINUTES).abs_value_us);
156 /*check absolute subtract */ 156 /*check absolute subtract */
157 now.abs_value_us = 50000; 157 now.abs_value_us = 50000;
158 rel.rel_value_us = 100000; 158 rel.rel_value_us = 100000;
159 GNUNET_assert (GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us == 159 GNUNET_assert(GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us ==
160 (GNUNET_TIME_absolute_subtract (now, rel)).abs_value_us); 160 (GNUNET_TIME_absolute_subtract(now, rel)).abs_value_us);
161 rel.rel_value_us = 10000; 161 rel.rel_value_us = 10000;
162 GNUNET_assert (40000 == (GNUNET_TIME_absolute_subtract (now, rel)).abs_value_us); 162 GNUNET_assert(40000 == (GNUNET_TIME_absolute_subtract(now, rel)).abs_value_us);
163 163
164 /*check relative divide */ 164 /*check relative divide */
165 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == 165 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
166 (GNUNET_TIME_relative_divide (rel, 0)).rel_value_us); 166 (GNUNET_TIME_relative_divide(rel, 0)).rel_value_us);
167 167
168 rel = GNUNET_TIME_UNIT_FOREVER_REL; 168 rel = GNUNET_TIME_UNIT_FOREVER_REL;
169 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == 169 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
170 (GNUNET_TIME_relative_divide (rel, 2)).rel_value_us); 170 (GNUNET_TIME_relative_divide(rel, 2)).rel_value_us);
171 171
172 rel = GNUNET_TIME_relative_divide (relUnit, 2); 172 rel = GNUNET_TIME_relative_divide(relUnit, 2);
173 GNUNET_assert (rel.rel_value_us == relUnit.rel_value_us / 2); 173 GNUNET_assert(rel.rel_value_us == relUnit.rel_value_us / 2);
174 174
175 175
176 /* check Return absolute time of 0ms */ 176 /* check Return absolute time of 0ms */
177 zero = GNUNET_TIME_UNIT_ZERO_ABS; 177 zero = GNUNET_TIME_UNIT_ZERO_ABS;
178 178
179 /* check GNUNET_TIME_calculate_eta */ 179 /* check GNUNET_TIME_calculate_eta */
180 last.abs_value_us = GNUNET_TIME_absolute_get ().abs_value_us - 1024; 180 last.abs_value_us = GNUNET_TIME_absolute_get().abs_value_us - 1024;
181 forever = GNUNET_TIME_UNIT_FOREVER_ABS; 181 forever = GNUNET_TIME_UNIT_FOREVER_ABS;
182 forever.abs_value_us = forever.abs_value_us - 1024; 182 forever.abs_value_us = forever.abs_value_us - 1024;
183 GNUNET_assert (GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us == 183 GNUNET_assert(GNUNET_TIME_UNIT_ZERO_ABS.abs_value_us ==
184 GNUNET_TIME_calculate_eta (forever, 50000, 100000).rel_value_us); 184 GNUNET_TIME_calculate_eta(forever, 50000, 100000).rel_value_us);
185 /* check zero */ 185 /* check zero */
186 GNUNET_log_skip (1, GNUNET_NO); 186 GNUNET_log_skip(1, GNUNET_NO);
187 GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value_us == 187 GNUNET_assert(GNUNET_TIME_UNIT_ZERO.rel_value_us ==
188 (GNUNET_TIME_calculate_eta (last, 60000, 50000)).rel_value_us); 188 (GNUNET_TIME_calculate_eta(last, 60000, 50000)).rel_value_us);
189 GNUNET_log_skip (0, GNUNET_YES); 189 GNUNET_log_skip(0, GNUNET_YES);
190 /*check forever */ 190 /*check forever */
191 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == 191 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
192 (GNUNET_TIME_calculate_eta (last, 0, 50000)).rel_value_us); 192 (GNUNET_TIME_calculate_eta(last, 0, 50000)).rel_value_us);
193 193
194 /*check relative subtract */ 194 /*check relative subtract */
195 now = GNUNET_TIME_absolute_get (); 195 now = GNUNET_TIME_absolute_get();
196 rel.rel_value_us = now.abs_value_us; 196 rel.rel_value_us = now.abs_value_us;
197 relForever.rel_value_us = rel.rel_value_us + 1024; 197 relForever.rel_value_us = rel.rel_value_us + 1024;
198 GNUNET_assert (1024 == 198 GNUNET_assert(1024 ==
199 GNUNET_TIME_relative_subtract (relForever, rel).rel_value_us); 199 GNUNET_TIME_relative_subtract(relForever, rel).rel_value_us);
200 /*check zero */ 200 /*check zero */
201 GNUNET_assert (GNUNET_TIME_UNIT_ZERO.rel_value_us == 201 GNUNET_assert(GNUNET_TIME_UNIT_ZERO.rel_value_us ==
202 GNUNET_TIME_relative_subtract (rel, relForever).rel_value_us); 202 GNUNET_TIME_relative_subtract(rel, relForever).rel_value_us);
203 /*check forever */ 203 /*check forever */
204 rel.rel_value_us = UINT64_MAX; 204 rel.rel_value_us = UINT64_MAX;
205 GNUNET_assert (GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us == 205 GNUNET_assert(GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us ==
206 GNUNET_TIME_relative_subtract (rel, relForever).rel_value_us); 206 GNUNET_TIME_relative_subtract(rel, relForever).rel_value_us);
207 207
208 /*check GNUNET_TIME_relative_min */ 208 /*check GNUNET_TIME_relative_min */
209 now = GNUNET_TIME_absolute_get (); 209 now = GNUNET_TIME_absolute_get();
210 rel.rel_value_us = now.abs_value_us; 210 rel.rel_value_us = now.abs_value_us;
211 relForever.rel_value_us = rel.rel_value_us - 1024; 211 relForever.rel_value_us = rel.rel_value_us - 1024;
212 GNUNET_assert (relForever.rel_value_us == 212 GNUNET_assert(relForever.rel_value_us ==
213 GNUNET_TIME_relative_min (rel, relForever).rel_value_us); 213 GNUNET_TIME_relative_min(rel, relForever).rel_value_us);
214 214
215 /*check GNUNET_TIME_relative_max */ 215 /*check GNUNET_TIME_relative_max */
216 GNUNET_assert (rel.rel_value_us == 216 GNUNET_assert(rel.rel_value_us ==
217 GNUNET_TIME_relative_max (rel, relForever).rel_value_us); 217 GNUNET_TIME_relative_max(rel, relForever).rel_value_us);
218 218
219 /*check GNUNET_TIME_absolute_min */ 219 /*check GNUNET_TIME_absolute_min */
220 now = GNUNET_TIME_absolute_get (); 220 now = GNUNET_TIME_absolute_get();
221 last.abs_value_us = now.abs_value_us - 1024; 221 last.abs_value_us = now.abs_value_us - 1024;
222 GNUNET_assert (last.abs_value_us == 222 GNUNET_assert(last.abs_value_us ==
223 GNUNET_TIME_absolute_min (now, last).abs_value_us); 223 GNUNET_TIME_absolute_min(now, last).abs_value_us);
224 224
225 /*check GNUNET_TIME_absolute_max */ 225 /*check GNUNET_TIME_absolute_max */
226 GNUNET_assert (now.abs_value_us == 226 GNUNET_assert(now.abs_value_us ==
227 GNUNET_TIME_absolute_max (now, last).abs_value_us); 227 GNUNET_TIME_absolute_max(now, last).abs_value_us);
228 for (unsigned int i=0;i<30;i++) 228 for (unsigned int i = 0; i < 30; i++)
229 { 229 {
230 struct GNUNET_CONFIGURATION_Handle *cfg; 230 struct GNUNET_CONFIGURATION_Handle *cfg;
231 231
232 cfg = GNUNET_CONFIGURATION_create (); 232 cfg = GNUNET_CONFIGURATION_create();
233 last = GNUNET_TIME_absolute_get_monotonic (cfg); 233 last = GNUNET_TIME_absolute_get_monotonic(cfg);
234 now = GNUNET_TIME_absolute_get_monotonic (cfg); 234 now = GNUNET_TIME_absolute_get_monotonic(cfg);
235 GNUNET_assert (now.abs_value_us > last.abs_value_us); 235 GNUNET_assert(now.abs_value_us > last.abs_value_us);
236 (void) GNUNET_TIME_absolute_get_monotonic (NULL); 236 (void)GNUNET_TIME_absolute_get_monotonic(NULL);
237 GNUNET_CONFIGURATION_set_value_string (cfg, 237 GNUNET_CONFIGURATION_set_value_string(cfg,
238 "util", 238 "util",
239 "MONOTONIC_TIME_FILENAME", 239 "MONOTONIC_TIME_FILENAME",
240 "monotonic-time.dat"); 240 "monotonic-time.dat");
241 last = GNUNET_TIME_absolute_get_monotonic (cfg); 241 last = GNUNET_TIME_absolute_get_monotonic(cfg);
242 now = GNUNET_TIME_absolute_get_monotonic (cfg); 242 now = GNUNET_TIME_absolute_get_monotonic(cfg);
243 (void) GNUNET_TIME_absolute_get_monotonic (NULL); 243 (void)GNUNET_TIME_absolute_get_monotonic(NULL);
244 GNUNET_assert (now.abs_value_us > last.abs_value_us); 244 GNUNET_assert(now.abs_value_us > last.abs_value_us);
245 GNUNET_CONFIGURATION_destroy (cfg); 245 GNUNET_CONFIGURATION_destroy(cfg);
246 } 246 }
247 GNUNET_break (GNUNET_OK == 247 GNUNET_break(GNUNET_OK ==
248 GNUNET_DISK_directory_remove ("monotonic-time.dat")); 248 GNUNET_DISK_directory_remove("monotonic-time.dat"));
249 249
250 return 0; 250 return 0;
251} 251}
252 252
diff --git a/src/util/test_tun.c b/src/util/test_tun.c
index 391791c4b..f94e9c8ff 100644
--- a/src/util/test_tun.c
+++ b/src/util/test_tun.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file tun/test_tun.c 22 * @file tun/test_tun.c
@@ -29,9 +29,9 @@
29static int ret; 29static int ret;
30 30
31static void 31static void
32test_udp (size_t pll, 32test_udp(size_t pll,
33 int pl_fill, 33 int pl_fill,
34 uint16_t crc) 34 uint16_t crc)
35{ 35{
36 struct GNUNET_TUN_IPv4Header ip; 36 struct GNUNET_TUN_IPv4Header ip;
37 struct GNUNET_TUN_UdpHeader udp; 37 struct GNUNET_TUN_UdpHeader udp;
@@ -39,36 +39,36 @@ test_udp (size_t pll,
39 struct in_addr src; 39 struct in_addr src;
40 struct in_addr dst; 40 struct in_addr dst;
41 41
42 GNUNET_assert (1 == inet_pton (AF_INET, "1.2.3.4", &src)); 42 GNUNET_assert(1 == inet_pton(AF_INET, "1.2.3.4", &src));
43 GNUNET_assert (1 == inet_pton (AF_INET, "122.2.3.5", &dst)); 43 GNUNET_assert(1 == inet_pton(AF_INET, "122.2.3.5", &dst));
44 memset (payload, pl_fill, sizeof (payload)); 44 memset(payload, pl_fill, sizeof(payload));
45 GNUNET_TUN_initialize_ipv4_header (&ip, 45 GNUNET_TUN_initialize_ipv4_header(&ip,
46 IPPROTO_UDP, 46 IPPROTO_UDP,
47 pll + sizeof (udp), 47 pll + sizeof(udp),
48 &src, 48 &src,
49 &dst); 49 &dst);
50 udp.source_port = htons (4242); 50 udp.source_port = htons(4242);
51 udp.destination_port = htons (4242); 51 udp.destination_port = htons(4242);
52 udp.len = htons (pll); 52 udp.len = htons(pll);
53 GNUNET_TUN_calculate_udp4_checksum (&ip, 53 GNUNET_TUN_calculate_udp4_checksum(&ip,
54 &udp, 54 &udp,
55 payload, 55 payload,
56 pll); 56 pll);
57 if (crc != ntohs (udp.crc)) 57 if (crc != ntohs(udp.crc))
58 { 58 {
59 fprintf (stderr, "Got CRC: %u, wanted: %u\n", 59 fprintf(stderr, "Got CRC: %u, wanted: %u\n",
60 ntohs (udp.crc), 60 ntohs(udp.crc),
61 crc); 61 crc);
62 ret = 1; 62 ret = 1;
63 } 63 }
64} 64}
65 65
66int main (int argc, 66int main(int argc,
67 char **argv) 67 char **argv)
68{ 68{
69 test_udp (4, 3, 22439); 69 test_udp(4, 3, 22439);
70 test_udp (4, 1, 23467); 70 test_udp(4, 1, 23467);
71 test_udp (7, 17, 6516); 71 test_udp(7, 17, 6516);
72 test_udp (12451, 251, 42771); 72 test_udp(12451, 251, 42771);
73 return ret; 73 return ret;
74} 74}
diff --git a/src/util/time.c b/src/util/time.c
index 85a781aff..3df7b469e 100644
--- a/src/util/time.c
+++ b/src/util/time.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/time.c 22 * @file util/time.c
@@ -37,7 +37,7 @@
37#endif 37#endif
38#endif 38#endif
39 39
40#define LOG(kind, ...) GNUNET_log_from (kind, "util-time", __VA_ARGS__) 40#define LOG(kind, ...) GNUNET_log_from(kind, "util-time", __VA_ARGS__)
41 41
42/** 42/**
43 * Variable used to simulate clock skew. Used for testing, never in production. 43 * Variable used to simulate clock skew. Used for testing, never in production.
@@ -50,7 +50,7 @@ static long long timestamp_offset;
50 * @param offset the offset to skew the locale time by 50 * @param offset the offset to skew the locale time by
51 */ 51 */
52void 52void
53GNUNET_TIME_set_offset (long long offset) 53GNUNET_TIME_set_offset(long long offset)
54{ 54{
55 timestamp_offset = offset; 55 timestamp_offset = offset;
56} 56}
@@ -62,7 +62,7 @@ GNUNET_TIME_set_offset (long long offset)
62 * @return the offset we currently skew the locale time by 62 * @return the offset we currently skew the locale time by
63 */ 63 */
64long long 64long long
65GNUNET_TIME_get_offset () 65GNUNET_TIME_get_offset()
66{ 66{
67 return timestamp_offset; 67 return timestamp_offset;
68} 68}
@@ -77,7 +77,7 @@ GNUNET_TIME_get_offset ()
77 * it was just now rounded 77 * it was just now rounded
78 */ 78 */
79int 79int
80GNUNET_TIME_round_abs (struct GNUNET_TIME_Absolute *at) 80GNUNET_TIME_round_abs(struct GNUNET_TIME_Absolute *at)
81{ 81{
82 if (at->abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us) 82 if (at->abs_value_us == GNUNET_TIME_UNIT_FOREVER_ABS.abs_value_us)
83 return GNUNET_OK; 83 return GNUNET_OK;
@@ -97,7 +97,7 @@ GNUNET_TIME_round_abs (struct GNUNET_TIME_Absolute *at)
97 * it was just now rounded 97 * it was just now rounded
98 */ 98 */
99int 99int
100GNUNET_TIME_round_rel (struct GNUNET_TIME_Relative *rt) 100GNUNET_TIME_round_rel(struct GNUNET_TIME_Relative *rt)
101{ 101{
102 if (rt->rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) 102 if (rt->rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
103 return GNUNET_OK; 103 return GNUNET_OK;
@@ -115,14 +115,14 @@ GNUNET_TIME_round_rel (struct GNUNET_TIME_Relative *rt)
115 * @return the current time 115 * @return the current time
116 */ 116 */
117struct GNUNET_TIME_Absolute 117struct GNUNET_TIME_Absolute
118GNUNET_TIME_absolute_get () 118GNUNET_TIME_absolute_get()
119{ 119{
120 struct GNUNET_TIME_Absolute ret; 120 struct GNUNET_TIME_Absolute ret;
121 struct timeval tv; 121 struct timeval tv;
122 122
123 gettimeofday (&tv, NULL); 123 gettimeofday(&tv, NULL);
124 ret.abs_value_us = (uint64_t) (((uint64_t) tv.tv_sec * 1000LL * 1000LL) + 124 ret.abs_value_us = (uint64_t)(((uint64_t)tv.tv_sec * 1000LL * 1000LL) +
125 ((uint64_t) tv.tv_usec)) + 125 ((uint64_t)tv.tv_usec)) +
126 timestamp_offset; 126 timestamp_offset;
127 return ret; 127 return ret;
128} 128}
@@ -132,7 +132,7 @@ GNUNET_TIME_absolute_get ()
132 * Return relative time of 0ms. 132 * Return relative time of 0ms.
133 */ 133 */
134struct GNUNET_TIME_Relative 134struct GNUNET_TIME_Relative
135GNUNET_TIME_relative_get_zero_ () 135GNUNET_TIME_relative_get_zero_()
136{ 136{
137 static struct GNUNET_TIME_Relative zero; 137 static struct GNUNET_TIME_Relative zero;
138 138
@@ -144,7 +144,7 @@ GNUNET_TIME_relative_get_zero_ ()
144 * Return absolute time of 0ms. 144 * Return absolute time of 0ms.
145 */ 145 */
146struct GNUNET_TIME_Absolute 146struct GNUNET_TIME_Absolute
147GNUNET_TIME_absolute_get_zero_ () 147GNUNET_TIME_absolute_get_zero_()
148{ 148{
149 static struct GNUNET_TIME_Absolute zero; 149 static struct GNUNET_TIME_Absolute zero;
150 150
@@ -156,9 +156,9 @@ GNUNET_TIME_absolute_get_zero_ ()
156 * Return relative time of 1us. 156 * Return relative time of 1us.
157 */ 157 */
158struct GNUNET_TIME_Relative 158struct GNUNET_TIME_Relative
159GNUNET_TIME_relative_get_unit_ () 159GNUNET_TIME_relative_get_unit_()
160{ 160{
161 static struct GNUNET_TIME_Relative one = {1}; 161 static struct GNUNET_TIME_Relative one = { 1 };
162 162
163 return one; 163 return one;
164} 164}
@@ -168,9 +168,9 @@ GNUNET_TIME_relative_get_unit_ ()
168 * Return relative time of 1ms. 168 * Return relative time of 1ms.
169 */ 169 */
170struct GNUNET_TIME_Relative 170struct GNUNET_TIME_Relative
171GNUNET_TIME_relative_get_millisecond_ () 171GNUNET_TIME_relative_get_millisecond_()
172{ 172{
173 static struct GNUNET_TIME_Relative one = {1000}; 173 static struct GNUNET_TIME_Relative one = { 1000 };
174 174
175 return one; 175 return one;
176} 176}
@@ -180,9 +180,9 @@ GNUNET_TIME_relative_get_millisecond_ ()
180 * Return relative time of 1s. 180 * Return relative time of 1s.
181 */ 181 */
182struct GNUNET_TIME_Relative 182struct GNUNET_TIME_Relative
183GNUNET_TIME_relative_get_second_ () 183GNUNET_TIME_relative_get_second_()
184{ 184{
185 static struct GNUNET_TIME_Relative one = {1000 * 1000LL}; 185 static struct GNUNET_TIME_Relative one = { 1000 * 1000LL };
186 186
187 return one; 187 return one;
188} 188}
@@ -192,9 +192,9 @@ GNUNET_TIME_relative_get_second_ ()
192 * Return relative time of 1 minute. 192 * Return relative time of 1 minute.
193 */ 193 */
194struct GNUNET_TIME_Relative 194struct GNUNET_TIME_Relative
195GNUNET_TIME_relative_get_minute_ () 195GNUNET_TIME_relative_get_minute_()
196{ 196{
197 static struct GNUNET_TIME_Relative one = {60 * 1000 * 1000LL}; 197 static struct GNUNET_TIME_Relative one = { 60 * 1000 * 1000LL };
198 198
199 return one; 199 return one;
200} 200}
@@ -204,9 +204,9 @@ GNUNET_TIME_relative_get_minute_ ()
204 * Return relative time of 1 hour. 204 * Return relative time of 1 hour.
205 */ 205 */
206struct GNUNET_TIME_Relative 206struct GNUNET_TIME_Relative
207GNUNET_TIME_relative_get_hour_ () 207GNUNET_TIME_relative_get_hour_()
208{ 208{
209 static struct GNUNET_TIME_Relative one = {60 * 60 * 1000 * 1000LL}; 209 static struct GNUNET_TIME_Relative one = { 60 * 60 * 1000 * 1000LL };
210 210
211 return one; 211 return one;
212} 212}
@@ -216,9 +216,9 @@ GNUNET_TIME_relative_get_hour_ ()
216 * Return "forever". 216 * Return "forever".
217 */ 217 */
218struct GNUNET_TIME_Relative 218struct GNUNET_TIME_Relative
219GNUNET_TIME_relative_get_forever_ () 219GNUNET_TIME_relative_get_forever_()
220{ 220{
221 static struct GNUNET_TIME_Relative forever = {UINT64_MAX}; 221 static struct GNUNET_TIME_Relative forever = { UINT64_MAX };
222 222
223 return forever; 223 return forever;
224} 224}
@@ -228,9 +228,10 @@ GNUNET_TIME_relative_get_forever_ ()
228 * Return "forever". 228 * Return "forever".
229 */ 229 */
230struct GNUNET_TIME_Absolute 230struct GNUNET_TIME_Absolute
231GNUNET_TIME_absolute_get_forever_ () 231GNUNET_TIME_absolute_get_forever_()
232{ 232{
233 static struct GNUNET_TIME_Absolute forever = {UINT64_MAX}; 233 static struct GNUNET_TIME_Absolute forever = { UINT64_MAX };
234
234 return forever; 235 return forever;
235} 236}
236 237
@@ -242,19 +243,19 @@ GNUNET_TIME_absolute_get_forever_ ()
242 * @return timestamp that is "rel" in the future, or FOREVER if rel==FOREVER (or if we would overflow) 243 * @return timestamp that is "rel" in the future, or FOREVER if rel==FOREVER (or if we would overflow)
243 */ 244 */
244struct GNUNET_TIME_Absolute 245struct GNUNET_TIME_Absolute
245GNUNET_TIME_relative_to_absolute (struct GNUNET_TIME_Relative rel) 246GNUNET_TIME_relative_to_absolute(struct GNUNET_TIME_Relative rel)
246{ 247{
247 struct GNUNET_TIME_Absolute ret; 248 struct GNUNET_TIME_Absolute ret;
248 249
249 if (rel.rel_value_us == UINT64_MAX) 250 if (rel.rel_value_us == UINT64_MAX)
250 return GNUNET_TIME_UNIT_FOREVER_ABS; 251 return GNUNET_TIME_UNIT_FOREVER_ABS;
251 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); 252 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
252 253
253 if (rel.rel_value_us + now.abs_value_us < rel.rel_value_us) 254 if (rel.rel_value_us + now.abs_value_us < rel.rel_value_us)
254 { 255 {
255 GNUNET_break (0); /* overflow... */ 256 GNUNET_break(0); /* overflow... */
256 return GNUNET_TIME_UNIT_FOREVER_ABS; 257 return GNUNET_TIME_UNIT_FOREVER_ABS;
257 } 258 }
258 ret.abs_value_us = rel.rel_value_us + now.abs_value_us; 259 ret.abs_value_us = rel.rel_value_us + now.abs_value_us;
259 return ret; 260 return ret;
260} 261}
@@ -268,8 +269,8 @@ GNUNET_TIME_relative_to_absolute (struct GNUNET_TIME_Relative rel)
268 * @return timestamp that is smaller 269 * @return timestamp that is smaller
269 */ 270 */
270struct GNUNET_TIME_Relative 271struct GNUNET_TIME_Relative
271GNUNET_TIME_relative_min (struct GNUNET_TIME_Relative t1, 272GNUNET_TIME_relative_min(struct GNUNET_TIME_Relative t1,
272 struct GNUNET_TIME_Relative t2) 273 struct GNUNET_TIME_Relative t2)
273{ 274{
274 return (t1.rel_value_us < t2.rel_value_us) ? t1 : t2; 275 return (t1.rel_value_us < t2.rel_value_us) ? t1 : t2;
275} 276}
@@ -283,8 +284,8 @@ GNUNET_TIME_relative_min (struct GNUNET_TIME_Relative t1,
283 * @return timestamp that is larger 284 * @return timestamp that is larger
284 */ 285 */
285struct GNUNET_TIME_Relative 286struct GNUNET_TIME_Relative
286GNUNET_TIME_relative_max (struct GNUNET_TIME_Relative t1, 287GNUNET_TIME_relative_max(struct GNUNET_TIME_Relative t1,
287 struct GNUNET_TIME_Relative t2) 288 struct GNUNET_TIME_Relative t2)
288{ 289{
289 return (t1.rel_value_us > t2.rel_value_us) ? t1 : t2; 290 return (t1.rel_value_us > t2.rel_value_us) ? t1 : t2;
290} 291}
@@ -298,8 +299,8 @@ GNUNET_TIME_relative_max (struct GNUNET_TIME_Relative t1,
298 * @return timestamp that is smaller 299 * @return timestamp that is smaller
299 */ 300 */
300struct GNUNET_TIME_Absolute 301struct GNUNET_TIME_Absolute
301GNUNET_TIME_absolute_min (struct GNUNET_TIME_Absolute t1, 302GNUNET_TIME_absolute_min(struct GNUNET_TIME_Absolute t1,
302 struct GNUNET_TIME_Absolute t2) 303 struct GNUNET_TIME_Absolute t2)
303{ 304{
304 return (t1.abs_value_us < t2.abs_value_us) ? t1 : t2; 305 return (t1.abs_value_us < t2.abs_value_us) ? t1 : t2;
305} 306}
@@ -313,8 +314,8 @@ GNUNET_TIME_absolute_min (struct GNUNET_TIME_Absolute t1,
313 * @return timestamp that is bigger 314 * @return timestamp that is bigger
314 */ 315 */
315struct GNUNET_TIME_Absolute 316struct GNUNET_TIME_Absolute
316GNUNET_TIME_absolute_max (struct GNUNET_TIME_Absolute t1, 317GNUNET_TIME_absolute_max(struct GNUNET_TIME_Absolute t1,
317 struct GNUNET_TIME_Absolute t2) 318 struct GNUNET_TIME_Absolute t2)
318{ 319{
319 return (t1.abs_value_us > t2.abs_value_us) ? t1 : t2; 320 return (t1.abs_value_us > t2.abs_value_us) ? t1 : t2;
320} 321}
@@ -327,13 +328,13 @@ GNUNET_TIME_absolute_max (struct GNUNET_TIME_Absolute t1,
327 * @return future - now, or 0 if now >= future, or FOREVER if future==FOREVER. 328 * @return future - now, or 0 if now >= future, or FOREVER if future==FOREVER.
328 */ 329 */
329struct GNUNET_TIME_Relative 330struct GNUNET_TIME_Relative
330GNUNET_TIME_absolute_get_remaining (struct GNUNET_TIME_Absolute future) 331GNUNET_TIME_absolute_get_remaining(struct GNUNET_TIME_Absolute future)
331{ 332{
332 struct GNUNET_TIME_Relative ret; 333 struct GNUNET_TIME_Relative ret;
333 334
334 if (future.abs_value_us == UINT64_MAX) 335 if (future.abs_value_us == UINT64_MAX)
335 return GNUNET_TIME_UNIT_FOREVER_REL; 336 return GNUNET_TIME_UNIT_FOREVER_REL;
336 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get (); 337 struct GNUNET_TIME_Absolute now = GNUNET_TIME_absolute_get();
337 338
338 if (now.abs_value_us > future.abs_value_us) 339 if (now.abs_value_us > future.abs_value_us)
339 return GNUNET_TIME_UNIT_ZERO; 340 return GNUNET_TIME_UNIT_ZERO;
@@ -349,8 +350,8 @@ GNUNET_TIME_absolute_get_remaining (struct GNUNET_TIME_Absolute future)
349 * @return 0 if start >= end; FOREVER if end==FOREVER; otherwise end - start 350 * @return 0 if start >= end; FOREVER if end==FOREVER; otherwise end - start
350 */ 351 */
351struct GNUNET_TIME_Relative 352struct GNUNET_TIME_Relative
352GNUNET_TIME_absolute_get_difference (struct GNUNET_TIME_Absolute start, 353GNUNET_TIME_absolute_get_difference(struct GNUNET_TIME_Absolute start,
353 struct GNUNET_TIME_Absolute end) 354 struct GNUNET_TIME_Absolute end)
354{ 355{
355 struct GNUNET_TIME_Relative ret; 356 struct GNUNET_TIME_Relative ret;
356 357
@@ -369,12 +370,12 @@ GNUNET_TIME_absolute_get_difference (struct GNUNET_TIME_Absolute start,
369 * @return 0 if whence > now, otherwise now-whence. 370 * @return 0 if whence > now, otherwise now-whence.
370 */ 371 */
371struct GNUNET_TIME_Relative 372struct GNUNET_TIME_Relative
372GNUNET_TIME_absolute_get_duration (struct GNUNET_TIME_Absolute whence) 373GNUNET_TIME_absolute_get_duration(struct GNUNET_TIME_Absolute whence)
373{ 374{
374 struct GNUNET_TIME_Absolute now; 375 struct GNUNET_TIME_Absolute now;
375 struct GNUNET_TIME_Relative ret; 376 struct GNUNET_TIME_Relative ret;
376 377
377 now = GNUNET_TIME_absolute_get (); 378 now = GNUNET_TIME_absolute_get();
378 if (whence.abs_value_us > now.abs_value_us) 379 if (whence.abs_value_us > now.abs_value_us)
379 return GNUNET_TIME_UNIT_ZERO; 380 return GNUNET_TIME_UNIT_ZERO;
380 ret.rel_value_us = now.abs_value_us - whence.abs_value_us; 381 ret.rel_value_us = now.abs_value_us - whence.abs_value_us;
@@ -389,8 +390,8 @@ GNUNET_TIME_absolute_get_duration (struct GNUNET_TIME_Absolute whence)
389 * @return FOREVER if either argument is FOREVER or on overflow; start+duration otherwise 390 * @return FOREVER if either argument is FOREVER or on overflow; start+duration otherwise
390 */ 391 */
391struct GNUNET_TIME_Absolute 392struct GNUNET_TIME_Absolute
392GNUNET_TIME_absolute_add (struct GNUNET_TIME_Absolute start, 393GNUNET_TIME_absolute_add(struct GNUNET_TIME_Absolute start,
393 struct GNUNET_TIME_Relative duration) 394 struct GNUNET_TIME_Relative duration)
394{ 395{
395 struct GNUNET_TIME_Absolute ret; 396 struct GNUNET_TIME_Absolute ret;
396 397
@@ -398,10 +399,10 @@ GNUNET_TIME_absolute_add (struct GNUNET_TIME_Absolute start,
398 (duration.rel_value_us == UINT64_MAX)) 399 (duration.rel_value_us == UINT64_MAX))
399 return GNUNET_TIME_UNIT_FOREVER_ABS; 400 return GNUNET_TIME_UNIT_FOREVER_ABS;
400 if (start.abs_value_us + duration.rel_value_us < start.abs_value_us) 401 if (start.abs_value_us + duration.rel_value_us < start.abs_value_us)
401 { 402 {
402 GNUNET_break (0); 403 GNUNET_break(0);
403 return GNUNET_TIME_UNIT_FOREVER_ABS; 404 return GNUNET_TIME_UNIT_FOREVER_ABS;
404 } 405 }
405 ret.abs_value_us = start.abs_value_us + duration.rel_value_us; 406 ret.abs_value_us = start.abs_value_us + duration.rel_value_us;
406 return ret; 407 return ret;
407} 408}
@@ -416,8 +417,8 @@ GNUNET_TIME_absolute_add (struct GNUNET_TIME_Absolute start,
416 * @return ZERO if start <= duration, or FOREVER if start time is FOREVER; start-duration otherwise 417 * @return ZERO if start <= duration, or FOREVER if start time is FOREVER; start-duration otherwise
417 */ 418 */
418struct GNUNET_TIME_Absolute 419struct GNUNET_TIME_Absolute
419GNUNET_TIME_absolute_subtract (struct GNUNET_TIME_Absolute start, 420GNUNET_TIME_absolute_subtract(struct GNUNET_TIME_Absolute start,
420 struct GNUNET_TIME_Relative duration) 421 struct GNUNET_TIME_Relative duration)
421{ 422{
422 struct GNUNET_TIME_Absolute ret; 423 struct GNUNET_TIME_Absolute ret;
423 424
@@ -436,8 +437,8 @@ GNUNET_TIME_absolute_subtract (struct GNUNET_TIME_Absolute start,
436 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor 437 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor
437 */ 438 */
438struct GNUNET_TIME_Relative 439struct GNUNET_TIME_Relative
439GNUNET_TIME_relative_multiply (struct GNUNET_TIME_Relative rel, 440GNUNET_TIME_relative_multiply(struct GNUNET_TIME_Relative rel,
440 unsigned long long factor) 441 unsigned long long factor)
441{ 442{
442 struct GNUNET_TIME_Relative ret; 443 struct GNUNET_TIME_Relative ret;
443 444
@@ -447,10 +448,10 @@ GNUNET_TIME_relative_multiply (struct GNUNET_TIME_Relative rel,
447 return GNUNET_TIME_UNIT_FOREVER_REL; 448 return GNUNET_TIME_UNIT_FOREVER_REL;
448 ret.rel_value_us = rel.rel_value_us * factor; 449 ret.rel_value_us = rel.rel_value_us * factor;
449 if (ret.rel_value_us / factor != rel.rel_value_us) 450 if (ret.rel_value_us / factor != rel.rel_value_us)
450 { 451 {
451 GNUNET_break (0); 452 GNUNET_break(0);
452 return GNUNET_TIME_UNIT_FOREVER_REL; 453 return GNUNET_TIME_UNIT_FOREVER_REL;
453 } 454 }
454 return ret; 455 return ret;
455} 456}
456 457
@@ -462,27 +463,27 @@ GNUNET_TIME_relative_multiply (struct GNUNET_TIME_Relative rel,
462 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor 463 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor
463 */ 464 */
464struct GNUNET_TIME_Relative 465struct GNUNET_TIME_Relative
465relative_multiply_double (struct GNUNET_TIME_Relative rel, double factor) 466relative_multiply_double(struct GNUNET_TIME_Relative rel, double factor)
466{ 467{
467 struct GNUNET_TIME_Relative out; 468 struct GNUNET_TIME_Relative out;
468 double m; 469 double m;
469 470
470 GNUNET_assert (0 <= factor); 471 GNUNET_assert(0 <= factor);
471 472
472 if (0 == factor) 473 if (0 == factor)
473 return GNUNET_TIME_UNIT_ZERO; 474 return GNUNET_TIME_UNIT_ZERO;
474 if (rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us) 475 if (rel.rel_value_us == GNUNET_TIME_UNIT_FOREVER_REL.rel_value_us)
475 return GNUNET_TIME_UNIT_FOREVER_REL; 476 return GNUNET_TIME_UNIT_FOREVER_REL;
476 477
477 m = ((double) rel.rel_value_us) * factor; 478 m = ((double)rel.rel_value_us) * factor;
478 479
479 if (m >= (double) (GNUNET_TIME_UNIT_FOREVER_REL).rel_value_us) 480 if (m >= (double)(GNUNET_TIME_UNIT_FOREVER_REL).rel_value_us)
480 { 481 {
481 GNUNET_break (0); 482 GNUNET_break(0);
482 return GNUNET_TIME_UNIT_FOREVER_REL; 483 return GNUNET_TIME_UNIT_FOREVER_REL;
483 } 484 }
484 485
485 out.rel_value_us = (uint64_t) m; 486 out.rel_value_us = (uint64_t)m;
486 return out; 487 return out;
487} 488}
488 489
@@ -495,8 +496,8 @@ relative_multiply_double (struct GNUNET_TIME_Relative rel, double factor)
495 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor 496 * @return FOREVER if rel=FOREVER or on overflow; otherwise rel*factor
496 */ 497 */
497struct GNUNET_TIME_Relative 498struct GNUNET_TIME_Relative
498GNUNET_TIME_relative_saturating_multiply (struct GNUNET_TIME_Relative rel, 499GNUNET_TIME_relative_saturating_multiply(struct GNUNET_TIME_Relative rel,
499 unsigned long long factor) 500 unsigned long long factor)
500{ 501{
501 struct GNUNET_TIME_Relative ret; 502 struct GNUNET_TIME_Relative ret;
502 503
@@ -506,9 +507,9 @@ GNUNET_TIME_relative_saturating_multiply (struct GNUNET_TIME_Relative rel,
506 return GNUNET_TIME_UNIT_FOREVER_REL; 507 return GNUNET_TIME_UNIT_FOREVER_REL;
507 ret.rel_value_us = rel.rel_value_us * factor; 508 ret.rel_value_us = rel.rel_value_us * factor;
508 if (ret.rel_value_us / factor != rel.rel_value_us) 509 if (ret.rel_value_us / factor != rel.rel_value_us)
509 { 510 {
510 return GNUNET_TIME_UNIT_FOREVER_REL; 511 return GNUNET_TIME_UNIT_FOREVER_REL;
511 } 512 }
512 return ret; 513 return ret;
513} 514}
514 515
@@ -521,8 +522,8 @@ GNUNET_TIME_relative_saturating_multiply (struct GNUNET_TIME_Relative rel,
521 * @return FOREVER if rel=FOREVER or factor==0; otherwise rel/factor 522 * @return FOREVER if rel=FOREVER or factor==0; otherwise rel/factor
522 */ 523 */
523struct GNUNET_TIME_Relative 524struct GNUNET_TIME_Relative
524GNUNET_TIME_relative_divide (struct GNUNET_TIME_Relative rel, 525GNUNET_TIME_relative_divide(struct GNUNET_TIME_Relative rel,
525 unsigned long long factor) 526 unsigned long long factor)
526{ 527{
527 struct GNUNET_TIME_Relative ret; 528 struct GNUNET_TIME_Relative ret;
528 529
@@ -545,22 +546,22 @@ GNUNET_TIME_relative_divide (struct GNUNET_TIME_Relative rel,
545 * assuming it continues at the same speed 546 * assuming it continues at the same speed
546 */ 547 */
547struct GNUNET_TIME_Relative 548struct GNUNET_TIME_Relative
548GNUNET_TIME_calculate_eta (struct GNUNET_TIME_Absolute start, 549GNUNET_TIME_calculate_eta(struct GNUNET_TIME_Absolute start,
549 uint64_t finished, 550 uint64_t finished,
550 uint64_t total) 551 uint64_t total)
551{ 552{
552 struct GNUNET_TIME_Relative dur; 553 struct GNUNET_TIME_Relative dur;
553 double exp; 554 double exp;
554 struct GNUNET_TIME_Relative ret; 555 struct GNUNET_TIME_Relative ret;
555 556
556 GNUNET_break (finished <= total); 557 GNUNET_break(finished <= total);
557 if (finished >= total) 558 if (finished >= total)
558 return GNUNET_TIME_UNIT_ZERO; 559 return GNUNET_TIME_UNIT_ZERO;
559 if (0 == finished) 560 if (0 == finished)
560 return GNUNET_TIME_UNIT_FOREVER_REL; 561 return GNUNET_TIME_UNIT_FOREVER_REL;
561 dur = GNUNET_TIME_absolute_get_duration (start); 562 dur = GNUNET_TIME_absolute_get_duration(start);
562 exp = ((double) dur.rel_value_us) * ((double) total) / ((double) finished); 563 exp = ((double)dur.rel_value_us) * ((double)total) / ((double)finished);
563 ret.rel_value_us = ((uint64_t) exp) - dur.rel_value_us; 564 ret.rel_value_us = ((uint64_t)exp) - dur.rel_value_us;
564 return ret; 565 return ret;
565} 566}
566 567
@@ -573,18 +574,18 @@ GNUNET_TIME_calculate_eta (struct GNUNET_TIME_Absolute start,
573 * @return FOREVER if either argument is FOREVER or on overflow; a1+a2 otherwise 574 * @return FOREVER if either argument is FOREVER or on overflow; a1+a2 otherwise
574 */ 575 */
575struct GNUNET_TIME_Relative 576struct GNUNET_TIME_Relative
576GNUNET_TIME_relative_add (struct GNUNET_TIME_Relative a1, 577GNUNET_TIME_relative_add(struct GNUNET_TIME_Relative a1,
577 struct GNUNET_TIME_Relative a2) 578 struct GNUNET_TIME_Relative a2)
578{ 579{
579 struct GNUNET_TIME_Relative ret; 580 struct GNUNET_TIME_Relative ret;
580 581
581 if ((a1.rel_value_us == UINT64_MAX) || (a2.rel_value_us == UINT64_MAX)) 582 if ((a1.rel_value_us == UINT64_MAX) || (a2.rel_value_us == UINT64_MAX))
582 return GNUNET_TIME_UNIT_FOREVER_REL; 583 return GNUNET_TIME_UNIT_FOREVER_REL;
583 if (a1.rel_value_us + a2.rel_value_us < a1.rel_value_us) 584 if (a1.rel_value_us + a2.rel_value_us < a1.rel_value_us)
584 { 585 {
585 GNUNET_break (0); 586 GNUNET_break(0);
586 return GNUNET_TIME_UNIT_FOREVER_REL; 587 return GNUNET_TIME_UNIT_FOREVER_REL;
587 } 588 }
588 ret.rel_value_us = a1.rel_value_us + a2.rel_value_us; 589 ret.rel_value_us = a1.rel_value_us + a2.rel_value_us;
589 return ret; 590 return ret;
590} 591}
@@ -598,8 +599,8 @@ GNUNET_TIME_relative_add (struct GNUNET_TIME_Relative a1,
598 * @return ZERO if a2>=a1 (including both FOREVER), FOREVER if a1 is FOREVER, a1-a2 otherwise 599 * @return ZERO if a2>=a1 (including both FOREVER), FOREVER if a1 is FOREVER, a1-a2 otherwise
599 */ 600 */
600struct GNUNET_TIME_Relative 601struct GNUNET_TIME_Relative
601GNUNET_TIME_relative_subtract (struct GNUNET_TIME_Relative a1, 602GNUNET_TIME_relative_subtract(struct GNUNET_TIME_Relative a1,
602 struct GNUNET_TIME_Relative a2) 603 struct GNUNET_TIME_Relative a2)
603{ 604{
604 struct GNUNET_TIME_Relative ret; 605 struct GNUNET_TIME_Relative ret;
605 606
@@ -619,11 +620,11 @@ GNUNET_TIME_relative_subtract (struct GNUNET_TIME_Relative a1,
619 * @return time in network byte order 620 * @return time in network byte order
620 */ 621 */
621struct GNUNET_TIME_RelativeNBO 622struct GNUNET_TIME_RelativeNBO
622GNUNET_TIME_relative_hton (struct GNUNET_TIME_Relative a) 623GNUNET_TIME_relative_hton(struct GNUNET_TIME_Relative a)
623{ 624{
624 struct GNUNET_TIME_RelativeNBO ret; 625 struct GNUNET_TIME_RelativeNBO ret;
625 626
626 ret.rel_value_us__ = GNUNET_htonll (a.rel_value_us); 627 ret.rel_value_us__ = GNUNET_htonll(a.rel_value_us);
627 return ret; 628 return ret;
628} 629}
629 630
@@ -635,11 +636,11 @@ GNUNET_TIME_relative_hton (struct GNUNET_TIME_Relative a)
635 * @return time in host byte order 636 * @return time in host byte order
636 */ 637 */
637struct GNUNET_TIME_Relative 638struct GNUNET_TIME_Relative
638GNUNET_TIME_relative_ntoh (struct GNUNET_TIME_RelativeNBO a) 639GNUNET_TIME_relative_ntoh(struct GNUNET_TIME_RelativeNBO a)
639{ 640{
640 struct GNUNET_TIME_Relative ret; 641 struct GNUNET_TIME_Relative ret;
641 642
642 ret.rel_value_us = GNUNET_ntohll (a.rel_value_us__); 643 ret.rel_value_us = GNUNET_ntohll(a.rel_value_us__);
643 return ret; 644 return ret;
644} 645}
645 646
@@ -651,11 +652,11 @@ GNUNET_TIME_relative_ntoh (struct GNUNET_TIME_RelativeNBO a)
651 * @return time in network byte order 652 * @return time in network byte order
652 */ 653 */
653struct GNUNET_TIME_AbsoluteNBO 654struct GNUNET_TIME_AbsoluteNBO
654GNUNET_TIME_absolute_hton (struct GNUNET_TIME_Absolute a) 655GNUNET_TIME_absolute_hton(struct GNUNET_TIME_Absolute a)
655{ 656{
656 struct GNUNET_TIME_AbsoluteNBO ret; 657 struct GNUNET_TIME_AbsoluteNBO ret;
657 658
658 ret.abs_value_us__ = GNUNET_htonll (a.abs_value_us); 659 ret.abs_value_us__ = GNUNET_htonll(a.abs_value_us);
659 return ret; 660 return ret;
660} 661}
661 662
@@ -667,11 +668,11 @@ GNUNET_TIME_absolute_hton (struct GNUNET_TIME_Absolute a)
667 * @return time in host byte order 668 * @return time in host byte order
668 */ 669 */
669struct GNUNET_TIME_Absolute 670struct GNUNET_TIME_Absolute
670GNUNET_TIME_absolute_ntoh (struct GNUNET_TIME_AbsoluteNBO a) 671GNUNET_TIME_absolute_ntoh(struct GNUNET_TIME_AbsoluteNBO a)
671{ 672{
672 struct GNUNET_TIME_Absolute ret; 673 struct GNUNET_TIME_Absolute ret;
673 674
674 ret.abs_value_us = GNUNET_ntohll (a.abs_value_us__); 675 ret.abs_value_us = GNUNET_ntohll(a.abs_value_us__);
675 return ret; 676 return ret;
676} 677}
677 678
@@ -680,13 +681,13 @@ GNUNET_TIME_absolute_ntoh (struct GNUNET_TIME_AbsoluteNBO a)
680 * Return the current year (i.e. '2011'). 681 * Return the current year (i.e. '2011').
681 */ 682 */
682unsigned int 683unsigned int
683GNUNET_TIME_get_current_year () 684GNUNET_TIME_get_current_year()
684{ 685{
685 time_t tp; 686 time_t tp;
686 struct tm *t; 687 struct tm *t;
687 688
688 tp = time (NULL); 689 tp = time(NULL);
689 t = gmtime (&tp); 690 t = gmtime(&tp);
690 if (t == NULL) 691 if (t == NULL)
691 return 0; 692 return 0;
692 return t->tm_year + 1900; 693 return t->tm_year + 1900;
@@ -700,13 +701,13 @@ GNUNET_TIME_get_current_year ()
700 * @return year a year (after 1970), 0 on error 701 * @return year a year (after 1970), 0 on error
701 */ 702 */
702unsigned int 703unsigned int
703GNUNET_TIME_time_to_year (struct GNUNET_TIME_Absolute at) 704GNUNET_TIME_time_to_year(struct GNUNET_TIME_Absolute at)
704{ 705{
705 struct tm *t; 706 struct tm *t;
706 time_t tp; 707 time_t tp;
707 708
708 tp = at.abs_value_us / 1000LL / 1000LL; /* microseconds to seconds */ 709 tp = at.abs_value_us / 1000LL / 1000LL; /* microseconds to seconds */
709 t = gmtime (&tp); 710 t = gmtime(&tp);
710 if (t == NULL) 711 if (t == NULL)
711 return 0; 712 return 0;
712 return t->tm_year + 1900; 713 return t->tm_year + 1900;
@@ -720,25 +721,25 @@ GNUNET_TIME_time_to_year (struct GNUNET_TIME_Absolute at)
720 * @return absolute time for January 1st of that year. 721 * @return absolute time for January 1st of that year.
721 */ 722 */
722struct GNUNET_TIME_Absolute 723struct GNUNET_TIME_Absolute
723GNUNET_TIME_year_to_time (unsigned int year) 724GNUNET_TIME_year_to_time(unsigned int year)
724{ 725{
725 struct GNUNET_TIME_Absolute ret; 726 struct GNUNET_TIME_Absolute ret;
726 time_t tp; 727 time_t tp;
727 struct tm t; 728 struct tm t;
728 729
729 memset (&t, 0, sizeof (t)); 730 memset(&t, 0, sizeof(t));
730 if (year < 1900) 731 if (year < 1900)
731 { 732 {
732 GNUNET_break (0); 733 GNUNET_break(0);
733 return GNUNET_TIME_absolute_get (); /* now */ 734 return GNUNET_TIME_absolute_get(); /* now */
734 } 735 }
735 t.tm_year = year - 1900; 736 t.tm_year = year - 1900;
736 t.tm_mday = 1; 737 t.tm_mday = 1;
737 t.tm_mon = 0; 738 t.tm_mon = 0;
738 t.tm_wday = 1; 739 t.tm_wday = 1;
739 t.tm_yday = 1; 740 t.tm_yday = 1;
740 tp = mktime (&t); 741 tp = mktime(&t);
741 GNUNET_break (tp != (time_t) -1); 742 GNUNET_break(tp != (time_t)-1);
742 ret.abs_value_us = tp * 1000LL * 1000LL; /* seconds to microseconds */ 743 ret.abs_value_us = tp * 1000LL * 1000LL; /* seconds to microseconds */
743 return ret; 744 return ret;
744} 745}
@@ -754,16 +755,16 @@ GNUNET_TIME_year_to_time (unsigned int year)
754 * @return the next backoff time 755 * @return the next backoff time
755 */ 756 */
756struct GNUNET_TIME_Relative 757struct GNUNET_TIME_Relative
757GNUNET_TIME_randomized_backoff (struct GNUNET_TIME_Relative rt, 758GNUNET_TIME_randomized_backoff(struct GNUNET_TIME_Relative rt,
758 struct GNUNET_TIME_Relative threshold) 759 struct GNUNET_TIME_Relative threshold)
759{ 760{
760 double r = (rand () % 500) / 1000.0; 761 double r = (rand() % 500) / 1000.0;
761 struct GNUNET_TIME_Relative t; 762 struct GNUNET_TIME_Relative t;
762 763
763 t = relative_multiply_double ( 764 t = relative_multiply_double(
764 GNUNET_TIME_relative_max (GNUNET_TIME_UNIT_MILLISECONDS, rt), 765 GNUNET_TIME_relative_max(GNUNET_TIME_UNIT_MILLISECONDS, rt),
765 2 + r); 766 2 + r);
766 return GNUNET_TIME_relative_min (threshold, t); 767 return GNUNET_TIME_relative_min(threshold, t);
767} 768}
768 769
769 770
@@ -774,11 +775,11 @@ GNUNET_TIME_randomized_backoff (struct GNUNET_TIME_Relative rt,
774 * @return randomized time 775 * @return randomized time
775 */ 776 */
776struct GNUNET_TIME_Relative 777struct GNUNET_TIME_Relative
777GNUNET_TIME_randomize (struct GNUNET_TIME_Relative r) 778GNUNET_TIME_randomize(struct GNUNET_TIME_Relative r)
778{ 779{
779 double d = ((rand () % 1001) - 500) / 1000.0; 780 double d = ((rand() % 1001) - 500) / 1000.0;
780 781
781 return relative_multiply_double (r, d); 782 return relative_multiply_double(r, d);
782} 783}
783 784
784 785
@@ -801,7 +802,7 @@ GNUNET_TIME_randomize (struct GNUNET_TIME_Relative r)
801 * @return monotonically increasing time 802 * @return monotonically increasing time
802 */ 803 */
803struct GNUNET_TIME_Absolute 804struct GNUNET_TIME_Absolute
804GNUNET_TIME_absolute_get_monotonic ( 805GNUNET_TIME_absolute_get_monotonic(
805 const struct GNUNET_CONFIGURATION_Handle *cfg) 806 const struct GNUNET_CONFIGURATION_Handle *cfg)
806{ 807{
807 static const struct GNUNET_CONFIGURATION_Handle *last_cfg; 808 static const struct GNUNET_CONFIGURATION_Handle *last_cfg;
@@ -810,114 +811,114 @@ GNUNET_TIME_absolute_get_monotonic (
810 static ATOMIC volatile uint64_t *map; 811 static ATOMIC volatile uint64_t *map;
811 struct GNUNET_TIME_Absolute now; 812 struct GNUNET_TIME_Absolute now;
812 813
813 now = GNUNET_TIME_absolute_get (); 814 now = GNUNET_TIME_absolute_get();
814 if (last_cfg != cfg) 815 if (last_cfg != cfg)
815 {
816 char *filename;
817
818 if (NULL != map_handle)
819 { 816 {
820 GNUNET_DISK_file_unmap (map_handle); 817 char *filename;
821 map_handle = NULL;
822 }
823 map = NULL;
824
825 last_cfg = cfg;
826 if ((NULL != cfg) &&
827 (GNUNET_OK ==
828 GNUNET_CONFIGURATION_get_value_filename (cfg,
829 "util",
830 "MONOTONIC_TIME_FILENAME",
831 &filename)))
832 {
833 struct GNUNET_DISK_FileHandle *fh;
834
835 fh = GNUNET_DISK_file_open (filename,
836 GNUNET_DISK_OPEN_READWRITE |
837 GNUNET_DISK_OPEN_CREATE,
838 GNUNET_DISK_PERM_USER_WRITE |
839 GNUNET_DISK_PERM_GROUP_WRITE |
840 GNUNET_DISK_PERM_USER_READ |
841 GNUNET_DISK_PERM_GROUP_READ);
842 if (NULL == fh)
843 {
844 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
845 _ ("Failed to map `%s', cannot assure monotonic time!\n"),
846 filename);
847 }
848 else
849 {
850 off_t size;
851
852 size = 0;
853 GNUNET_break (GNUNET_OK == GNUNET_DISK_file_handle_size (fh, &size));
854 if (size < (off_t) sizeof (*map))
855 {
856 struct GNUNET_TIME_AbsoluteNBO o;
857 818
858 o = GNUNET_TIME_absolute_hton (now); 819 if (NULL != map_handle)
859 if (sizeof (o) != GNUNET_DISK_file_write (fh, &o, sizeof (o)))
860 size = 0;
861 else
862 size = sizeof (o);
863 }
864 if (size == sizeof (*map))
865 { 820 {
866 map = GNUNET_DISK_file_map (fh, 821 GNUNET_DISK_file_unmap(map_handle);
867 &map_handle, 822 map_handle = NULL;
868 GNUNET_DISK_MAP_TYPE_READWRITE,
869 sizeof (*map));
870 if (NULL == map)
871 GNUNET_log (GNUNET_ERROR_TYPE_WARNING,
872 _ (
873 "Failed to map `%s', cannot assure monotonic time!\n"),
874 filename);
875 } 823 }
876 else 824 map = NULL;
825
826 last_cfg = cfg;
827 if ((NULL != cfg) &&
828 (GNUNET_OK ==
829 GNUNET_CONFIGURATION_get_value_filename(cfg,
830 "util",
831 "MONOTONIC_TIME_FILENAME",
832 &filename)))
877 { 833 {
878 GNUNET_log ( 834 struct GNUNET_DISK_FileHandle *fh;
879 GNUNET_ERROR_TYPE_WARNING, 835
880 _ ( 836 fh = GNUNET_DISK_file_open(filename,
881 "Failed to setup monotonic time file `%s', cannot assure monotonic time!\n"), 837 GNUNET_DISK_OPEN_READWRITE |
882 filename); 838 GNUNET_DISK_OPEN_CREATE,
839 GNUNET_DISK_PERM_USER_WRITE |
840 GNUNET_DISK_PERM_GROUP_WRITE |
841 GNUNET_DISK_PERM_USER_READ |
842 GNUNET_DISK_PERM_GROUP_READ);
843 if (NULL == fh)
844 {
845 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
846 _("Failed to map `%s', cannot assure monotonic time!\n"),
847 filename);
848 }
849 else
850 {
851 off_t size;
852
853 size = 0;
854 GNUNET_break(GNUNET_OK == GNUNET_DISK_file_handle_size(fh, &size));
855 if (size < (off_t)sizeof(*map))
856 {
857 struct GNUNET_TIME_AbsoluteNBO o;
858
859 o = GNUNET_TIME_absolute_hton(now);
860 if (sizeof(o) != GNUNET_DISK_file_write(fh, &o, sizeof(o)))
861 size = 0;
862 else
863 size = sizeof(o);
864 }
865 if (size == sizeof(*map))
866 {
867 map = GNUNET_DISK_file_map(fh,
868 &map_handle,
869 GNUNET_DISK_MAP_TYPE_READWRITE,
870 sizeof(*map));
871 if (NULL == map)
872 GNUNET_log(GNUNET_ERROR_TYPE_WARNING,
873 _(
874 "Failed to map `%s', cannot assure monotonic time!\n"),
875 filename);
876 }
877 else
878 {
879 GNUNET_log(
880 GNUNET_ERROR_TYPE_WARNING,
881 _(
882 "Failed to setup monotonic time file `%s', cannot assure monotonic time!\n"),
883 filename);
884 }
885 }
886 GNUNET_DISK_file_close(fh);
887 GNUNET_free(filename);
883 } 888 }
884 }
885 GNUNET_DISK_file_close (fh);
886 GNUNET_free (filename);
887 } 889 }
888 }
889 if (NULL != map) 890 if (NULL != map)
890 { 891 {
891 struct GNUNET_TIME_AbsoluteNBO mt; 892 struct GNUNET_TIME_AbsoluteNBO mt;
892 893
893#if __STDC_NO_ATOMICS__ 894#if __STDC_NO_ATOMICS__
894#if __GNUC__ 895#if __GNUC__
895 mt.abs_value_us__ = __sync_fetch_and_or (map, 0); 896 mt.abs_value_us__ = __sync_fetch_and_or(map, 0);
896#else 897#else
897 mt.abs_value_us__ = *map; /* godspeed, pray this is atomic */ 898 mt.abs_value_us__ = *map; /* godspeed, pray this is atomic */
898#endif 899#endif
899#else 900#else
900 mt.abs_value_us__ = atomic_load (map); 901 mt.abs_value_us__ = atomic_load(map);
901#endif 902#endif
902 last_time = 903 last_time =
903 GNUNET_TIME_absolute_max (GNUNET_TIME_absolute_ntoh (mt), last_time); 904 GNUNET_TIME_absolute_max(GNUNET_TIME_absolute_ntoh(mt), last_time);
904 } 905 }
905 if (now.abs_value_us <= last_time.abs_value_us) 906 if (now.abs_value_us <= last_time.abs_value_us)
906 now.abs_value_us = last_time.abs_value_us + 1; 907 now.abs_value_us = last_time.abs_value_us + 1;
907 last_time = now; 908 last_time = now;
908 if (NULL != map) 909 if (NULL != map)
909 { 910 {
910 uint64_t val = GNUNET_TIME_absolute_hton (now).abs_value_us__; 911 uint64_t val = GNUNET_TIME_absolute_hton(now).abs_value_us__;
911#if __STDC_NO_ATOMICS__ 912#if __STDC_NO_ATOMICS__
912#if __GNUC__ 913#if __GNUC__
913 (void) __sync_lock_test_and_set (map, val); 914 (void)__sync_lock_test_and_set(map, val);
914#else 915#else
915 *map = val; /* godspeed, pray this is atomic */ 916 *map = val; /* godspeed, pray this is atomic */
916#endif 917#endif
917#else 918#else
918 atomic_store (map, val); 919 atomic_store(map, val);
919#endif 920#endif
920 } 921 }
921 return now; 922 return now;
922} 923}
923 924
@@ -925,9 +926,9 @@ GNUNET_TIME_absolute_get_monotonic (
925/** 926/**
926 * Destructor 927 * Destructor
927 */ 928 */
928void __attribute__ ((destructor)) GNUNET_util_time_fini () 929void __attribute__ ((destructor)) GNUNET_util_time_fini()
929{ 930{
930 (void) GNUNET_TIME_absolute_get_monotonic (NULL); 931 (void)GNUNET_TIME_absolute_get_monotonic(NULL);
931} 932}
932 933
933/* end of time.c */ 934/* end of time.c */
diff --git a/src/util/tun.c b/src/util/tun.c
index e3643d0c6..f3b97b860 100644
--- a/src/util/tun.c
+++ b/src/util/tun.c
@@ -16,7 +16,7 @@
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file tun/tun.c 22 * @file tun/tun.c
@@ -43,28 +43,28 @@
43 * @param dst destination IP address to use 43 * @param dst destination IP address to use
44 */ 44 */
45void 45void
46GNUNET_TUN_initialize_ipv4_header (struct GNUNET_TUN_IPv4Header *ip, 46GNUNET_TUN_initialize_ipv4_header(struct GNUNET_TUN_IPv4Header *ip,
47 uint8_t protocol, 47 uint8_t protocol,
48 uint16_t payload_length, 48 uint16_t payload_length,
49 const struct in_addr *src, 49 const struct in_addr *src,
50 const struct in_addr *dst) 50 const struct in_addr *dst)
51{ 51{
52 GNUNET_assert (20 == sizeof (struct GNUNET_TUN_IPv4Header)); 52 GNUNET_assert(20 == sizeof(struct GNUNET_TUN_IPv4Header));
53 GNUNET_assert (payload_length <= 53 GNUNET_assert(payload_length <=
54 UINT16_MAX - sizeof (struct GNUNET_TUN_IPv4Header)); 54 UINT16_MAX - sizeof(struct GNUNET_TUN_IPv4Header));
55 memset (ip, 0, sizeof (struct GNUNET_TUN_IPv4Header)); 55 memset(ip, 0, sizeof(struct GNUNET_TUN_IPv4Header));
56 ip->header_length = sizeof (struct GNUNET_TUN_IPv4Header) / 4; 56 ip->header_length = sizeof(struct GNUNET_TUN_IPv4Header) / 4;
57 ip->version = 4; 57 ip->version = 4;
58 ip->total_length = 58 ip->total_length =
59 htons (sizeof (struct GNUNET_TUN_IPv4Header) + payload_length); 59 htons(sizeof(struct GNUNET_TUN_IPv4Header) + payload_length);
60 ip->identification = 60 ip->identification =
61 (uint16_t) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, 65536); 61 (uint16_t)GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, 65536);
62 ip->ttl = FRESH_TTL; 62 ip->ttl = FRESH_TTL;
63 ip->protocol = protocol; 63 ip->protocol = protocol;
64 ip->source_address = *src; 64 ip->source_address = *src;
65 ip->destination_address = *dst; 65 ip->destination_address = *dst;
66 ip->checksum = 66 ip->checksum =
67 GNUNET_CRYPTO_crc16_n (ip, sizeof (struct GNUNET_TUN_IPv4Header)); 67 GNUNET_CRYPTO_crc16_n(ip, sizeof(struct GNUNET_TUN_IPv4Header));
68} 68}
69 69
70 70
@@ -78,19 +78,19 @@ GNUNET_TUN_initialize_ipv4_header (struct GNUNET_TUN_IPv4Header *ip,
78 * @param dst destination IP address to use 78 * @param dst destination IP address to use
79 */ 79 */
80void 80void
81GNUNET_TUN_initialize_ipv6_header (struct GNUNET_TUN_IPv6Header *ip, 81GNUNET_TUN_initialize_ipv6_header(struct GNUNET_TUN_IPv6Header *ip,
82 uint8_t protocol, 82 uint8_t protocol,
83 uint16_t payload_length, 83 uint16_t payload_length,
84 const struct in6_addr *src, 84 const struct in6_addr *src,
85 const struct in6_addr *dst) 85 const struct in6_addr *dst)
86{ 86{
87 GNUNET_assert (40 == sizeof (struct GNUNET_TUN_IPv6Header)); 87 GNUNET_assert(40 == sizeof(struct GNUNET_TUN_IPv6Header));
88 GNUNET_assert (payload_length <= 88 GNUNET_assert(payload_length <=
89 UINT16_MAX - sizeof (struct GNUNET_TUN_IPv6Header)); 89 UINT16_MAX - sizeof(struct GNUNET_TUN_IPv6Header));
90 memset (ip, 0, sizeof (struct GNUNET_TUN_IPv6Header)); 90 memset(ip, 0, sizeof(struct GNUNET_TUN_IPv6Header));
91 ip->version = 6; 91 ip->version = 6;
92 ip->next_header = protocol; 92 ip->next_header = protocol;
93 ip->payload_length = htons ((uint16_t) payload_length); 93 ip->payload_length = htons((uint16_t)payload_length);
94 ip->hop_limit = FRESH_TTL; 94 ip->hop_limit = FRESH_TTL;
95 ip->destination_address = *dst; 95 ip->destination_address = *dst;
96 ip->source_address = *src; 96 ip->source_address = *src;
@@ -106,32 +106,32 @@ GNUNET_TUN_initialize_ipv6_header (struct GNUNET_TUN_IPv6Header *ip,
106 * @param payload_length number of bytes of TCP payload 106 * @param payload_length number of bytes of TCP payload
107 */ 107 */
108void 108void
109GNUNET_TUN_calculate_tcp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, 109GNUNET_TUN_calculate_tcp4_checksum(const struct GNUNET_TUN_IPv4Header *ip,
110 struct GNUNET_TUN_TcpHeader *tcp, 110 struct GNUNET_TUN_TcpHeader *tcp,
111 const void *payload, 111 const void *payload,
112 uint16_t payload_length) 112 uint16_t payload_length)
113{ 113{
114 uint32_t sum; 114 uint32_t sum;
115 uint16_t tmp; 115 uint16_t tmp;
116 116
117 GNUNET_assert (20 == sizeof (struct GNUNET_TUN_TcpHeader)); 117 GNUNET_assert(20 == sizeof(struct GNUNET_TUN_TcpHeader));
118 GNUNET_assert (payload_length + sizeof (struct GNUNET_TUN_IPv4Header) + 118 GNUNET_assert(payload_length + sizeof(struct GNUNET_TUN_IPv4Header) +
119 sizeof (struct GNUNET_TUN_TcpHeader) == 119 sizeof(struct GNUNET_TUN_TcpHeader) ==
120 ntohs (ip->total_length)); 120 ntohs(ip->total_length));
121 GNUNET_assert (IPPROTO_TCP == ip->protocol); 121 GNUNET_assert(IPPROTO_TCP == ip->protocol);
122 122
123 tcp->crc = 0; 123 tcp->crc = 0;
124 sum = GNUNET_CRYPTO_crc16_step (0, 124 sum = GNUNET_CRYPTO_crc16_step(0,
125 &ip->source_address, 125 &ip->source_address,
126 sizeof (struct in_addr) * 2); 126 sizeof(struct in_addr) * 2);
127 tmp = htons (IPPROTO_TCP); 127 tmp = htons(IPPROTO_TCP);
128 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint16_t)); 128 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint16_t));
129 tmp = htons (payload_length + sizeof (struct GNUNET_TUN_TcpHeader)); 129 tmp = htons(payload_length + sizeof(struct GNUNET_TUN_TcpHeader));
130 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint16_t)); 130 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint16_t));
131 sum = 131 sum =
132 GNUNET_CRYPTO_crc16_step (sum, tcp, sizeof (struct GNUNET_TUN_TcpHeader)); 132 GNUNET_CRYPTO_crc16_step(sum, tcp, sizeof(struct GNUNET_TUN_TcpHeader));
133 sum = GNUNET_CRYPTO_crc16_step (sum, payload, payload_length); 133 sum = GNUNET_CRYPTO_crc16_step(sum, payload, payload_length);
134 tcp->crc = GNUNET_CRYPTO_crc16_finish (sum); 134 tcp->crc = GNUNET_CRYPTO_crc16_finish(sum);
135} 135}
136 136
137 137
@@ -144,30 +144,30 @@ GNUNET_TUN_calculate_tcp4_checksum (const struct GNUNET_TUN_IPv4Header *ip,
144 * @param payload_length number of bytes of TCP payload 144 * @param payload_length number of bytes of TCP payload
145 */ 145 */
146void 146void
147GNUNET_TUN_calculate_tcp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, 147GNUNET_TUN_calculate_tcp6_checksum(const struct GNUNET_TUN_IPv6Header *ip,
148 struct GNUNET_TUN_TcpHeader *tcp, 148 struct GNUNET_TUN_TcpHeader *tcp,
149 const void *payload, 149 const void *payload,
150 uint16_t payload_length) 150 uint16_t payload_length)
151{ 151{
152 uint32_t sum; 152 uint32_t sum;
153 uint32_t tmp; 153 uint32_t tmp;
154 154
155 GNUNET_assert (20 == sizeof (struct GNUNET_TUN_TcpHeader)); 155 GNUNET_assert(20 == sizeof(struct GNUNET_TUN_TcpHeader));
156 GNUNET_assert (payload_length + sizeof (struct GNUNET_TUN_TcpHeader) == 156 GNUNET_assert(payload_length + sizeof(struct GNUNET_TUN_TcpHeader) ==
157 ntohs (ip->payload_length)); 157 ntohs(ip->payload_length));
158 GNUNET_assert (IPPROTO_TCP == ip->next_header); 158 GNUNET_assert(IPPROTO_TCP == ip->next_header);
159 tcp->crc = 0; 159 tcp->crc = 0;
160 sum = GNUNET_CRYPTO_crc16_step (0, 160 sum = GNUNET_CRYPTO_crc16_step(0,
161 &ip->source_address, 161 &ip->source_address,
162 2 * sizeof (struct in6_addr)); 162 2 * sizeof(struct in6_addr));
163 tmp = htonl (sizeof (struct GNUNET_TUN_TcpHeader) + payload_length); 163 tmp = htonl(sizeof(struct GNUNET_TUN_TcpHeader) + payload_length);
164 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t)); 164 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint32_t));
165 tmp = htonl (IPPROTO_TCP); 165 tmp = htonl(IPPROTO_TCP);
166 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t)); 166 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint32_t));
167 sum = 167 sum =
168 GNUNET_CRYPTO_crc16_step (sum, tcp, sizeof (struct GNUNET_TUN_TcpHeader)); 168 GNUNET_CRYPTO_crc16_step(sum, tcp, sizeof(struct GNUNET_TUN_TcpHeader));
169 sum = GNUNET_CRYPTO_crc16_step (sum, payload, payload_length); 169 sum = GNUNET_CRYPTO_crc16_step(sum, payload, payload_length);
170 tcp->crc = GNUNET_CRYPTO_crc16_finish (sum); 170 tcp->crc = GNUNET_CRYPTO_crc16_finish(sum);
171} 171}
172 172
173 173
@@ -180,33 +180,33 @@ GNUNET_TUN_calculate_tcp6_checksum (const struct GNUNET_TUN_IPv6Header *ip,
180 * @param payload_length number of bytes of UDP payload 180 * @param payload_length number of bytes of UDP payload
181 */ 181 */
182void 182void
183GNUNET_TUN_calculate_udp4_checksum (const struct GNUNET_TUN_IPv4Header *ip, 183GNUNET_TUN_calculate_udp4_checksum(const struct GNUNET_TUN_IPv4Header *ip,
184 struct GNUNET_TUN_UdpHeader *udp, 184 struct GNUNET_TUN_UdpHeader *udp,
185 const void *payload, 185 const void *payload,
186 uint16_t payload_length) 186 uint16_t payload_length)
187{ 187{
188 uint32_t sum; 188 uint32_t sum;
189 uint16_t tmp; 189 uint16_t tmp;
190 190
191 GNUNET_assert (8 == sizeof (struct GNUNET_TUN_UdpHeader)); 191 GNUNET_assert(8 == sizeof(struct GNUNET_TUN_UdpHeader));
192 GNUNET_assert (payload_length + sizeof (struct GNUNET_TUN_IPv4Header) + 192 GNUNET_assert(payload_length + sizeof(struct GNUNET_TUN_IPv4Header) +
193 sizeof (struct GNUNET_TUN_UdpHeader) == 193 sizeof(struct GNUNET_TUN_UdpHeader) ==
194 ntohs (ip->total_length)); 194 ntohs(ip->total_length));
195 GNUNET_assert (IPPROTO_UDP == ip->protocol); 195 GNUNET_assert(IPPROTO_UDP == ip->protocol);
196 196
197 udp->crc = 197 udp->crc =
198 0; /* technically optional, but we calculate it anyway, just to be sure */ 198 0; /* technically optional, but we calculate it anyway, just to be sure */
199 sum = GNUNET_CRYPTO_crc16_step (0, 199 sum = GNUNET_CRYPTO_crc16_step(0,
200 &ip->source_address, 200 &ip->source_address,
201 sizeof (struct in_addr) * 2); 201 sizeof(struct in_addr) * 2);
202 tmp = htons (IPPROTO_UDP); 202 tmp = htons(IPPROTO_UDP);
203 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint16_t)); 203 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint16_t));
204 tmp = htons (sizeof (struct GNUNET_TUN_UdpHeader) + payload_length); 204 tmp = htons(sizeof(struct GNUNET_TUN_UdpHeader) + payload_length);
205 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint16_t)); 205 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint16_t));
206 sum = 206 sum =
207 GNUNET_CRYPTO_crc16_step (sum, udp, sizeof (struct GNUNET_TUN_UdpHeader)); 207 GNUNET_CRYPTO_crc16_step(sum, udp, sizeof(struct GNUNET_TUN_UdpHeader));
208 sum = GNUNET_CRYPTO_crc16_step (sum, payload, payload_length); 208 sum = GNUNET_CRYPTO_crc16_step(sum, payload, payload_length);
209 udp->crc = GNUNET_CRYPTO_crc16_finish (sum); 209 udp->crc = GNUNET_CRYPTO_crc16_finish(sum);
210} 210}
211 211
212 212
@@ -219,33 +219,33 @@ GNUNET_TUN_calculate_udp4_checksum (const struct GNUNET_TUN_IPv4Header *ip,
219 * @param payload_length number of bytes of UDP payload 219 * @param payload_length number of bytes of UDP payload
220 */ 220 */
221void 221void
222GNUNET_TUN_calculate_udp6_checksum (const struct GNUNET_TUN_IPv6Header *ip, 222GNUNET_TUN_calculate_udp6_checksum(const struct GNUNET_TUN_IPv6Header *ip,
223 struct GNUNET_TUN_UdpHeader *udp, 223 struct GNUNET_TUN_UdpHeader *udp,
224 const void *payload, 224 const void *payload,
225 uint16_t payload_length) 225 uint16_t payload_length)
226{ 226{
227 uint32_t sum; 227 uint32_t sum;
228 uint32_t tmp; 228 uint32_t tmp;
229 229
230 GNUNET_assert (payload_length + sizeof (struct GNUNET_TUN_UdpHeader) == 230 GNUNET_assert(payload_length + sizeof(struct GNUNET_TUN_UdpHeader) ==
231 ntohs (ip->payload_length)); 231 ntohs(ip->payload_length));
232 GNUNET_assert (payload_length + sizeof (struct GNUNET_TUN_UdpHeader) == 232 GNUNET_assert(payload_length + sizeof(struct GNUNET_TUN_UdpHeader) ==
233 ntohs (udp->len)); 233 ntohs(udp->len));
234 GNUNET_assert (IPPROTO_UDP == ip->next_header); 234 GNUNET_assert(IPPROTO_UDP == ip->next_header);
235 235
236 udp->crc = 0; 236 udp->crc = 0;
237 sum = GNUNET_CRYPTO_crc16_step (0, 237 sum = GNUNET_CRYPTO_crc16_step(0,
238 &ip->source_address, 238 &ip->source_address,
239 sizeof (struct in6_addr) * 2); 239 sizeof(struct in6_addr) * 2);
240 tmp = htons (sizeof (struct GNUNET_TUN_UdpHeader) + 240 tmp = htons(sizeof(struct GNUNET_TUN_UdpHeader) +
241 payload_length); /* aka udp->len */ 241 payload_length); /* aka udp->len */
242 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t)); 242 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint32_t));
243 tmp = htons (ip->next_header); 243 tmp = htons(ip->next_header);
244 sum = GNUNET_CRYPTO_crc16_step (sum, &tmp, sizeof (uint32_t)); 244 sum = GNUNET_CRYPTO_crc16_step(sum, &tmp, sizeof(uint32_t));
245 sum = 245 sum =
246 GNUNET_CRYPTO_crc16_step (sum, udp, sizeof (struct GNUNET_TUN_UdpHeader)); 246 GNUNET_CRYPTO_crc16_step(sum, udp, sizeof(struct GNUNET_TUN_UdpHeader));
247 sum = GNUNET_CRYPTO_crc16_step (sum, payload, payload_length); 247 sum = GNUNET_CRYPTO_crc16_step(sum, payload, payload_length);
248 udp->crc = GNUNET_CRYPTO_crc16_finish (sum); 248 udp->crc = GNUNET_CRYPTO_crc16_finish(sum);
249} 249}
250 250
251 251
@@ -257,18 +257,18 @@ GNUNET_TUN_calculate_udp6_checksum (const struct GNUNET_TUN_IPv6Header *ip,
257 * @param payload_length number of bytes of ICMP payload 257 * @param payload_length number of bytes of ICMP payload
258 */ 258 */
259void 259void
260GNUNET_TUN_calculate_icmp_checksum (struct GNUNET_TUN_IcmpHeader *icmp, 260GNUNET_TUN_calculate_icmp_checksum(struct GNUNET_TUN_IcmpHeader *icmp,
261 const void *payload, 261 const void *payload,
262 uint16_t payload_length) 262 uint16_t payload_length)
263{ 263{
264 uint32_t sum; 264 uint32_t sum;
265 265
266 GNUNET_assert (8 == sizeof (struct GNUNET_TUN_IcmpHeader)); 266 GNUNET_assert(8 == sizeof(struct GNUNET_TUN_IcmpHeader));
267 icmp->crc = 0; 267 icmp->crc = 0;
268 sum = 268 sum =
269 GNUNET_CRYPTO_crc16_step (0, icmp, sizeof (struct GNUNET_TUN_IcmpHeader)); 269 GNUNET_CRYPTO_crc16_step(0, icmp, sizeof(struct GNUNET_TUN_IcmpHeader));
270 sum = GNUNET_CRYPTO_crc16_step (sum, payload, payload_length); 270 sum = GNUNET_CRYPTO_crc16_step(sum, payload, payload_length);
271 icmp->crc = GNUNET_CRYPTO_crc16_finish (sum); 271 icmp->crc = GNUNET_CRYPTO_crc16_finish(sum);
272} 272}
273 273
274 274
@@ -281,35 +281,37 @@ GNUNET_TUN_calculate_icmp_checksum (struct GNUNET_TUN_IcmpHeader *icmp,
281 * @return #GNUNET_YES if they are equal 281 * @return #GNUNET_YES if they are equal
282 */ 282 */
283int 283int
284GNUNET_TUN_sockaddr_cmp (const struct sockaddr *sa, 284GNUNET_TUN_sockaddr_cmp(const struct sockaddr *sa,
285 const struct sockaddr *sb, 285 const struct sockaddr *sb,
286 int include_port) 286 int include_port)
287{ 287{
288 if (sa->sa_family != sb->sa_family) 288 if (sa->sa_family != sb->sa_family)
289 return GNUNET_NO; 289 return GNUNET_NO;
290 290
291 switch (sa->sa_family) 291 switch (sa->sa_family)
292 { 292 {
293 case AF_INET: { 293 case AF_INET: {
294 const struct sockaddr_in *sa4 = (const struct sockaddr_in *) sa; 294 const struct sockaddr_in *sa4 = (const struct sockaddr_in *)sa;
295 const struct sockaddr_in *sb4 = (const struct sockaddr_in *) sb; 295 const struct sockaddr_in *sb4 = (const struct sockaddr_in *)sb;
296 if ((include_port) && (sa4->sin_port != sb4->sin_port)) 296 if ((include_port) && (sa4->sin_port != sb4->sin_port))
297 return GNUNET_NO; 297 return GNUNET_NO;
298 return (sa4->sin_addr.s_addr == sb4->sin_addr.s_addr); 298 return(sa4->sin_addr.s_addr == sb4->sin_addr.s_addr);
299 } 299 }
300 case AF_INET6: { 300
301 const struct sockaddr_in6 *sa6 = (const struct sockaddr_in6 *) sa; 301 case AF_INET6: {
302 const struct sockaddr_in6 *sb6 = (const struct sockaddr_in6 *) sb; 302 const struct sockaddr_in6 *sa6 = (const struct sockaddr_in6 *)sa;
303 303 const struct sockaddr_in6 *sb6 = (const struct sockaddr_in6 *)sb;
304 if ((include_port) && (sa6->sin6_port != sb6->sin6_port)) 304
305 return GNUNET_NO; 305 if ((include_port) && (sa6->sin6_port != sb6->sin6_port))
306 return ( 306 return GNUNET_NO;
307 0 == memcmp (&sa6->sin6_addr, &sb6->sin6_addr, sizeof (struct in6_addr))); 307 return(
308 } 308 0 == memcmp(&sa6->sin6_addr, &sb6->sin6_addr, sizeof(struct in6_addr)));
309 default: 309 }
310 GNUNET_break (0); 310
311 return GNUNET_SYSERR; 311 default:
312 } 312 GNUNET_break(0);
313 return GNUNET_SYSERR;
314 }
313} 315}
314 316
315 317
diff --git a/src/util/w32cat.c b/src/util/w32cat.c
index 8a48638aa..fa7637d38 100644
--- a/src/util/w32cat.c
+++ b/src/util/w32cat.c
@@ -18,7 +18,7 @@
18 Boston, MA 02110-1301, USA. 18 Boston, MA 02110-1301, USA.
19 19
20 SPDX-License-Identifier: AGPL3.0-or-later 20 SPDX-License-Identifier: AGPL3.0-or-later
21*/ 21 */
22 22
23#include <stdio.h> 23#include <stdio.h>
24#include <windows.h> 24#include <windows.h>
@@ -26,45 +26,46 @@
26#include <signal.h> 26#include <signal.h>
27 27
28DWORD WINAPI 28DWORD WINAPI
29parent_control_thread (LPVOID lpParameter) 29parent_control_thread(LPVOID lpParameter)
30{ 30{
31 HANDLE h = (HANDLE) lpParameter; 31 HANDLE h = (HANDLE)lpParameter;
32
32 while (TRUE) 33 while (TRUE)
33 {
34 DWORD dw;
35 BOOL b;
36 unsigned char c;
37 b = ReadFile (h, &c, 1, &dw, NULL);
38 if (!b)
39 { 34 {
40 ExitProcess (0); 35 DWORD dw;
36 BOOL b;
37 unsigned char c;
38 b = ReadFile(h, &c, 1, &dw, NULL);
39 if (!b)
40 {
41 ExitProcess(0);
42 }
43 raise((int)c);
41 } 44 }
42 raise ((int) c);
43 }
44} 45}
45 46
46void 47void
47install_parent_control_handler () 48install_parent_control_handler()
48{ 49{
49 const char *env_buf; 50 const char *env_buf;
50 char *env_buf_end; 51 char *env_buf_end;
51 uint64_t pipe_fd; 52 uint64_t pipe_fd;
52 HANDLE pipe_handle; 53 HANDLE pipe_handle;
53 54
54 env_buf = getenv ("GNUNET_OS_CONTROL_PIPE"); 55 env_buf = getenv("GNUNET_OS_CONTROL_PIPE");
55 if ( (NULL == env_buf) || (strlen (env_buf) <= 0) ) 56 if ((NULL == env_buf) || (strlen(env_buf) <= 0))
56 return; 57 return;
57 errno = 0; 58 errno = 0;
58 pipe_fd = strtoull (env_buf, &env_buf_end, 16); 59 pipe_fd = strtoull(env_buf, &env_buf_end, 16);
59 if ((0 != errno) || (env_buf == env_buf_end)) 60 if ((0 != errno) || (env_buf == env_buf_end))
60 return; 61 return;
61 /* Gcc will issue a warning here. What to do with it? */ 62 /* Gcc will issue a warning here. What to do with it? */
62 pipe_handle = (HANDLE) (uintptr_t) pipe_fd; 63 pipe_handle = (HANDLE)(uintptr_t)pipe_fd;
63 CreateThread (NULL, 0, parent_control_thread, (LPVOID) pipe_handle, 0, NULL); 64 CreateThread(NULL, 0, parent_control_thread, (LPVOID)pipe_handle, 0, NULL);
64} 65}
65 66
66int 67int
67main (int argc, char **argv) 68main(int argc, char **argv)
68{ 69{
69 HANDLE stdi, stdo; 70 HANDLE stdi, stdo;
70 BOOL b; 71 BOOL b;
@@ -72,81 +73,82 @@ main (int argc, char **argv)
72 int argcw; 73 int argcw;
73 int i; 74 int i;
74 75
75 stdo = GetStdHandle (STD_OUTPUT_HANDLE); 76 stdo = GetStdHandle(STD_OUTPUT_HANDLE);
76 if (stdo == INVALID_HANDLE_VALUE || stdo == NULL) 77 if (stdo == INVALID_HANDLE_VALUE || stdo == NULL)
77 return 1; 78 return 1;
78 79
79 commandlinew = GetCommandLineW (); 80 commandlinew = GetCommandLineW();
80 argvw = CommandLineToArgvW (commandlinew, &argcw); 81 argvw = CommandLineToArgvW(commandlinew, &argcw);
81 if (argvw == NULL) 82 if (argvw == NULL)
82 return 1; 83 return 1;
83 84
84 install_parent_control_handler (); 85 install_parent_control_handler();
85 86
86 for (i = 1; i < argcw || argcw == 1; i++) 87 for (i = 1; i < argcw || argcw == 1; i++)
87 {
88 DWORD r, w;
89 int is_dash = wcscmp (NULL == argvw[i] ? L"-" : argvw[i], L"-") == 0;
90 if (argcw == 1 || is_dash)
91 {
92 stdi = GetStdHandle (STD_INPUT_HANDLE);
93 if (stdi == INVALID_HANDLE_VALUE)
94 {
95 fprintf (stderr, "cat: Failed to obtain stdin handle.\n");
96 return 4;
97 }
98 if (stdi == NULL)
99 {
100 fprintf (stderr, "cat: Have no stdin.\n");
101 return 5;
102 }
103 }
104 else
105 { 88 {
106 stdi = CreateFileW (argvw[i], GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); 89 DWORD r, w;
107 if (stdi == INVALID_HANDLE_VALUE) 90 int is_dash = wcscmp(NULL == argvw[i] ? L"-" : argvw[i], L"-") == 0;
108 { 91 if (argcw == 1 || is_dash)
109 wchar_t *msgbuf;
110 DWORD le = GetLastError ();
111 if (0 < FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, le, 0, (wchar_t *) &msgbuf, 0, NULL))
112 { 92 {
113 fprintf (stderr, "cat: Failed to open file `%S'. Error %lu.\n", argvw[i], le); 93 stdi = GetStdHandle(STD_INPUT_HANDLE);
114 return 3; 94 if (stdi == INVALID_HANDLE_VALUE)
95 {
96 fprintf(stderr, "cat: Failed to obtain stdin handle.\n");
97 return 4;
98 }
99 if (stdi == NULL)
100 {
101 fprintf(stderr, "cat: Have no stdin.\n");
102 return 5;
103 }
115 } 104 }
116 fprintf (stderr, "cat: Failed to open file `%S'. Error %lu: %S\n", argvw[i], le, msgbuf); 105 else
117 if (msgbuf != NULL)
118 LocalFree (msgbuf);
119 return 2;
120 }
121 }
122 do
123 {
124 unsigned char c;
125 b = ReadFile (stdi, &c, 1, &r, NULL);
126 if (b && r > 0)
127 {
128 b = WriteFile (stdo, &c, 1, &w, NULL);
129 if (b == 0)
130 { 106 {
131 wchar_t *msgbuf; 107 stdi = CreateFileW(argvw[i], GENERIC_READ, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL);
132 DWORD le = GetLastError (); 108 if (stdi == INVALID_HANDLE_VALUE)
133 if (0 < FormatMessageW (FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, le, 0, (wchar_t *) &msgbuf, 0, NULL)) 109 {
134 { 110 wchar_t *msgbuf;
135 fprintf (stderr, "cat: Failed to write into stdout. Error %lu.\n", le); 111 DWORD le = GetLastError();
136 return 3; 112 if (0 < FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, le, 0, (wchar_t *)&msgbuf, 0, NULL))
137 } 113 {
138 fprintf (stderr, "cat: Failed to write into stdout. Error %lu: %S\n", le, msgbuf); 114 fprintf(stderr, "cat: Failed to open file `%S'. Error %lu.\n", argvw[i], le);
139 if (msgbuf != NULL) 115 return 3;
140 LocalFree (msgbuf); 116 }
141 return 6; 117 fprintf(stderr, "cat: Failed to open file `%S'. Error %lu: %S\n", argvw[i], le, msgbuf);
118 if (msgbuf != NULL)
119 LocalFree(msgbuf);
120 return 2;
121 }
142 } 122 }
143 } 123 do
144 } while (b && r > 0); 124 {
145 if (argcw == 1) 125 unsigned char c;
146 break; 126 b = ReadFile(stdi, &c, 1, &r, NULL);
147 if (!is_dash) 127 if (b && r > 0)
148 CloseHandle (stdi); 128 {
149 } 129 b = WriteFile(stdo, &c, 1, &w, NULL);
150 LocalFree (argvw); 130 if (b == 0)
131 {
132 wchar_t *msgbuf;
133 DWORD le = GetLastError();
134 if (0 < FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 0, le, 0, (wchar_t *)&msgbuf, 0, NULL))
135 {
136 fprintf(stderr, "cat: Failed to write into stdout. Error %lu.\n", le);
137 return 3;
138 }
139 fprintf(stderr, "cat: Failed to write into stdout. Error %lu: %S\n", le, msgbuf);
140 if (msgbuf != NULL)
141 LocalFree(msgbuf);
142 return 6;
143 }
144 }
145 }
146 while (b && r > 0);
147 if (argcw == 1)
148 break;
149 if (!is_dash)
150 CloseHandle(stdi);
151 }
152 LocalFree(argvw);
151 return 0; 153 return 0;
152} 154}
diff --git a/src/util/win.c b/src/util/win.c
index ad6275cc4..39b276a6c 100644
--- a/src/util/win.c
+++ b/src/util/win.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/win.c 22 * @file util/win.c
@@ -49,28 +49,28 @@ int plibc_conv_to_win_path(const char *pszUnix, char *pszWindows);
49 }; 49 };
50 50
51#define _IP_ADAPTER_UNICAST_ADDRESS_BASE \ 51#define _IP_ADAPTER_UNICAST_ADDRESS_BASE \
52 SOCKET_ADDRESS Address; \ 52 SOCKET_ADDRESS Address; \
53 IP_PREFIX_ORIGIN PrefixOrigin; \ 53 IP_PREFIX_ORIGIN PrefixOrigin; \
54 IP_SUFFIX_ORIGIN SuffixOrigin; \ 54 IP_SUFFIX_ORIGIN SuffixOrigin; \
55 IP_DAD_STATE DadState; \ 55 IP_DAD_STATE DadState; \
56 ULONG ValidLifetime; \ 56 ULONG ValidLifetime; \
57 ULONG PreferredLifetime; \ 57 ULONG PreferredLifetime; \
58 ULONG LeaseLifetime; 58 ULONG LeaseLifetime;
59 59
60#define _IP_ADAPTER_UNICAST_ADDRESS_ADD_VISTA \ 60#define _IP_ADAPTER_UNICAST_ADDRESS_ADD_VISTA \
61 UINT8 OnLinkPrefixLength; 61 UINT8 OnLinkPrefixLength;
62 62
63 63
64#define _IP_ADAPTER_UNICAST_ADDRESS_DEFINE(suffix,addition) \ 64#define _IP_ADAPTER_UNICAST_ADDRESS_DEFINE(suffix, addition) \
65typedef struct _IP_ADAPTER_UNICAST_ADDRESS##suffix { \ 65 typedef struct _IP_ADAPTER_UNICAST_ADDRESS ## suffix { \
66 _IP_ADAPTER_UNICAST_ADDRESS_HEAD \ 66 _IP_ADAPTER_UNICAST_ADDRESS_HEAD \
67 struct _IP_ADAPTER_UNICAST_ADDRESS##suffix *Next; \ 67 struct _IP_ADAPTER_UNICAST_ADDRESS ## suffix *Next; \
68 _IP_ADAPTER_UNICAST_ADDRESS_BASE \ 68 _IP_ADAPTER_UNICAST_ADDRESS_BASE \
69 addition \ 69 addition \
70} IP_ADAPTER_UNICAST_ADDRESS##suffix, *PIP_ADAPTER_UNICAST_ADDRESS##suffix; 70 } IP_ADAPTER_UNICAST_ADDRESS ## suffix, *PIP_ADAPTER_UNICAST_ADDRESS ## suffix;
71 71
72/* _IP_ADAPTER_UNICAST_ADDRESS_DEFINE(,) defined in w32api headers */ 72/* _IP_ADAPTER_UNICAST_ADDRESS_DEFINE(,) defined in w32api headers */
73_IP_ADAPTER_UNICAST_ADDRESS_DEFINE(_VISTA,_IP_ADAPTER_UNICAST_ADDRESS_ADD_VISTA) 73_IP_ADAPTER_UNICAST_ADDRESS_DEFINE(_VISTA, _IP_ADAPTER_UNICAST_ADDRESS_ADD_VISTA)
74 74
75 75
76#ifndef __MINGW64_VERSION_MAJOR 76#ifndef __MINGW64_VERSION_MAJOR
@@ -83,7 +83,7 @@ typedef struct _IP_ADAPTER_WINS_SERVER_ADDRESS {
83 }; 83 };
84 }; 84 };
85 struct _IP_ADAPTER_WINS_SERVER_ADDRESS *Next; 85 struct _IP_ADAPTER_WINS_SERVER_ADDRESS *Next;
86 SOCKET_ADDRESS Address; 86 SOCKET_ADDRESS Address;
87} IP_ADAPTER_WINS_SERVER_ADDRESS, *PIP_ADAPTER_WINS_SERVER_ADDRESS, *PIP_ADAPTER_WINS_SERVER_ADDRESS_LH; 87} IP_ADAPTER_WINS_SERVER_ADDRESS, *PIP_ADAPTER_WINS_SERVER_ADDRESS, *PIP_ADAPTER_WINS_SERVER_ADDRESS_LH;
88 88
89typedef struct _IP_ADAPTER_GATEWAY_ADDRESS { 89typedef struct _IP_ADAPTER_GATEWAY_ADDRESS {
@@ -95,7 +95,7 @@ typedef struct _IP_ADAPTER_GATEWAY_ADDRESS {
95 }; 95 };
96 }; 96 };
97 struct _IP_ADAPTER_GATEWAY_ADDRESS *Next; 97 struct _IP_ADAPTER_GATEWAY_ADDRESS *Next;
98 SOCKET_ADDRESS Address; 98 SOCKET_ADDRESS Address;
99} IP_ADAPTER_GATEWAY_ADDRESS, *PIP_ADAPTER_GATEWAY_ADDRESS, *PIP_ADAPTER_GATEWAY_ADDRESS_LH; 99} IP_ADAPTER_GATEWAY_ADDRESS, *PIP_ADAPTER_GATEWAY_ADDRESS, *PIP_ADAPTER_GATEWAY_ADDRESS_LH;
100#endif 100#endif
101 101
@@ -122,20 +122,20 @@ typedef enum {
122#endif 122#endif
123 123
124/* 124/*
125A DUID consists of a two-octet type code represented in network byte 125 A DUID consists of a two-octet type code represented in network byte
126 order, followed by a variable number of octets that make up the 126 order, followed by a variable number of octets that make up the
127 actual identifier. A DUID can be no more than 128 octets long (not 127 actual identifier. A DUID can be no more than 128 octets long (not
128 including the type code). 128 including the type code).
129*/ 129 */
130#define MAX_DHCPV6_DUID_LENGTH 130 130#define MAX_DHCPV6_DUID_LENGTH 130
131 131
132#ifndef __MINGW64_VERSION_MAJOR 132#ifndef __MINGW64_VERSION_MAJOR
133typedef union _NET_LUID { 133typedef union _NET_LUID {
134 ULONG64 Value; 134 ULONG64 Value;
135 struct { 135 struct {
136 ULONG64 Reserved :24; 136 ULONG64 Reserved : 24;
137 ULONG64 NetLuidIndex :24; 137 ULONG64 NetLuidIndex : 24;
138 ULONG64 IfType :16; 138 ULONG64 IfType : 16;
139 } Info; 139 } Info;
140} NET_LUID, *PNET_LUID, IF_LUID; 140} NET_LUID, *PNET_LUID, IF_LUID;
141 141
@@ -143,7 +143,7 @@ typedef union _NET_LUID {
143 143
144typedef struct _IP_ADAPTER_DNS_SUFFIX { 144typedef struct _IP_ADAPTER_DNS_SUFFIX {
145 struct _IP_ADAPTER_DNS_SUFFIX *Next; 145 struct _IP_ADAPTER_DNS_SUFFIX *Next;
146 WCHAR String[MAX_DNS_SUFFIX_STRING_LENGTH]; 146 WCHAR String[MAX_DNS_SUFFIX_STRING_LENGTH];
147} IP_ADAPTER_DNS_SUFFIX, *PIP_ADAPTER_DNS_SUFFIX; 147} IP_ADAPTER_DNS_SUFFIX, *PIP_ADAPTER_DNS_SUFFIX;
148#endif 148#endif
149 149
@@ -159,72 +159,73 @@ typedef struct _IP_ADAPTER_DNS_SUFFIX {
159 }; 159 };
160 160
161#define _IP_ADAPTER_ADDRESSES_BASE \ 161#define _IP_ADAPTER_ADDRESSES_BASE \
162 PCHAR AdapterName; \ 162 PCHAR AdapterName; \
163 PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress; \ 163 PIP_ADAPTER_UNICAST_ADDRESS FirstUnicastAddress; \
164 PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress; \ 164 PIP_ADAPTER_ANYCAST_ADDRESS FirstAnycastAddress; \
165 PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress; \ 165 PIP_ADAPTER_MULTICAST_ADDRESS FirstMulticastAddress; \
166 PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress; \ 166 PIP_ADAPTER_DNS_SERVER_ADDRESS FirstDnsServerAddress; \
167 PWCHAR DnsSuffix; \ 167 PWCHAR DnsSuffix; \
168 PWCHAR Description; \ 168 PWCHAR Description; \
169 PWCHAR FriendlyName; \ 169 PWCHAR FriendlyName; \
170 BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; \ 170 BYTE PhysicalAddress[MAX_ADAPTER_ADDRESS_LENGTH]; \
171 DWORD PhysicalAddressLength; \ 171 DWORD PhysicalAddressLength; \
172 DWORD Flags; \ 172 DWORD Flags; \
173 DWORD Mtu; \ 173 DWORD Mtu; \
174 DWORD IfType; \ 174 DWORD IfType; \
175 IF_OPER_STATUS OperStatus; 175 IF_OPER_STATUS OperStatus;
176 176
177#define _IP_ADAPTER_ADDRESSES_ADD_XPSP1 \ 177#define _IP_ADAPTER_ADDRESSES_ADD_XPSP1 \
178 DWORD Ipv6IfIndex; \ 178 DWORD Ipv6IfIndex; \
179 DWORD ZoneIndices[16]; \ 179 DWORD ZoneIndices[16]; \
180 PIP_ADAPTER_PREFIX FirstPrefix; \ 180 PIP_ADAPTER_PREFIX FirstPrefix; \
181 181
182 182
183#define _IP_ADAPTER_ADDRESSES_ADD_VISTA \ 183#define _IP_ADAPTER_ADDRESSES_ADD_VISTA \
184 _IP_ADAPTER_ADDRESSES_ADD_XPSP1 \ 184 _IP_ADAPTER_ADDRESSES_ADD_XPSP1 \
185 ULONG64 TransmitLinkSpeed; \ 185 ULONG64 TransmitLinkSpeed; \
186 ULONG64 ReceiveLinkSpeed; \ 186 ULONG64 ReceiveLinkSpeed; \
187 PIP_ADAPTER_WINS_SERVER_ADDRESS_LH FirstWinsServerAddress; \ 187 PIP_ADAPTER_WINS_SERVER_ADDRESS_LH FirstWinsServerAddress; \
188 PIP_ADAPTER_GATEWAY_ADDRESS_LH FirstGatewayAddress; \ 188 PIP_ADAPTER_GATEWAY_ADDRESS_LH FirstGatewayAddress; \
189 ULONG Ipv4Metric; \ 189 ULONG Ipv4Metric; \
190 ULONG Ipv6Metric; \ 190 ULONG Ipv6Metric; \
191 IF_LUID Luid; \ 191 IF_LUID Luid; \
192 SOCKET_ADDRESS Dhcpv4Server; \ 192 SOCKET_ADDRESS Dhcpv4Server; \
193 NET_IF_COMPARTMENT_ID CompartmentId; \ 193 NET_IF_COMPARTMENT_ID CompartmentId; \
194 NET_IF_NETWORK_GUID NetworkGuid; \ 194 NET_IF_NETWORK_GUID NetworkGuid; \
195 NET_IF_CONNECTION_TYPE ConnectionType; \ 195 NET_IF_CONNECTION_TYPE ConnectionType; \
196 TUNNEL_TYPE TunnelType; \ 196 TUNNEL_TYPE TunnelType; \
197 SOCKET_ADDRESS Dhcpv6Server; \ 197 SOCKET_ADDRESS Dhcpv6Server; \
198 BYTE Dhcpv6ClientDuid[MAX_DHCPV6_DUID_LENGTH]; \ 198 BYTE Dhcpv6ClientDuid[MAX_DHCPV6_DUID_LENGTH]; \
199 ULONG Dhcpv6ClientDuidLength; \ 199 ULONG Dhcpv6ClientDuidLength; \
200 ULONG Dhcpv6Iaid; 200 ULONG Dhcpv6Iaid;
201 201
202#define _IP_ADAPTER_ADDRESSES_ADD_2008_OR_VISTASP1 \ 202#define _IP_ADAPTER_ADDRESSES_ADD_2008_OR_VISTASP1 \
203 _IP_ADAPTER_ADDRESSES_ADD_VISTA \ 203 _IP_ADAPTER_ADDRESSES_ADD_VISTA \
204 PIP_ADAPTER_DNS_SUFFIX FirstDnsSuffix; 204 PIP_ADAPTER_DNS_SUFFIX FirstDnsSuffix;
205 205
206#define _IP_ADAPTER_ADDRESSES_DEFINE(suffix,addition) \ 206#define _IP_ADAPTER_ADDRESSES_DEFINE(suffix, addition) \
207typedef struct _IP_ADAPTER_ADDRESSES##suffix { \ 207 typedef struct _IP_ADAPTER_ADDRESSES ## suffix { \
208 _IP_ADAPTER_ADDRESSES_HEAD \ 208 _IP_ADAPTER_ADDRESSES_HEAD \
209 struct _IP_ADAPTER_ADDRESSES##suffix *Next; \ 209 struct _IP_ADAPTER_ADDRESSES ## suffix *Next; \
210 _IP_ADAPTER_ADDRESSES_BASE \ 210 _IP_ADAPTER_ADDRESSES_BASE \
211 addition \ 211 addition \
212} IP_ADAPTER_ADDRESSES##suffix, *PIP_ADAPTER_ADDRESSES##suffix; 212 } IP_ADAPTER_ADDRESSES ## suffix, *PIP_ADAPTER_ADDRESSES ## suffix;
213 213
214 214
215/* _IP_ADAPTER_ADDRESSES_DEFINE(,) defined in w32api headers */ 215/* _IP_ADAPTER_ADDRESSES_DEFINE(,) defined in w32api headers */
216_IP_ADAPTER_ADDRESSES_DEFINE(_XPSP1,_IP_ADAPTER_ADDRESSES_ADD_XPSP1) 216_IP_ADAPTER_ADDRESSES_DEFINE(_XPSP1, _IP_ADAPTER_ADDRESSES_ADD_XPSP1)
217_IP_ADAPTER_ADDRESSES_DEFINE(_VISTA,_IP_ADAPTER_ADDRESSES_ADD_VISTA) 217_IP_ADAPTER_ADDRESSES_DEFINE(_VISTA, _IP_ADAPTER_ADDRESSES_ADD_VISTA)
218_IP_ADAPTER_ADDRESSES_DEFINE(_2008_OR_VISTASP1,_IP_ADAPTER_ADDRESSES_ADD_2008_OR_VISTASP1) 218_IP_ADAPTER_ADDRESSES_DEFINE(_2008_OR_VISTASP1, _IP_ADAPTER_ADDRESSES_ADD_2008_OR_VISTASP1)
219 219
220static int 220static int
221EnumNICs_IPv6_get_ifs_count (SOCKET s) 221EnumNICs_IPv6_get_ifs_count(SOCKET s)
222{ 222{
223 DWORD dwret = 0, err; 223 DWORD dwret = 0, err;
224 int iret; 224 int iret;
225 iret = WSAIoctl (s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0, 225
226 &dwret, NULL, NULL); 226 iret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, NULL, 0,
227 err = GetLastError (); 227 &dwret, NULL, NULL);
228 err = GetLastError();
228 if (iret == SOCKET_ERROR && err == WSAEFAULT) 229 if (iret == SOCKET_ERROR && err == WSAEFAULT)
229 return dwret; 230 return dwret;
230 else if (iret == 0) 231 else if (iret == 0)
@@ -233,71 +234,73 @@ EnumNICs_IPv6_get_ifs_count (SOCKET s)
233} 234}
234 235
235static int 236static int
236EnumNICs_IPv6_get_ifs (SOCKET s, SOCKET_ADDRESS_LIST *inf, int size) 237EnumNICs_IPv6_get_ifs(SOCKET s, SOCKET_ADDRESS_LIST *inf, int size)
237{ 238{
238 int iret; 239 int iret;
239 DWORD dwret = 0; 240 DWORD dwret = 0;
240 iret = WSAIoctl (s, SIO_ADDRESS_LIST_QUERY, NULL, 0, inf, size, 241
241 &dwret, NULL, NULL); 242 iret = WSAIoctl(s, SIO_ADDRESS_LIST_QUERY, NULL, 0, inf, size,
243 &dwret, NULL, NULL);
242 244
243 if (iret != 0 || dwret != size) 245 if (iret != 0 || dwret != size)
244 { 246 {
245 /* It's supposed to succeed! And size should be the same */ 247 /* It's supposed to succeed! And size should be the same */
246 return GNUNET_SYSERR; 248 return GNUNET_SYSERR;
247 } 249 }
248 return GNUNET_OK; 250 return GNUNET_OK;
249} 251}
250 252
251#undef GNUNET_malloc 253#undef GNUNET_malloc
252#define GNUNET_malloc(a) HeapAlloc(GetProcessHeap (), HEAP_ZERO_MEMORY | \ 254#define GNUNET_malloc(a) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY | \
253 HEAP_GENERATE_EXCEPTIONS, a) 255 HEAP_GENERATE_EXCEPTIONS, a)
254 256
255#undef GNUNET_free 257#undef GNUNET_free
256#define GNUNET_free(a) HeapFree(GetProcessHeap (), 0, a) 258#define GNUNET_free(a) HeapFree(GetProcessHeap(), 0, a)
257 259
258#undef GNUNET_free_non_null 260#undef GNUNET_free_non_null
259#define GNUNET_free_non_null(a) do { if ((a) != NULL) GNUNET_free(a); } while (0) 261#define GNUNET_free_non_null(a) do { if ((a) != NULL) GNUNET_free (a); } while (0)
260 262
261static int 263static int
262EnumNICs_IPv4_get_ifs (SOCKET s, INTERFACE_INFO **inf, int *size) 264EnumNICs_IPv4_get_ifs(SOCKET s, INTERFACE_INFO **inf, int *size)
263{ 265{
264 int iret; 266 int iret;
265 DWORD dwret = 0; 267 DWORD dwret = 0;
266 DWORD error; 268 DWORD error;
267 INTERFACE_INFO *ii = NULL; 269 INTERFACE_INFO *ii = NULL;
268 DWORD ii_size = sizeof (INTERFACE_INFO) * 15; 270 DWORD ii_size = sizeof(INTERFACE_INFO) * 15;
271
269 while (TRUE) 272 while (TRUE)
270 {
271 if (ii_size >= sizeof (INTERFACE_INFO) * 1000)
272 return GNUNET_SYSERR;
273 ii = (INTERFACE_INFO *) GNUNET_malloc (ii_size);
274 dwret = 0;
275 iret = WSAIoctl (s, SIO_GET_INTERFACE_LIST, NULL, 0, ii, ii_size,
276 &dwret, NULL, NULL);
277 error = GetLastError ();
278 if (iret == SOCKET_ERROR)
279 { 273 {
280 if (error == WSAEFAULT) 274 if (ii_size >= sizeof(INTERFACE_INFO) * 1000)
281 { 275 return GNUNET_SYSERR;
282 GNUNET_free (ii); 276 ii = (INTERFACE_INFO *)GNUNET_malloc(ii_size);
283 ii_size *= 2; 277 dwret = 0;
284 continue; 278 iret = WSAIoctl(s, SIO_GET_INTERFACE_LIST, NULL, 0, ii, ii_size,
285 } 279 &dwret, NULL, NULL);
286 GNUNET_free (ii); 280 error = GetLastError();
287 return GNUNET_SYSERR; 281 if (iret == SOCKET_ERROR)
288 } 282 {
289 else 283 if (error == WSAEFAULT)
290 { 284 {
291 *inf = ii; 285 GNUNET_free(ii);
292 *size = dwret; 286 ii_size *= 2;
293 return GNUNET_OK; 287 continue;
288 }
289 GNUNET_free(ii);
290 return GNUNET_SYSERR;
291 }
292 else
293 {
294 *inf = ii;
295 *size = dwret;
296 return GNUNET_OK;
297 }
294 } 298 }
295 }
296 return GNUNET_SYSERR; 299 return GNUNET_SYSERR;
297} 300}
298 301
299int 302int
300EnumNICs2 (INTERFACE_INFO **ifs4, int *ifs4_len, SOCKET_ADDRESS_LIST **ifs6) 303EnumNICs2(INTERFACE_INFO **ifs4, int *ifs4_len, SOCKET_ADDRESS_LIST **ifs6)
301{ 304{
302 int result = 0; 305 int result = 0;
303 SOCKET s4; 306 SOCKET s4;
@@ -307,49 +310,49 @@ EnumNICs2 (INTERFACE_INFO **ifs4, int *ifs4_len, SOCKET_ADDRESS_LIST **ifs6)
307 INTERFACE_INFO *interfaces4 = NULL; 310 INTERFACE_INFO *interfaces4 = NULL;
308 SOCKET_ADDRESS_LIST *interfaces6 = NULL; 311 SOCKET_ADDRESS_LIST *interfaces6 = NULL;
309 312
310 SetLastError (0); 313 SetLastError(0);
311 s4 = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); 314 s4 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
312 (void) GetLastError (); 315 (void)GetLastError();
313 SetLastError (0); 316 SetLastError(0);
314 s6 = socket (AF_INET6, SOCK_STREAM, IPPROTO_TCP); 317 s6 = socket(AF_INET6, SOCK_STREAM, IPPROTO_TCP);
315 (void) GetLastError (); 318 (void)GetLastError();
316 if (s6 != INVALID_SOCKET) 319 if (s6 != INVALID_SOCKET)
317 {
318 ifs6len = EnumNICs_IPv6_get_ifs_count (s6);
319 if (ifs6len > 0)
320 { 320 {
321 interfaces6 = (SOCKET_ADDRESS_LIST *) GNUNET_malloc (ifs6len); 321 ifs6len = EnumNICs_IPv6_get_ifs_count(s6);
322 result = EnumNICs_IPv6_get_ifs (s6, interfaces6, ifs6len) || result; 322 if (ifs6len > 0)
323 {
324 interfaces6 = (SOCKET_ADDRESS_LIST *)GNUNET_malloc(ifs6len);
325 result = EnumNICs_IPv6_get_ifs(s6, interfaces6, ifs6len) || result;
326 }
327 closesocket(s6);
328 s6 = INVALID_SOCKET;
323 } 329 }
324 closesocket (s6);
325 s6 = INVALID_SOCKET;
326 }
327 330
328 if (s4 != INVALID_SOCKET) 331 if (s4 != INVALID_SOCKET)
329 { 332 {
330 result = EnumNICs_IPv4_get_ifs (s4, &interfaces4, &ifs4len) || result; 333 result = EnumNICs_IPv4_get_ifs(s4, &interfaces4, &ifs4len) || result;
331 closesocket (s4); 334 closesocket(s4);
332 s4 = INVALID_SOCKET; 335 s4 = INVALID_SOCKET;
333 } 336 }
334 if (ifs6len + ifs4len == 0) 337 if (ifs6len + ifs4len == 0)
335 goto error; 338 goto error;
336 339
337 if (!result) 340 if (!result)
338 { 341 {
339 *ifs4 = interfaces4; 342 *ifs4 = interfaces4;
340 *ifs4_len = ifs4len; 343 *ifs4_len = ifs4len;
341 *ifs6 = interfaces6; 344 *ifs6 = interfaces6;
342 return GNUNET_OK; 345 return GNUNET_OK;
343 } 346 }
344error: 347error:
345 if (interfaces4 != NULL) 348 if (interfaces4 != NULL)
346 GNUNET_free (interfaces4); 349 GNUNET_free(interfaces4);
347 if (interfaces6 != NULL) 350 if (interfaces6 != NULL)
348 GNUNET_free (interfaces6); 351 GNUNET_free(interfaces6);
349 if (s4 != INVALID_SOCKET) 352 if (s4 != INVALID_SOCKET)
350 closesocket (s4); 353 closesocket(s4);
351 if (s6 != INVALID_SOCKET) 354 if (s6 != INVALID_SOCKET)
352 closesocket (s6); 355 closesocket(s6);
353 return GNUNET_SYSERR; 356 return GNUNET_SYSERR;
354} 357}
355 358
@@ -358,12 +361,12 @@ error:
358 * @returns #GNUNET_OK on success, #GNUNET_SYSERR on error 361 * @returns #GNUNET_OK on success, #GNUNET_SYSERR on error
359 */ 362 */
360int 363int
361EnumNICs3 (struct EnumNICs3_results **results, int *results_count) 364EnumNICs3(struct EnumNICs3_results **results, int *results_count)
362{ 365{
363 DWORD dwRetVal = 0; 366 DWORD dwRetVal = 0;
364 int count = 0; 367 int count = 0;
365 ULONG flags = /*GAA_FLAG_INCLUDE_PREFIX |*/ GAA_FLAG_SKIP_ANYCAST | 368 ULONG flags = /*GAA_FLAG_INCLUDE_PREFIX |*/ GAA_FLAG_SKIP_ANYCAST |
366 GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER; 369 GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER;
367 struct sockaddr_in6 examplecom6; 370 struct sockaddr_in6 examplecom6;
368 IPAddr examplecom; 371 IPAddr examplecom;
369 DWORD best_interface = 0; 372 DWORD best_interface = 0;
@@ -374,54 +377,54 @@ EnumNICs3 (struct EnumNICs3_results **results, int *results_count)
374 int interfaces4_len = 0; 377 int interfaces4_len = 0;
375 SOCKET_ADDRESS_LIST *interfaces6 = NULL; 378 SOCKET_ADDRESS_LIST *interfaces6 = NULL;
376 379
377 unsigned long outBufLen = sizeof (IP_ADAPTER_ADDRESSES); 380 unsigned long outBufLen = sizeof(IP_ADAPTER_ADDRESSES);
378 IP_ADAPTER_ADDRESSES *pCurrentAddress = NULL; 381 IP_ADAPTER_ADDRESSES *pCurrentAddress = NULL;
379 IP_ADAPTER_ADDRESSES *pAddresses = (IP_ADAPTER_ADDRESSES *) GNUNET_malloc (outBufLen); 382 IP_ADAPTER_ADDRESSES *pAddresses = (IP_ADAPTER_ADDRESSES *)GNUNET_malloc(outBufLen);
380 383
381 if (GetAdaptersAddresses (AF_UNSPEC, flags, NULL, pAddresses, &outBufLen) 384 if (GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAddresses, &outBufLen)
382 == ERROR_BUFFER_OVERFLOW) 385 == ERROR_BUFFER_OVERFLOW)
383 { 386 {
384 GNUNET_free (pAddresses); 387 GNUNET_free(pAddresses);
385 pAddresses = (IP_ADAPTER_ADDRESSES *) GNUNET_malloc (outBufLen); 388 pAddresses = (IP_ADAPTER_ADDRESSES *)GNUNET_malloc(outBufLen);
386 } 389 }
387 390
388 dwRetVal = GetAdaptersAddresses (AF_UNSPEC, flags, NULL, pAddresses, &outBufLen); 391 dwRetVal = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, pAddresses, &outBufLen);
389 392
390 if (dwRetVal != NO_ERROR) 393 if (dwRetVal != NO_ERROR)
391 {
392 GNUNET_free (pAddresses);
393 return GNUNET_SYSERR;
394 }
395
396 if (pAddresses->Length < sizeof (IP_ADAPTER_ADDRESSES_VISTA))
397 {
398 use_enum2 = 1;
399
400 /* Enumerate NICs using WSAIoctl() */
401 if (GNUNET_OK != EnumNICs2 (&interfaces4, &interfaces4_len, &interfaces6))
402 { 394 {
403 GNUNET_free (pAddresses); 395 GNUNET_free(pAddresses);
404 return GNUNET_SYSERR; 396 return GNUNET_SYSERR;
405 } 397 }
406 } 398
399 if (pAddresses->Length < sizeof(IP_ADAPTER_ADDRESSES_VISTA))
400 {
401 use_enum2 = 1;
402
403 /* Enumerate NICs using WSAIoctl() */
404 if (GNUNET_OK != EnumNICs2(&interfaces4, &interfaces4_len, &interfaces6))
405 {
406 GNUNET_free(pAddresses);
407 return GNUNET_SYSERR;
408 }
409 }
407 410
408 examplecom = inet_addr("192.0.34.166"); /* www.example.com */ 411 examplecom = inet_addr("192.0.34.166"); /* www.example.com */
409 if (GetBestInterface (examplecom, &best_interface) != NO_ERROR) 412 if (GetBestInterface(examplecom, &best_interface) != NO_ERROR)
410 best_interface = 0; 413 best_interface = 0;
411 414
412 if (GNGetBestInterfaceEx != NULL) 415 if (GNGetBestInterfaceEx != NULL)
413 { 416 {
414 examplecom6.sin6_family = AF_INET6; 417 examplecom6.sin6_family = AF_INET6;
415 examplecom6.sin6_port = 0; 418 examplecom6.sin6_port = 0;
416 examplecom6.sin6_flowinfo = 0; 419 examplecom6.sin6_flowinfo = 0;
417 examplecom6.sin6_scope_id = 0; 420 examplecom6.sin6_scope_id = 0;
418 inet_pton (AF_INET6, "2001:500:88:200:0:0:0:10", 421 inet_pton(AF_INET6, "2001:500:88:200:0:0:0:10",
419 (struct sockaddr *) &examplecom6.sin6_addr); 422 (struct sockaddr *)&examplecom6.sin6_addr);
420 dwRetVal = GNGetBestInterfaceEx ((struct sockaddr *) &examplecom6, 423 dwRetVal = GNGetBestInterfaceEx((struct sockaddr *)&examplecom6,
421 &best_interface6); 424 &best_interface6);
422 if (dwRetVal != NO_ERROR) 425 if (dwRetVal != NO_ERROR)
423 best_interface6 = 0; 426 best_interface6 = 0;
424 } 427 }
425 428
426 /* Give IPv6 a priority */ 429 /* Give IPv6 a priority */
427 if (best_interface6 != 0) 430 if (best_interface6 != 0)
@@ -429,200 +432,200 @@ EnumNICs3 (struct EnumNICs3_results **results, int *results_count)
429 432
430 count = 0; 433 count = 0;
431 for (pCurrentAddress = pAddresses; 434 for (pCurrentAddress = pAddresses;
432 pCurrentAddress != NULL; pCurrentAddress = pCurrentAddress->Next) 435 pCurrentAddress != NULL; pCurrentAddress = pCurrentAddress->Next)
433 {
434 if (pCurrentAddress->OperStatus == IfOperStatusUp)
435 { 436 {
436 IP_ADAPTER_UNICAST_ADDRESS *unicast = NULL; 437 if (pCurrentAddress->OperStatus == IfOperStatusUp)
437 for (unicast = pCurrentAddress->FirstUnicastAddress; unicast != NULL; 438 {
438 unicast = unicast->Next) 439 IP_ADAPTER_UNICAST_ADDRESS *unicast = NULL;
439 { 440 for (unicast = pCurrentAddress->FirstUnicastAddress; unicast != NULL;
440 if ((unicast->Address.lpSockaddr->sa_family == AF_INET || 441 unicast = unicast->Next)
441 unicast->Address.lpSockaddr->sa_family == AF_INET6) && 442 {
442 (unicast->DadState == IpDadStateDeprecated || 443 if ((unicast->Address.lpSockaddr->sa_family == AF_INET ||
443 unicast->DadState == IpDadStatePreferred)) 444 unicast->Address.lpSockaddr->sa_family == AF_INET6) &&
444 count += 1; 445 (unicast->DadState == IpDadStateDeprecated ||
445 } 446 unicast->DadState == IpDadStatePreferred))
447 count += 1;
448 }
449 }
446 } 450 }
447 }
448 451
449 if (count == 0) 452 if (count == 0)
450 { 453 {
451 *results = NULL; 454 *results = NULL;
452 *results_count = 0; 455 *results_count = 0;
453 GNUNET_free (pAddresses); 456 GNUNET_free(pAddresses);
454 GNUNET_free_non_null (interfaces4); 457 GNUNET_free_non_null(interfaces4);
455 GNUNET_free_non_null (interfaces6); 458 GNUNET_free_non_null(interfaces6);
456 return GNUNET_OK; 459 return GNUNET_OK;
457 } 460 }
458 461
459 *results = (struct EnumNICs3_results *) GNUNET_malloc ( 462 *results = (struct EnumNICs3_results *)GNUNET_malloc(
460 sizeof (struct EnumNICs3_results) * count); 463 sizeof(struct EnumNICs3_results) * count);
461 *results_count = count; 464 *results_count = count;
462 465
463 count = 0; 466 count = 0;
464 for (pCurrentAddress = pAddresses; 467 for (pCurrentAddress = pAddresses;
465 pCurrentAddress != NULL; pCurrentAddress = pCurrentAddress->Next) 468 pCurrentAddress != NULL; pCurrentAddress = pCurrentAddress->Next)
466 {
467 struct EnumNICs3_results *r;
468 IP_ADAPTER_UNICAST_ADDRESS *unicast = NULL;
469 if (pCurrentAddress->OperStatus != IfOperStatusUp)
470 continue;
471 for (unicast = pCurrentAddress->FirstUnicastAddress; unicast != NULL;
472 unicast = unicast->Next)
473 { 469 {
474 int i, j; 470 struct EnumNICs3_results *r;
475 int mask_length = -1; 471 IP_ADAPTER_UNICAST_ADDRESS *unicast = NULL;
476 char dst[INET6_ADDRSTRLEN + 1]; 472 if (pCurrentAddress->OperStatus != IfOperStatusUp)
477
478 if ((unicast->Address.lpSockaddr->sa_family != AF_INET &&
479 unicast->Address.lpSockaddr->sa_family != AF_INET6) ||
480 (unicast->DadState != IpDadStateDeprecated &&
481 unicast->DadState != IpDadStatePreferred))
482 continue; 473 continue;
483 474 for (unicast = pCurrentAddress->FirstUnicastAddress; unicast != NULL;
484 r = &(*results)[count]; 475 unicast = unicast->Next)
485 r->flags = 0;
486 if (pCurrentAddress->IfIndex > 0 &&
487 pCurrentAddress->IfIndex == best_interface &&
488 unicast->Address.lpSockaddr->sa_family == AF_INET)
489 r->is_default = 1;
490 else if (pCurrentAddress->Ipv6IfIndex > 0 &&
491 pCurrentAddress->Ipv6IfIndex == best_interface6 &&
492 unicast->Address.lpSockaddr->sa_family == AF_INET6)
493 r->is_default = 1;
494 else
495 r->is_default = 0;
496
497 /* Don't choose default interface twice */
498 if (r->is_default)
499 best_interface = best_interface6 = 0;
500
501 if (!use_enum2)
502 {
503 GNUNET_memcpy (&r->address, unicast->Address.lpSockaddr,
504 unicast->Address.iSockaddrLength);
505 memset (&r->mask, 0, sizeof (struct sockaddr));
506 mask_length = ((IP_ADAPTER_UNICAST_ADDRESS_VISTA *) unicast)->
507 OnLinkPrefixLength;
508 /* OnLinkPrefixLength is the number of leading 1s in the mask.
509 * OnLinkPrefixLength is available on Vista and later (hence use_enum2).
510 */
511 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
512 {
513 struct sockaddr_in *m = (struct sockaddr_in *) &r->mask;
514 for (i = 0; i < mask_length; i++)
515 ((unsigned char *) &m->sin_addr)[i / 8] |= 0x80 >> (i % 8);
516 }
517 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6)
518 {
519 struct sockaddr_in6 *m = (struct sockaddr_in6 *) &r->mask;
520 struct sockaddr_in6 *b = (struct sockaddr_in6 *) &r->broadcast;
521 for (i = 0; i < mask_length; i++)
522 ((unsigned char *) &m->sin6_addr)[i / 8] |= 0x80 >> (i % 8);
523 GNUNET_memcpy (&r->broadcast, &r->address, unicast->Address.iSockaddrLength);
524 for (i = mask_length; i < 128; i++)
525 ((unsigned char *) &b->sin6_addr)[i / 8] |= 0x80 >> (i % 8);
526 }
527 r->flags |= ENUMNICS3_MASK_OK;
528 }
529 else
530 {
531 int found = 0;
532 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
533 { 476 {
534 for (i = 0; !found && i < interfaces4_len / sizeof (INTERFACE_INFO); i++) 477 int i, j;
535 { 478 int mask_length = -1;
536 struct sockaddr_in *m = (struct sockaddr_in *) &r->mask; 479 char dst[INET6_ADDRSTRLEN + 1];
537 GNUNET_memcpy (&interfaces4[i].iiAddress.Address, 480
538 unicast->Address.lpSockaddr, 481 if ((unicast->Address.lpSockaddr->sa_family != AF_INET &&
539 unicast->Address.iSockaddrLength); 482 unicast->Address.lpSockaddr->sa_family != AF_INET6) ||
540 found = 1; 483 (unicast->DadState != IpDadStateDeprecated &&
541 GNUNET_memcpy (&r->address, &interfaces4[i].iiAddress.Address, 484 unicast->DadState != IpDadStatePreferred))
542 sizeof (struct sockaddr_in)); 485 continue;
543 GNUNET_memcpy (&r->mask, &interfaces4[i].iiNetmask.Address, 486
544 sizeof (struct sockaddr_in)); 487 r = &(*results)[count];
545 for (mask_length = 0; 488 r->flags = 0;
546 ((unsigned char *) &m->sin_addr)[mask_length / 8] & 489 if (pCurrentAddress->IfIndex > 0 &&
547 0x80 >> (mask_length % 8); mask_length++) 490 pCurrentAddress->IfIndex == best_interface &&
491 unicast->Address.lpSockaddr->sa_family == AF_INET)
492 r->is_default = 1;
493 else if (pCurrentAddress->Ipv6IfIndex > 0 &&
494 pCurrentAddress->Ipv6IfIndex == best_interface6 &&
495 unicast->Address.lpSockaddr->sa_family == AF_INET6)
496 r->is_default = 1;
497 else
498 r->is_default = 0;
499
500 /* Don't choose default interface twice */
501 if (r->is_default)
502 best_interface = best_interface6 = 0;
503
504 if (!use_enum2)
548 { 505 {
506 GNUNET_memcpy(&r->address, unicast->Address.lpSockaddr,
507 unicast->Address.iSockaddrLength);
508 memset(&r->mask, 0, sizeof(struct sockaddr));
509 mask_length = ((IP_ADAPTER_UNICAST_ADDRESS_VISTA *)unicast)->
510 OnLinkPrefixLength;
511 /* OnLinkPrefixLength is the number of leading 1s in the mask.
512 * OnLinkPrefixLength is available on Vista and later (hence use_enum2).
513 */
514 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
515 {
516 struct sockaddr_in *m = (struct sockaddr_in *)&r->mask;
517 for (i = 0; i < mask_length; i++)
518 ((unsigned char *)&m->sin_addr)[i / 8] |= 0x80 >> (i % 8);
519 }
520 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6)
521 {
522 struct sockaddr_in6 *m = (struct sockaddr_in6 *)&r->mask;
523 struct sockaddr_in6 *b = (struct sockaddr_in6 *)&r->broadcast;
524 for (i = 0; i < mask_length; i++)
525 ((unsigned char *)&m->sin6_addr)[i / 8] |= 0x80 >> (i % 8);
526 GNUNET_memcpy(&r->broadcast, &r->address, unicast->Address.iSockaddrLength);
527 for (i = mask_length; i < 128; i++)
528 ((unsigned char *)&b->sin6_addr)[i / 8] |= 0x80 >> (i % 8);
529 }
530 r->flags |= ENUMNICS3_MASK_OK;
549 } 531 }
550 r->flags |= ENUMNICS3_MASK_OK; 532 else
551 } 533 {
552 } 534 int found = 0;
553 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6) 535 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
554 { 536 {
555 for (i = 0; 537 for (i = 0; !found && i < interfaces4_len / sizeof(INTERFACE_INFO); i++)
556 interfaces6 != NULL && !found && i < interfaces6->iAddressCount; 538 {
557 i++) 539 struct sockaddr_in *m = (struct sockaddr_in *)&r->mask;
558 { 540 GNUNET_memcpy(&interfaces4[i].iiAddress.Address,
559 GNUNET_memcpy (interfaces6->Address[i].lpSockaddr, 541 unicast->Address.lpSockaddr,
560 unicast->Address.lpSockaddr, 542 unicast->Address.iSockaddrLength);
561 unicast->Address.iSockaddrLength); 543 found = 1;
562 found = 1; 544 GNUNET_memcpy(&r->address, &interfaces4[i].iiAddress.Address,
563 GNUNET_memcpy (&r->address, interfaces6->Address[i].lpSockaddr, 545 sizeof(struct sockaddr_in));
564 sizeof (struct sockaddr_in6)); 546 GNUNET_memcpy(&r->mask, &interfaces4[i].iiNetmask.Address,
565 /* TODO: Find a way to reliably get network mask for IPv6 on XP */ 547 sizeof(struct sockaddr_in));
566 memset (&r->mask, 0, sizeof (struct sockaddr)); 548 for (mask_length = 0;
567 r->flags &= ~ENUMNICS3_MASK_OK; 549 ((unsigned char *)&m->sin_addr)[mask_length / 8] &
568 } 550 0x80 >> (mask_length % 8); mask_length++)
569 } 551 {
570 if (!found) 552 }
571 { 553 r->flags |= ENUMNICS3_MASK_OK;
572 DebugBreak (); 554 }
555 }
556 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6)
557 {
558 for (i = 0;
559 interfaces6 != NULL && !found && i < interfaces6->iAddressCount;
560 i++)
561 {
562 GNUNET_memcpy(interfaces6->Address[i].lpSockaddr,
563 unicast->Address.lpSockaddr,
564 unicast->Address.iSockaddrLength);
565 found = 1;
566 GNUNET_memcpy(&r->address, interfaces6->Address[i].lpSockaddr,
567 sizeof(struct sockaddr_in6));
568 /* TODO: Find a way to reliably get network mask for IPv6 on XP */
569 memset(&r->mask, 0, sizeof(struct sockaddr));
570 r->flags &= ~ENUMNICS3_MASK_OK;
571 }
572 }
573 if (!found)
574 {
575 DebugBreak();
576 }
577 }
578 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
579 {
580 struct sockaddr_in *m = (struct sockaddr_in *)&r->mask;
581 struct sockaddr_in *a = (struct sockaddr_in *)&r->address;
582 /* copy address to broadcast, then flip all the trailing bits not
583 * falling under netmask to 1,
584 * so we get, 192.168.0.255 from, say, 192.168.0.43 with mask == 24.
585 */
586 GNUNET_memcpy(&r->broadcast, &r->address, unicast->Address.iSockaddrLength);
587 for (i = mask_length; i < 32; i++)
588 ((unsigned char *)&m->sin_addr)[i / 8] |= 0x80 >> (i % 8);
589 r->flags |= ENUMNICS3_BCAST_OK;
590 r->addr_size = sizeof(struct sockaddr_in);
591 inet_ntop(AF_INET, &a->sin_addr, dst, INET_ADDRSTRLEN);
592 }
593 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6)
594 {
595 struct sockaddr_in6 *a = (struct sockaddr_in6 *)&r->address;
596 /* for IPv6 broadcast is not defined, zero it down */
597 memset(&r->broadcast, 0, sizeof(struct sockaddr));
598 r->flags &= ~ENUMNICS3_BCAST_OK;
599 r->addr_size = sizeof(struct sockaddr_in6);
600 inet_ntop(AF_INET6, &a->sin6_addr, dst, INET6_ADDRSTRLEN);
601 }
602
603 i = 0;
604 i += snprintf(&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0,
605 "%S (%s", pCurrentAddress->FriendlyName, dst);
606 for (j = 0; j < pCurrentAddress->PhysicalAddressLength; j++)
607 i += snprintf(&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0,
608 "%s%02X", j > 0 ? ":" : " - ", pCurrentAddress->PhysicalAddress[j]);
609 i += snprintf(&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0, ")");
610 r->pretty_name[1000] = '\0';
611 count += 1;
573 } 612 }
574 }
575 if (unicast->Address.lpSockaddr->sa_family == AF_INET)
576 {
577 struct sockaddr_in *m = (struct sockaddr_in *) &r->mask;
578 struct sockaddr_in *a = (struct sockaddr_in *) &r->address;
579 /* copy address to broadcast, then flip all the trailing bits not
580 * falling under netmask to 1,
581 * so we get, 192.168.0.255 from, say, 192.168.0.43 with mask == 24.
582 */
583 GNUNET_memcpy (&r->broadcast, &r->address, unicast->Address.iSockaddrLength);
584 for (i = mask_length; i < 32; i++)
585 ((unsigned char *) &m->sin_addr)[i / 8] |= 0x80 >> (i % 8);
586 r->flags |= ENUMNICS3_BCAST_OK;
587 r->addr_size = sizeof (struct sockaddr_in);
588 inet_ntop (AF_INET, &a->sin_addr, dst, INET_ADDRSTRLEN);
589 }
590 else if (unicast->Address.lpSockaddr->sa_family == AF_INET6)
591 {
592 struct sockaddr_in6 *a = (struct sockaddr_in6 *) &r->address;
593 /* for IPv6 broadcast is not defined, zero it down */
594 memset (&r->broadcast, 0, sizeof (struct sockaddr));
595 r->flags &= ~ENUMNICS3_BCAST_OK;
596 r->addr_size = sizeof (struct sockaddr_in6);
597 inet_ntop (AF_INET6, &a->sin6_addr, dst, INET6_ADDRSTRLEN);
598 }
599
600 i = 0;
601 i += snprintf (&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0,
602 "%S (%s", pCurrentAddress->FriendlyName, dst);
603 for (j = 0; j < pCurrentAddress->PhysicalAddressLength; j++)
604 i += snprintf (&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0,
605 "%s%02X",j > 0 ? ":" : " - ", pCurrentAddress->PhysicalAddress[j]);
606 i += snprintf (&r->pretty_name[i], 1000 - i > 0 ? 1000 - i : 0, ")");
607 r->pretty_name[1000] = '\0';
608 count += 1;
609 } 613 }
610 }
611 614
612 if (use_enum2) 615 if (use_enum2)
613 { 616 {
614 GNUNET_free_non_null (interfaces4); 617 GNUNET_free_non_null(interfaces4);
615 GNUNET_free_non_null (interfaces6); 618 GNUNET_free_non_null(interfaces6);
616 } 619 }
617 620
618 GNUNET_free (pAddresses); 621 GNUNET_free(pAddresses);
619 return GNUNET_OK; 622 return GNUNET_OK;
620} 623}
621 624
622void 625void
623EnumNICs3_free (struct EnumNICs3_results *r) 626EnumNICs3_free(struct EnumNICs3_results *r)
624{ 627{
625 GNUNET_free_non_null (r); 628 GNUNET_free_non_null(r);
626} 629}
627 630
628 631
@@ -634,20 +637,20 @@ EnumNICs3_free (struct EnumNICs3_results *r)
634 * @param callback_cls closure for callback 637 * @param callback_cls closure for callback
635 */ 638 */
636int 639int
637ListNICs (void (*callback) (void *, const char *, int), void * callback_cls) 640ListNICs(void (*callback)(void *, const char *, int), void * callback_cls)
638{ 641{
639 int r; 642 int r;
640 int i; 643 int i;
641 struct EnumNICs3_results *results = NULL; 644 struct EnumNICs3_results *results = NULL;
642 int results_count; 645 int results_count;
643 646
644 r = EnumNICs3 (&results, &results_count); 647 r = EnumNICs3(&results, &results_count);
645 if (r != GNUNET_OK) 648 if (r != GNUNET_OK)
646 return GNUNET_NO; 649 return GNUNET_NO;
647 650
648 for (i = 0; i < results_count; i++) 651 for (i = 0; i < results_count; i++)
649 callback (callback_cls, results[i].pretty_name, results[i].is_default); 652 callback(callback_cls, results[i].pretty_name, results[i].is_default);
650 GNUNET_free_non_null (results); 653 GNUNET_free_non_null(results);
651 return GNUNET_YES; 654 return GNUNET_YES;
652} 655}
653 656
@@ -667,29 +670,29 @@ int InstallAsService(char *servicename, char *application, char *username)
667 char szEXE[_MAX_PATH + 17] = "\""; 670 char szEXE[_MAX_PATH + 17] = "\"";
668 char *user = NULL; 671 char *user = NULL;
669 672
670 if (! GNOpenSCManager) 673 if (!GNOpenSCManager)
671 return 1; 674 return 1;
672 675
673 plibc_conv_to_win_path(application, szEXE + 1); 676 plibc_conv_to_win_path(application, szEXE + 1);
674 strcat(szEXE, "\" --win-service"); 677 strcat(szEXE, "\" --win-service");
675 hManager = GNOpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE); 678 hManager = GNOpenSCManager(NULL, NULL, SC_MANAGER_CREATE_SERVICE);
676 if (! hManager) 679 if (!hManager)
677 return 2; 680 return 2;
678 681
679 if (username) 682 if (username)
680 { 683 {
681 user = (char *) malloc(strlen(username) + 3); 684 user = (char *)malloc(strlen(username) + 3);
682 sprintf(user, ".\\%s", username); 685 sprintf(user, ".\\%s", username);
683 } 686 }
684 687
685 hService = GNCreateService(hManager, (LPCTSTR) servicename, (LPCTSTR) servicename, 0, 688 hService = GNCreateService(hManager, (LPCTSTR)servicename, (LPCTSTR)servicename, 0,
686 SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, (LPCTSTR) szEXE, 689 SERVICE_WIN32_OWN_PROCESS, SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, (LPCTSTR)szEXE,
687 NULL, NULL, NULL, (LPCTSTR) user, (LPCTSTR) username); 690 NULL, NULL, NULL, (LPCTSTR)user, (LPCTSTR)username);
688 691
689 if (user) 692 if (user)
690 free(user); 693 free(user);
691 694
692 if (! hService) 695 if (!hService)
693 return 3; 696 return 3;
694 697
695 GNCloseServiceHandle(hService); 698 GNCloseServiceHandle(hService);
@@ -712,22 +715,22 @@ UninstallService(char *servicename)
712{ 715{
713 SC_HANDLE hManager, hService; 716 SC_HANDLE hManager, hService;
714 717
715 if (! GNOpenSCManager) 718 if (!GNOpenSCManager)
716 return 1; 719 return 1;
717 720
718 hManager = GNOpenSCManager(NULL, NULL, SC_MANAGER_CONNECT); 721 hManager = GNOpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
719 if (! hManager) 722 if (!hManager)
720 return 2; 723 return 2;
721 724
722 if (! (hService = GNOpenService(hManager, (LPCTSTR) servicename, DELETE))) 725 if (!(hService = GNOpenService(hManager, (LPCTSTR)servicename, DELETE)))
723 { 726 {
724 if (GetLastError() != ERROR_SERVICE_DOES_NOT_EXIST) 727 if (GetLastError() != ERROR_SERVICE_DOES_NOT_EXIST)
725 return 3; 728 return 3;
726 else 729 else
727 goto closeSCM; 730 goto closeSCM;
728 } 731 }
729 732
730 if (! GNDeleteService(hService)) 733 if (!GNDeleteService(hService))
731 if (GetLastError() != ERROR_SERVICE_MARKED_FOR_DELETE) 734 if (GetLastError() != ERROR_SERVICE_MARKED_FOR_DELETE)
732 return 4; 735 return 4;
733 736
@@ -747,18 +750,18 @@ _InitLsaString(PLSA_UNICODE_STRING LsaString, LPWSTR String)
747{ 750{
748 DWORD StringLength; 751 DWORD StringLength;
749 752
750 if(String == NULL) 753 if (String == NULL)
751 { 754 {
752 LsaString->Buffer = NULL; 755 LsaString->Buffer = NULL;
753 LsaString->Length = 0; 756 LsaString->Length = 0;
754 LsaString->MaximumLength = 0; 757 LsaString->MaximumLength = 0;
755 return; 758 return;
756 } 759 }
757 760
758 StringLength = wcslen(String); 761 StringLength = wcslen(String);
759 LsaString->Buffer = String; 762 LsaString->Buffer = String;
760 LsaString->Length = (USHORT) StringLength *sizeof(WCHAR); 763 LsaString->Length = (USHORT)StringLength * sizeof(WCHAR);
761 LsaString->MaximumLength = (USHORT) (StringLength + 1) * sizeof(WCHAR); 764 LsaString->MaximumLength = (USHORT)(StringLength + 1) * sizeof(WCHAR);
762} 765}
763 766
764 767
@@ -777,16 +780,16 @@ _OpenPolicy(LPWSTR ServerName, DWORD DesiredAccess, PLSA_HANDLE PolicyHandle)
777 /* Always initialize the object attributes to all zeroes. */ 780 /* Always initialize the object attributes to all zeroes. */
778 ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes)); 781 ZeroMemory(&ObjectAttributes, sizeof(ObjectAttributes));
779 782
780 if(ServerName != NULL) 783 if (ServerName != NULL)
781 { 784 {
782 /* Make a LSA_UNICODE_STRING out of the LPWSTR passed in */ 785 /* Make a LSA_UNICODE_STRING out of the LPWSTR passed in */
783 _InitLsaString(&ServerString, ServerName); 786 _InitLsaString(&ServerString, ServerName);
784 Server = &ServerString; 787 Server = &ServerString;
785 } 788 }
786 789
787 /* Attempt to open the policy. */ 790 /* Attempt to open the policy. */
788 return GNLsaOpenPolicy(Server, 791 return GNLsaOpenPolicy(Server,
789 &ObjectAttributes, DesiredAccess, PolicyHandle); 792 &ObjectAttributes, DesiredAccess, PolicyHandle);
790} 793}
791 794
792/** 795/**
@@ -805,61 +808,61 @@ BOOL
805_GetAccountSid(LPCTSTR SystemName, LPCTSTR AccountName, PSID * Sid) 808_GetAccountSid(LPCTSTR SystemName, LPCTSTR AccountName, PSID * Sid)
806{ 809{
807 LPTSTR ReferencedDomain = NULL; 810 LPTSTR ReferencedDomain = NULL;
808 DWORD cbSid = 128; /* initial allocation attempt */ 811 DWORD cbSid = 128; /* initial allocation attempt */
809 DWORD cchReferencedDomain = 16; /* initial allocation size */ 812 DWORD cchReferencedDomain = 16; /* initial allocation size */
810 SID_NAME_USE peUse; 813 SID_NAME_USE peUse;
811 BOOL bSuccess = FALSE; /* assume this function will fail */ 814 BOOL bSuccess = FALSE; /* assume this function will fail */
812 815
813 /* initial memory allocations */ 816 /* initial memory allocations */
814 if ((*Sid = HeapAlloc (GetProcessHeap (), 0, cbSid)) == NULL) 817 if ((*Sid = HeapAlloc(GetProcessHeap(), 0, cbSid)) == NULL)
815 return FALSE; 818 return FALSE;
816 819
817 if ((ReferencedDomain = (LPTSTR) HeapAlloc (GetProcessHeap (), 820 if ((ReferencedDomain = (LPTSTR)HeapAlloc(GetProcessHeap(),
818 0, 821 0,
819 cchReferencedDomain * 822 cchReferencedDomain *
820 sizeof (TCHAR))) == NULL) 823 sizeof(TCHAR))) == NULL)
821 return FALSE; 824 return FALSE;
822 825
823 /* Obtain the SID of the specified account on the specified system. */ 826 /* Obtain the SID of the specified account on the specified system. */
824 while (!GNLookupAccountName(SystemName, /* machine to lookup account on */ 827 while (!GNLookupAccountName(SystemName, /* machine to lookup account on */
825 AccountName, /* account to lookup */ 828 AccountName, /* account to lookup */
826 *Sid, /* SID of interest */ 829 *Sid, /* SID of interest */
827 &cbSid, /* size of SID */ 830 &cbSid, /* size of SID */
828 ReferencedDomain, /* domain account was found on */ 831 ReferencedDomain, /* domain account was found on */
829 &cchReferencedDomain, &peUse)) 832 &cchReferencedDomain, &peUse))
830 { 833 {
831 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER) 834 if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
832 { 835 {
833 /* reallocate memory */ 836 /* reallocate memory */
834 if ((*Sid = HeapReAlloc (GetProcessHeap (), 0, *Sid, cbSid)) == NULL) 837 if ((*Sid = HeapReAlloc(GetProcessHeap(), 0, *Sid, cbSid)) == NULL)
835 return FALSE; 838 return FALSE;
836 839
837 if ((ReferencedDomain = (LPTSTR) HeapReAlloc (GetProcessHeap (), 840 if ((ReferencedDomain = (LPTSTR)HeapReAlloc(GetProcessHeap(),
838 0, 841 0,
839 ReferencedDomain, 842 ReferencedDomain,
840 cchReferencedDomain 843 cchReferencedDomain
841 * sizeof (TCHAR))) == NULL) 844 * sizeof(TCHAR))) == NULL)
842 return FALSE; 845 return FALSE;
843 } 846 }
844 else 847 else
845 goto end; 848 goto end;
846 } 849 }
847 850
848 /* Indicate success. */ 851 /* Indicate success. */
849 bSuccess = TRUE; 852 bSuccess = TRUE;
850 853
851end: 854end:
852 /* Cleanup and indicate failure, if appropriate. */ 855 /* Cleanup and indicate failure, if appropriate. */
853 HeapFree (GetProcessHeap (), 0, ReferencedDomain); 856 HeapFree(GetProcessHeap(), 0, ReferencedDomain);
854 857
855 if (!bSuccess) 858 if (!bSuccess)
856 {
857 if (*Sid != NULL)
858 { 859 {
859 HeapFree (GetProcessHeap (), 0, *Sid); 860 if (*Sid != NULL)
860 *Sid = NULL; 861 {
862 HeapFree(GetProcessHeap(), 0, *Sid);
863 *Sid = NULL;
864 }
861 } 865 }
862 }
863 866
864 return bSuccess; 867 return bSuccess;
865} 868}
@@ -871,10 +874,10 @@ end:
871 */ 874 */
872NTSTATUS 875NTSTATUS
873_SetPrivilegeOnAccount(LSA_HANDLE PolicyHandle,/* open policy handle */ 876_SetPrivilegeOnAccount(LSA_HANDLE PolicyHandle,/* open policy handle */
874 PSID AccountSid, /* SID to grant privilege to */ 877 PSID AccountSid, /* SID to grant privilege to */
875 LPWSTR PrivilegeName, /* privilege to grant (Unicode) */ 878 LPWSTR PrivilegeName, /* privilege to grant (Unicode) */
876 BOOL bEnable /* enable or disable */ 879 BOOL bEnable /* enable or disable */
877 ) 880 )
878{ 881{
879 LSA_UNICODE_STRING PrivilegeString; 882 LSA_UNICODE_STRING PrivilegeString;
880 883
@@ -882,26 +885,26 @@ _SetPrivilegeOnAccount(LSA_HANDLE PolicyHandle,/* open policy handle */
882 _InitLsaString(&PrivilegeString, PrivilegeName); 885 _InitLsaString(&PrivilegeString, PrivilegeName);
883 886
884 /* grant or revoke the privilege, accordingly */ 887 /* grant or revoke the privilege, accordingly */
885 if(bEnable) 888 if (bEnable)
886 { 889 {
887 NTSTATUS i; 890 NTSTATUS i;
888 891
889 i = GNLsaAddAccountRights(PolicyHandle, /* open policy handle */ 892 i = GNLsaAddAccountRights(PolicyHandle, /* open policy handle */
890 AccountSid, /* target SID */ 893 AccountSid, /* target SID */
891 &PrivilegeString, /* privileges */ 894 &PrivilegeString, /* privileges */
892 1 /* privilege count */ 895 1 /* privilege count */
893 ); 896 );
894 return i; 897 return i;
895 } 898 }
896 else 899 else
897 { 900 {
898 return GNLsaRemoveAccountRights(PolicyHandle, /* open policy handle */ 901 return GNLsaRemoveAccountRights(PolicyHandle, /* open policy handle */
899 AccountSid, /* target SID */ 902 AccountSid, /* target SID */
900 FALSE, /* do not disable all rights */ 903 FALSE, /* do not disable all rights */
901 &PrivilegeString, /* privileges */ 904 &PrivilegeString, /* privileges */
902 1 /* privilege count */ 905 1 /* privilege count */
903 ); 906 );
904 } 907 }
905} 908}
906 909
907/** 910/**
@@ -921,8 +924,8 @@ CreateServiceAccount(const char *pszName,
921 LSA_HANDLE hPolicy; 924 LSA_HANDLE hPolicy;
922 PSID pSID; 925 PSID pSID;
923 926
924 if (! GNNetUserAdd) 927 if (!GNNetUserAdd)
925 return 1; 928 return 1;
926 mbstowcs(wszName, pszName, strlen(pszName) + 1); 929 mbstowcs(wszName, pszName, strlen(pszName) + 1);
927 mbstowcs(wszDesc, pszDesc, strlen(pszDesc) + 1); 930 mbstowcs(wszDesc, pszDesc, strlen(pszDesc) + 1);
928 931
@@ -936,22 +939,22 @@ CreateServiceAccount(const char *pszName,
936 nStatus = GNNetUserAdd(NULL, 1, (LPBYTE)&ui, NULL); 939 nStatus = GNNetUserAdd(NULL, 1, (LPBYTE)&ui, NULL);
937 940
938 if (nStatus != NERR_Success && nStatus != NERR_UserExists) 941 if (nStatus != NERR_Success && nStatus != NERR_UserExists)
939 return 2; 942 return 2;
940 943
941 ui2.usri1008_flags = UF_PASSWD_CANT_CHANGE | UF_DONT_EXPIRE_PASSWD; 944 ui2.usri1008_flags = UF_PASSWD_CANT_CHANGE | UF_DONT_EXPIRE_PASSWD;
942 GNNetUserSetInfo(NULL, wszName, 1008, (LPBYTE)&ui2, NULL); 945 GNNetUserSetInfo(NULL, wszName, 1008, (LPBYTE)&ui2, NULL);
943 946
944 if (!NT_SUCCESS(_OpenPolicy(NULL, POLICY_ALL_ACCESS, &hPolicy))) 947 if (!NT_SUCCESS(_OpenPolicy(NULL, POLICY_ALL_ACCESS, &hPolicy)))
945 return 3; 948 return 3;
946 949
947 _GetAccountSid(NULL, (LPCTSTR) pszName, &pSID); 950 _GetAccountSid(NULL, (LPCTSTR)pszName, &pSID);
948 951
949 if (!NT_SUCCESS(_SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR) L"SeServiceLogonRight", TRUE))) 952 if (!NT_SUCCESS(_SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR)L"SeServiceLogonRight", TRUE)))
950 return 4; 953 return 4;
951 954
952 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR) L"SeDenyInteractiveLogonRight", TRUE); 955 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR)L"SeDenyInteractiveLogonRight", TRUE);
953 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR) L"SeDenyBatchLogonRight", TRUE); 956 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR)L"SeDenyBatchLogonRight", TRUE);
954 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR) L"SeDenyNetworkLogonRight", TRUE); 957 _SetPrivilegeOnAccount(hPolicy, pSID, (LPWSTR)L"SeDenyNetworkLogonRight", TRUE);
955 958
956 GNLsaClose(hPolicy); 959 GNLsaClose(hPolicy);
957 960
@@ -967,113 +970,122 @@ CreateServiceAccount(const char *pszName,
967 * @remark based on http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q102102& 970 * @remark based on http://support.microsoft.com/default.aspx?scid=KB;EN-US;Q102102&
968 */ 971 */
969BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName, 972BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
970 DWORD dwAccessMask) 973 DWORD dwAccessMask)
971{ 974{
972 /* SID variables. */ 975 /* SID variables. */
973 SID_NAME_USE snuType; 976 SID_NAME_USE snuType;
974 TCHAR * szDomain = NULL; 977 TCHAR * szDomain = NULL;
975 DWORD cbDomain = 0; 978 DWORD cbDomain = 0;
976 LPVOID pUserSID = NULL; 979 LPVOID pUserSID = NULL;
977 DWORD cbUserSID = 0; 980 DWORD cbUserSID = 0;
978 981
979 /* File SD variables. */ 982 /* File SD variables. */
980 PSECURITY_DESCRIPTOR pFileSD = NULL; 983 PSECURITY_DESCRIPTOR pFileSD = NULL;
981 DWORD cbFileSD = 0; 984 DWORD cbFileSD = 0;
982 985
983 /* New SD variables. */ 986 /* New SD variables. */
984 SECURITY_DESCRIPTOR newSD; 987 SECURITY_DESCRIPTOR newSD;
985 988
986 /* ACL variables. */ 989 /* ACL variables. */
987 PACL pACL = NULL; 990 PACL pACL = NULL;
988 BOOL fDaclPresent; 991 BOOL fDaclPresent;
989 BOOL fDaclDefaulted; 992 BOOL fDaclDefaulted;
990 ACL_SIZE_INFORMATION AclInfo; 993 ACL_SIZE_INFORMATION AclInfo;
991 994
992 /* New ACL variables. */ 995 /* New ACL variables. */
993 PACL pNewACL = NULL; 996 PACL pNewACL = NULL;
994 DWORD cbNewACL = 0; 997 DWORD cbNewACL = 0;
995 998
996 /* Temporary ACE. */ 999 /* Temporary ACE. */
997 LPVOID pTempAce = NULL; 1000 LPVOID pTempAce = NULL;
998 UINT CurrentAceIndex = 0; 1001 UINT CurrentAceIndex = 0;
999 1002
1000 UINT newAceIndex = 0; 1003 UINT newAceIndex = 0;
1001 1004
1002 /* Assume function will fail. */ 1005 /* Assume function will fail. */
1003 BOOL fResult = FALSE; 1006 BOOL fResult = FALSE;
1004 BOOL fAPISuccess; 1007 BOOL fAPISuccess;
1005 1008
1006 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION; 1009 SECURITY_INFORMATION secInfo = DACL_SECURITY_INFORMATION;
1007 1010
1008 /** 1011 /**
1009 * STEP 1: Get SID of the account name specified. 1012 * STEP 1: Get SID of the account name specified.
1010 */ 1013 */
1011 fAPISuccess = GNLookupAccountName(NULL, (LPCTSTR) lpszAccountName, 1014 fAPISuccess = GNLookupAccountName(NULL, (LPCTSTR)lpszAccountName,
1012 pUserSID, &cbUserSID, (LPTSTR) szDomain, &cbDomain, &snuType); 1015 pUserSID, &cbUserSID, (LPTSTR)szDomain, &cbDomain, &snuType);
1013 1016
1014 /* API should have failed with insufficient buffer. */ 1017 /* API should have failed with insufficient buffer. */
1015 if (fAPISuccess) 1018 if (fAPISuccess)
1016 goto end; 1019 goto end;
1017 else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { 1020 else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1018 goto end; 1021 {
1019 } 1022 goto end;
1023 }
1020 1024
1021 pUserSID = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbUserSID); 1025 pUserSID = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbUserSID);
1022 if (!pUserSID) { 1026 if (!pUserSID)
1023 goto end; 1027 {
1024 } 1028 goto end;
1029 }
1025 1030
1026 szDomain = (TCHAR *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbDomain * sizeof(TCHAR)); 1031 szDomain = (TCHAR *)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbDomain * sizeof(TCHAR));
1027 if (!szDomain) { 1032 if (!szDomain)
1028 goto end; 1033 {
1029 } 1034 goto end;
1035 }
1030 1036
1031 fAPISuccess = GNLookupAccountName(NULL, (LPCTSTR) lpszAccountName, 1037 fAPISuccess = GNLookupAccountName(NULL, (LPCTSTR)lpszAccountName,
1032 pUserSID, &cbUserSID, (LPTSTR) szDomain, &cbDomain, &snuType); 1038 pUserSID, &cbUserSID, (LPTSTR)szDomain, &cbDomain, &snuType);
1033 if (!fAPISuccess) { 1039 if (!fAPISuccess)
1034 goto end; 1040 {
1035 } 1041 goto end;
1042 }
1036 1043
1037 /** 1044 /**
1038 * STEP 2: Get security descriptor (SD) of the file specified. 1045 * STEP 2: Get security descriptor (SD) of the file specified.
1039 */ 1046 */
1040 fAPISuccess = GNGetFileSecurity((LPCTSTR) lpszFileName, 1047 fAPISuccess = GNGetFileSecurity((LPCTSTR)lpszFileName,
1041 secInfo, pFileSD, 0, &cbFileSD); 1048 secInfo, pFileSD, 0, &cbFileSD);
1042 1049
1043 /* API should have failed with insufficient buffer. */ 1050 /* API should have failed with insufficient buffer. */
1044 if (fAPISuccess) 1051 if (fAPISuccess)
1045 goto end; 1052 goto end;
1046 else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) { 1053 else if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1047 goto end; 1054 {
1048 } 1055 goto end;
1049 1056 }
1050 pFileSD = (PSECURITY_DESCRIPTOR) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, 1057
1051 cbFileSD); 1058 pFileSD = (PSECURITY_DESCRIPTOR)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,
1052 if (!pFileSD) { 1059 cbFileSD);
1053 goto end; 1060 if (!pFileSD)
1054 } 1061 {
1055 1062 goto end;
1056 fAPISuccess = GNGetFileSecurity((LPCTSTR) lpszFileName, 1063 }
1057 secInfo, pFileSD, cbFileSD, &cbFileSD); 1064
1058 if (!fAPISuccess) { 1065 fAPISuccess = GNGetFileSecurity((LPCTSTR)lpszFileName,
1059 goto end; 1066 secInfo, pFileSD, cbFileSD, &cbFileSD);
1060 } 1067 if (!fAPISuccess)
1068 {
1069 goto end;
1070 }
1061 1071
1062 /** 1072 /**
1063 * STEP 3: Initialize new SD. 1073 * STEP 3: Initialize new SD.
1064 */ 1074 */
1065 if (!GNInitializeSecurityDescriptor(&newSD, 1075 if (!GNInitializeSecurityDescriptor(&newSD,
1066 SECURITY_DESCRIPTOR_REVISION)) { 1076 SECURITY_DESCRIPTOR_REVISION))
1067 goto end; 1077 {
1068 } 1078 goto end;
1079 }
1069 1080
1070 /** 1081 /**
1071 * STEP 4: Get DACL from the old SD. 1082 * STEP 4: Get DACL from the old SD.
1072 */ 1083 */
1073 if (!GNGetSecurityDescriptorDacl(pFileSD, &fDaclPresent, &pACL, 1084 if (!GNGetSecurityDescriptorDacl(pFileSD, &fDaclPresent, &pACL,
1074 &fDaclDefaulted)) { 1085 &fDaclDefaulted))
1075 goto end; 1086 {
1076 } 1087 goto end;
1088 }
1077 1089
1078 /** 1090 /**
1079 * STEP 5: Get size information for DACL. 1091 * STEP 5: Get size information for DACL.
@@ -1083,37 +1095,40 @@ BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
1083 AclInfo.AclBytesInUse = sizeof(ACL); 1095 AclInfo.AclBytesInUse = sizeof(ACL);
1084 1096
1085 if (pACL == NULL) 1097 if (pACL == NULL)
1086 fDaclPresent = FALSE; 1098 fDaclPresent = FALSE;
1087 1099
1088 /* If not NULL DACL, gather size information from DACL. */ 1100 /* If not NULL DACL, gather size information from DACL. */
1089 if (fDaclPresent) { 1101 if (fDaclPresent)
1090 1102 {
1091 if (!GNGetAclInformation(pACL, &AclInfo, 1103 if (!GNGetAclInformation(pACL, &AclInfo,
1092 sizeof(ACL_SIZE_INFORMATION), AclSizeInformation)) { 1104 sizeof(ACL_SIZE_INFORMATION), AclSizeInformation))
1093 goto end; 1105 {
1094 } 1106 goto end;
1095 } 1107 }
1108 }
1096 1109
1097 /** 1110 /**
1098 * STEP 6: Compute size needed for the new ACL. 1111 * STEP 6: Compute size needed for the new ACL.
1099 */ 1112 */
1100 cbNewACL = AclInfo.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE) 1113 cbNewACL = AclInfo.AclBytesInUse + sizeof(ACCESS_ALLOWED_ACE)
1101 + GetLengthSid(pUserSID) - sizeof(DWORD); 1114 + GetLengthSid(pUserSID) - sizeof(DWORD);
1102 1115
1103 /** 1116 /**
1104 * STEP 7: Allocate memory for new ACL. 1117 * STEP 7: Allocate memory for new ACL.
1105 */ 1118 */
1106 pNewACL = (PACL) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbNewACL); 1119 pNewACL = (PACL)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, cbNewACL);
1107 if (!pNewACL) { 1120 if (!pNewACL)
1108 goto end; 1121 {
1109 } 1122 goto end;
1123 }
1110 1124
1111 /** 1125 /**
1112 * STEP 8: Initialize the new ACL. 1126 * STEP 8: Initialize the new ACL.
1113 */ 1127 */
1114 if (!GNInitializeAcl(pNewACL, cbNewACL, ACL_REVISION2)) { 1128 if (!GNInitializeAcl(pNewACL, cbNewACL, ACL_REVISION2))
1115 goto end; 1129 {
1116 } 1130 goto end;
1131 }
1117 1132
1118 /** 1133 /**
1119 * STEP 9 If DACL is present, copy all the ACEs from the old DACL 1134 * STEP 9 If DACL is present, copy all the ACEs from the old DACL
@@ -1128,51 +1143,53 @@ BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
1128 1143
1129 newAceIndex = 0; 1144 newAceIndex = 0;
1130 1145
1131 if (fDaclPresent && AclInfo.AceCount) { 1146 if (fDaclPresent && AclInfo.AceCount)
1132 1147 {
1133 for (CurrentAceIndex = 0; 1148 for (CurrentAceIndex = 0;
1134 CurrentAceIndex < AclInfo.AceCount; 1149 CurrentAceIndex < AclInfo.AceCount;
1135 CurrentAceIndex++) { 1150 CurrentAceIndex++)
1151 {
1152 /**
1153 * TEP 10: Get an ACE.
1154 */
1155 if (!GNGetAce(pACL, CurrentAceIndex, &pTempAce))
1156 {
1157 goto end;
1158 }
1136 1159
1137 /** 1160 /**
1138 * TEP 10: Get an ACE. 1161 * STEP 11: Check if it is a non-inherited ACE.
1139 */ 1162 * If it is an inherited ACE, break from the loop so
1140 if (!GNGetAce(pACL, CurrentAceIndex, &pTempAce)) { 1163 * that the new access allowed non-inherited ACE can
1141 goto end; 1164 * be added in the correct position, immediately after
1142 } 1165 * all non-inherited ACEs.
1166 */
1167 if (((ACCESS_ALLOWED_ACE *)pTempAce)->Header.AceFlags
1168 & INHERITED_ACE)
1169 break;
1170
1171 /**
1172 * STEP 12: Skip adding the ACE, if the SID matches
1173 * with the account specified, as we are going to
1174 * add an access allowed ACE with a different access
1175 * mask.
1176 */
1177 if (GNEqualSid(pUserSID,
1178 &(((ACCESS_ALLOWED_ACE *)pTempAce)->SidStart)))
1179 continue;
1180
1181 /**
1182 * STEP 13: Add the ACE to the new ACL.
1183 */
1184 if (!GNAddAce(pNewACL, ACL_REVISION, MAXDWORD, pTempAce,
1185 ((PACE_HEADER)pTempAce)->AceSize))
1186 {
1187 goto end;
1188 }
1143 1189
1144 /** 1190 newAceIndex++;
1145 * STEP 11: Check if it is a non-inherited ACE.
1146 * If it is an inherited ACE, break from the loop so
1147 * that the new access allowed non-inherited ACE can
1148 * be added in the correct position, immediately after
1149 * all non-inherited ACEs.
1150 */
1151 if (((ACCESS_ALLOWED_ACE *)pTempAce)->Header.AceFlags
1152 & INHERITED_ACE)
1153 break;
1154
1155 /**
1156 * STEP 12: Skip adding the ACE, if the SID matches
1157 * with the account specified, as we are going to
1158 * add an access allowed ACE with a different access
1159 * mask.
1160 */
1161 if (GNEqualSid(pUserSID,
1162 &(((ACCESS_ALLOWED_ACE *)pTempAce)->SidStart)))
1163 continue;
1164
1165 /**
1166 * STEP 13: Add the ACE to the new ACL.
1167 */
1168 if (!GNAddAce(pNewACL, ACL_REVISION, MAXDWORD, pTempAce,
1169 ((PACE_HEADER) pTempAce)->AceSize)) {
1170 goto end;
1171 } 1191 }
1172 1192 }
1173 newAceIndex++;
1174 }
1175 }
1176 1193
1177 /** 1194 /**
1178 * STEP 14: Add the access-allowed ACE to the new DACL. 1195 * STEP 14: Add the access-allowed ACE to the new DACL.
@@ -1180,9 +1197,10 @@ BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
1180 * immediately after all existing non-inherited ACEs. 1197 * immediately after all existing non-inherited ACEs.
1181 */ 1198 */
1182 if (!GNAddAccessAllowedAce(pNewACL, ACL_REVISION2, dwAccessMask, 1199 if (!GNAddAccessAllowedAce(pNewACL, ACL_REVISION2, dwAccessMask,
1183 pUserSID)) { 1200 pUserSID))
1184 goto end; 1201 {
1185 } 1202 goto end;
1203 }
1186 1204
1187 /** 1205 /**
1188 * STEP 14.5: Make new ACE inheritable 1206 * STEP 14.5: Make new ACE inheritable
@@ -1197,36 +1215,39 @@ BOOL AddPathAccessRights(char *lpszFileName, char *lpszAccountName,
1197 * we will now copy the rest of inherited ACEs from the 1215 * we will now copy the rest of inherited ACEs from the
1198 * old DACL to the new DACL. 1216 * old DACL to the new DACL.
1199 */ 1217 */
1200 if (fDaclPresent && AclInfo.AceCount) { 1218 if (fDaclPresent && AclInfo.AceCount)
1201 1219 {
1202 for (; 1220 for (;
1203 CurrentAceIndex < AclInfo.AceCount; 1221 CurrentAceIndex < AclInfo.AceCount;
1204 CurrentAceIndex++) { 1222 CurrentAceIndex++)
1205 1223 {
1206 /** 1224 /**
1207 * STEP 16: Get an ACE. 1225 * STEP 16: Get an ACE.
1208 */ 1226 */
1209 if (!GNGetAce(pACL, CurrentAceIndex, &pTempAce)) { 1227 if (!GNGetAce(pACL, CurrentAceIndex, &pTempAce))
1210 goto end; 1228 {
1211 } 1229 goto end;
1230 }
1212 1231
1213 /** 1232 /**
1214 * STEP 17: Add the ACE to the new ACL. 1233 * STEP 17: Add the ACE to the new ACL.
1215 */ 1234 */
1216 if (!GNAddAce(pNewACL, ACL_REVISION, MAXDWORD, pTempAce, 1235 if (!GNAddAce(pNewACL, ACL_REVISION, MAXDWORD, pTempAce,
1217 ((PACE_HEADER) pTempAce)->AceSize)) { 1236 ((PACE_HEADER)pTempAce)->AceSize))
1218 goto end; 1237 {
1238 goto end;
1239 }
1219 } 1240 }
1220 } 1241 }
1221 }
1222 1242
1223 /** 1243 /**
1224 * STEP 18: Set permissions 1244 * STEP 18: Set permissions
1225 */ 1245 */
1226 if (GNSetNamedSecurityInfo((LPTSTR) lpszFileName, SE_FILE_OBJECT, 1246 if (GNSetNamedSecurityInfo((LPTSTR)lpszFileName, SE_FILE_OBJECT,
1227 DACL_SECURITY_INFORMATION, NULL, NULL, pNewACL, NULL) != ERROR_SUCCESS) { 1247 DACL_SECURITY_INFORMATION, NULL, NULL, pNewACL, NULL) != ERROR_SUCCESS)
1228 goto end; 1248 {
1229 } 1249 goto end;
1250 }
1230 1251
1231 fResult = TRUE; 1252 fResult = TRUE;
1232 1253
@@ -1236,16 +1257,16 @@ end:
1236 * STEP 19: Free allocated memory 1257 * STEP 19: Free allocated memory
1237 */ 1258 */
1238 if (pUserSID) 1259 if (pUserSID)
1239 HeapFree(GetProcessHeap(), 0, pUserSID); 1260 HeapFree(GetProcessHeap(), 0, pUserSID);
1240 1261
1241 if (szDomain) 1262 if (szDomain)
1242 HeapFree(GetProcessHeap(), 0, szDomain); 1263 HeapFree(GetProcessHeap(), 0, szDomain);
1243 1264
1244 if (pFileSD) 1265 if (pFileSD)
1245 HeapFree(GetProcessHeap(), 0, pFileSD); 1266 HeapFree(GetProcessHeap(), 0, pFileSD);
1246 1267
1247 if (pNewACL) 1268 if (pNewACL)
1248 HeapFree(GetProcessHeap(), 0, pNewACL); 1269 HeapFree(GetProcessHeap(), 0, pNewACL);
1249 1270
1250 return fResult; 1271 return fResult;
1251} 1272}
@@ -1255,15 +1276,15 @@ char *winErrorStr(const char *prefix, int dwErr)
1255 char *err, *ret; 1276 char *err, *ret;
1256 int mem; 1277 int mem;
1257 1278
1258 if (! FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, 1279 if (!FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
1259 NULL, (DWORD) dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR) &err, 1280 NULL, (DWORD)dwErr, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&err,
1260 0, NULL )) 1281 0, NULL))
1261 { 1282 {
1262 err = (char *) LocalAlloc (LMEM_FIXED | LMEM_ZEROINIT, 1); 1283 err = (char *)LocalAlloc(LMEM_FIXED | LMEM_ZEROINIT, 1);
1263 } 1284 }
1264 1285
1265 mem = strlen(err) + strlen(prefix) + 20; 1286 mem = strlen(err) + strlen(prefix) + 20;
1266 ret = (char *) malloc(mem); 1287 ret = (char *)malloc(mem);
1267 1288
1268 snprintf(ret, mem, "%s: %s (#%u)", prefix, err, dwErr); 1289 snprintf(ret, mem, "%s: %s (#%u)", prefix, err, dwErr);
1269 1290
@@ -1285,58 +1306,58 @@ char *winErrorStr(const char *prefix, int dwErr)
1285 * @return TRUE on success, FALSE on failure (check last error for the code) 1306 * @return TRUE on success, FALSE on failure (check last error for the code)
1286 */ 1307 */
1287BOOL 1308BOOL
1288SafeTerminateProcess (HANDLE hProcess, UINT uExitCode, DWORD dwTimeout) 1309SafeTerminateProcess(HANDLE hProcess, UINT uExitCode, DWORD dwTimeout)
1289{ 1310{
1290 DWORD dwTID, dwCode, dwErr = 0; 1311 DWORD dwTID, dwCode, dwErr = 0;
1291 HANDLE hProcessDup = INVALID_HANDLE_VALUE; 1312 HANDLE hProcessDup = INVALID_HANDLE_VALUE;
1292 HANDLE hRT = NULL; 1313 HANDLE hRT = NULL;
1293 HINSTANCE hKernel = GetModuleHandle ("Kernel32"); 1314 HINSTANCE hKernel = GetModuleHandle("Kernel32");
1294 BOOL bSuccess = FALSE; 1315 BOOL bSuccess = FALSE;
1295 1316
1296 BOOL bDup = DuplicateHandle (GetCurrentProcess (), hProcess, 1317 BOOL bDup = DuplicateHandle(GetCurrentProcess(), hProcess,
1297 GetCurrentProcess (), &hProcessDup, PROCESS_ALL_ACCESS, 1318 GetCurrentProcess(), &hProcessDup, PROCESS_ALL_ACCESS,
1298 FALSE, 0); 1319 FALSE, 0);
1299 1320
1300 /* Detect the special case where the process is 1321 /* Detect the special case where the process is
1301 * already dead... 1322 * already dead...
1302 */ 1323 */
1303 if (GetExitCodeProcess (bDup ? hProcessDup : hProcess, &dwCode) && 1324 if (GetExitCodeProcess(bDup ? hProcessDup : hProcess, &dwCode) &&
1304 (STILL_ACTIVE == dwCode)) 1325 (STILL_ACTIVE == dwCode))
1305 { 1326 {
1306 FARPROC pfnExitProc; 1327 FARPROC pfnExitProc;
1307 1328
1308 pfnExitProc = GetProcAddress (hKernel, "ExitProcess"); 1329 pfnExitProc = GetProcAddress(hKernel, "ExitProcess");
1309 1330
1310 hRT = CreateRemoteThread ((bDup) ? hProcessDup : hProcess, NULL, 0, 1331 hRT = CreateRemoteThread((bDup) ? hProcessDup : hProcess, NULL, 0,
1311 (LPTHREAD_START_ROUTINE) pfnExitProc, (PVOID) uExitCode, 0, &dwTID); 1332 (LPTHREAD_START_ROUTINE)pfnExitProc, (PVOID)uExitCode, 0, &dwTID);
1312 1333
1313 dwErr = GetLastError (); 1334 dwErr = GetLastError();
1314 } 1335 }
1315 else 1336 else
1316 { 1337 {
1317 dwErr = ERROR_PROCESS_ABORTED; 1338 dwErr = ERROR_PROCESS_ABORTED;
1318 } 1339 }
1319 1340
1320 if (hRT) 1341 if (hRT)
1321 { 1342 {
1322 /* Must wait process to terminate to 1343 /* Must wait process to terminate to
1323 * guarantee that it has exited... 1344 * guarantee that it has exited...
1324 */ 1345 */
1325 DWORD dwWaitResult = WaitForSingleObject ((bDup) ? hProcessDup : hProcess, 1346 DWORD dwWaitResult = WaitForSingleObject((bDup) ? hProcessDup : hProcess,
1326 dwTimeout); 1347 dwTimeout);
1327 if (dwWaitResult == WAIT_TIMEOUT) 1348 if (dwWaitResult == WAIT_TIMEOUT)
1328 dwErr = WAIT_TIMEOUT; 1349 dwErr = WAIT_TIMEOUT;
1329 else 1350 else
1330 dwErr = GetLastError (); 1351 dwErr = GetLastError();
1331 1352
1332 CloseHandle (hRT); 1353 CloseHandle(hRT);
1333 bSuccess = dwErr == NO_ERROR; 1354 bSuccess = dwErr == NO_ERROR;
1334 } 1355 }
1335 1356
1336 if (bDup) 1357 if (bDup)
1337 CloseHandle (hProcessDup); 1358 CloseHandle(hProcessDup);
1338 1359
1339 SetLastError (dwErr); 1360 SetLastError(dwErr);
1340 1361
1341 return bSuccess; 1362 return bSuccess;
1342} 1363}
diff --git a/src/util/winproc.c b/src/util/winproc.c
index 2781b901f..f2e4de4df 100644
--- a/src/util/winproc.c
+++ b/src/util/winproc.c
@@ -11,12 +11,12 @@
11 WITHOUT ANY WARRANTY; without even the implied warranty of 11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 Affero General Public License for more details. 13 Affero General Public License for more details.
14 14
15 You should have received a copy of the GNU Affero General Public License 15 You should have received a copy of the GNU Affero General Public License
16 along with this program. If not, see <http://www.gnu.org/licenses/>. 16 along with this program. If not, see <http://www.gnu.org/licenses/>.
17 17
18 SPDX-License-Identifier: AGPL3.0-or-later 18 SPDX-License-Identifier: AGPL3.0-or-later
19*/ 19 */
20 20
21/** 21/**
22 * @file util/winproc.c 22 * @file util/winproc.c
@@ -69,15 +69,15 @@ TAddAce GNAddAce;
69TAddAccessAllowedAce GNAddAccessAllowedAce; 69TAddAccessAllowedAce GNAddAccessAllowedAce;
70TSetNamedSecurityInfo GNSetNamedSecurityInfo; 70TSetNamedSecurityInfo GNSetNamedSecurityInfo;
71 71
72#define LOG(kind,...) GNUNET_log_from (kind, "util-winproc", __VA_ARGS__) 72#define LOG(kind, ...) GNUNET_log_from(kind, "util-winproc", __VA_ARGS__)
73/** 73/**
74 * Log (panic) messages from PlibC 74 * Log (panic) messages from PlibC
75 */ 75 */
76void 76void
77plibc_panic (int err, char *msg) 77plibc_panic(int err, char *msg)
78{ 78{
79 LOG (((err == INT_MAX) ? GNUNET_ERROR_TYPE_DEBUG : GNUNET_ERROR_TYPE_ERROR), 79 LOG(((err == INT_MAX) ? GNUNET_ERROR_TYPE_DEBUG : GNUNET_ERROR_TYPE_ERROR),
80 "%s", msg); 80 "%s", msg);
81} 81}
82 82
83#ifdef W32_VEH 83#ifdef W32_VEH
@@ -91,45 +91,46 @@ plibc_panic (int err, char *msg)
91 * only way out of WaitForSingleObject() is to time out after 1 minute). 91 * only way out of WaitForSingleObject() is to time out after 1 minute).
92 */ 92 */
93LONG __stdcall 93LONG __stdcall
94GNWinVEH (PEXCEPTION_POINTERS ExceptionInfo) 94GNWinVEH(PEXCEPTION_POINTERS ExceptionInfo)
95{ 95{
96 char debugger[MAX_PATH + 1]; 96 char debugger[MAX_PATH + 1];
97 char *debugger_env = NULL; 97 char *debugger_env = NULL;
98 if (IsDebuggerPresent ()) 98
99 { 99 if (IsDebuggerPresent())
100 DebugBreak (); 100 {
101 return EXCEPTION_CONTINUE_EXECUTION; 101 DebugBreak();
102 } 102 return EXCEPTION_CONTINUE_EXECUTION;
103 debugger_env = getenv ("GNUNET_DEBUGGER"); 103 }
104 debugger_env = getenv("GNUNET_DEBUGGER");
104 if (debugger_env != NULL) 105 if (debugger_env != NULL)
105 {
106 STARTUPINFO si;
107 PROCESS_INFORMATION pi;
108 HANDLE event;
109 SECURITY_ATTRIBUTES sa;
110 memset (&si, 0, sizeof (si));
111 si.cb = sizeof (si);
112 memset (&pi, 0, sizeof (pi));
113 memset (&sa, 0, sizeof (sa));
114 sa.nLength = sizeof (sa);
115 sa.bInheritHandle = TRUE;
116 event = CreateEvent (&sa, FALSE, FALSE, NULL);
117 snprintf (debugger, MAX_PATH + 1, debugger_env, GetCurrentProcessId (), (uintptr_t) event);
118 debugger[MAX_PATH] = '\0';
119 if (0 != CreateProcessA (NULL, debugger, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
120 { 106 {
121 CloseHandle (pi.hProcess); 107 STARTUPINFO si;
122 CloseHandle (pi.hThread); 108 PROCESS_INFORMATION pi;
123 WaitForSingleObject (event, 60000); 109 HANDLE event;
124 CloseHandle (event); 110 SECURITY_ATTRIBUTES sa;
125 if (IsDebuggerPresent ()) 111 memset(&si, 0, sizeof(si));
126 { 112 si.cb = sizeof(si);
127 return EXCEPTION_CONTINUE_EXECUTION; 113 memset(&pi, 0, sizeof(pi));
128 } 114 memset(&sa, 0, sizeof(sa));
115 sa.nLength = sizeof(sa);
116 sa.bInheritHandle = TRUE;
117 event = CreateEvent(&sa, FALSE, FALSE, NULL);
118 snprintf(debugger, MAX_PATH + 1, debugger_env, GetCurrentProcessId(), (uintptr_t)event);
119 debugger[MAX_PATH] = '\0';
120 if (0 != CreateProcessA(NULL, debugger, NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
121 {
122 CloseHandle(pi.hProcess);
123 CloseHandle(pi.hThread);
124 WaitForSingleObject(event, 60000);
125 CloseHandle(event);
126 if (IsDebuggerPresent())
127 {
128 return EXCEPTION_CONTINUE_EXECUTION;
129 }
130 }
131 else
132 CloseHandle(event);
129 } 133 }
130 else
131 CloseHandle (event);
132 }
133 return EXCEPTION_CONTINUE_SEARCH; 134 return EXCEPTION_CONTINUE_SEARCH;
134} 135}
135#endif 136#endif
@@ -138,168 +139,168 @@ GNWinVEH (PEXCEPTION_POINTERS ExceptionInfo)
138 * @brief Initialize PlibC and set up Windows environment 139 * @brief Initialize PlibC and set up Windows environment
139 * @param logging context, NULL means stderr 140 * @param logging context, NULL means stderr
140 * @return Error code from winerror.h, ERROR_SUCCESS on success 141 * @return Error code from winerror.h, ERROR_SUCCESS on success
141*/ 142 */
142int 143int
143GNInitWinEnv () 144GNInitWinEnv()
144{ 145{
145 int ret; 146 int ret;
146 147
147 plibc_initialized (); 148 plibc_initialized();
148 plibc_set_panic_proc (plibc_panic); 149 plibc_set_panic_proc(plibc_panic);
149 ret = plibc_init_utf8 ("GNU", PACKAGE, 1); 150 ret = plibc_init_utf8("GNU", PACKAGE, 1);
150 plibc_set_stat_size_size (sizeof (((struct stat *) 0)->st_size)); 151 plibc_set_stat_size_size(sizeof(((struct stat *)0)->st_size));
151 plibc_set_stat_time_size (sizeof (((struct stat *) 0)->st_mtime)); 152 plibc_set_stat_time_size(sizeof(((struct stat *)0)->st_mtime));
152 /* don't load other DLLs twice */ 153 /* don't load other DLLs twice */
153 if (hNTDLL) 154 if (hNTDLL)
154 return ret; 155 return ret;
155 156
156#ifdef W32_VEH 157#ifdef W32_VEH
157 if (GNWinVEH_handle == NULL) 158 if (GNWinVEH_handle == NULL)
158 {
159 GNWinVEH_handle = AddVectoredExceptionHandler (1, &GNWinVEH);
160 if (GNWinVEH_handle == NULL)
161 { 159 {
162 /* This is bad, but what can we do? */ 160 GNWinVEH_handle = AddVectoredExceptionHandler(1, &GNWinVEH);
163 printf ("Failed to set up an exception handler!\n"); 161 if (GNWinVEH_handle == NULL)
162 {
163 /* This is bad, but what can we do? */
164 printf("Failed to set up an exception handler!\n");
165 }
164 } 166 }
165 }
166#endif 167#endif
167 168
168 hNTDLL = LoadLibrary ("ntdll.dll"); 169 hNTDLL = LoadLibrary("ntdll.dll");
169 170
170 /* Function to get CPU usage under Win NT */ 171 /* Function to get CPU usage under Win NT */
171 if (hNTDLL) 172 if (hNTDLL)
172 { 173 {
173 GNNtQuerySystemInformation = 174 GNNtQuerySystemInformation =
174 (TNtQuerySystemInformation) GetProcAddress (hNTDLL, 175 (TNtQuerySystemInformation)GetProcAddress(hNTDLL,
175 "NtQuerySystemInformation"); 176 "NtQuerySystemInformation");
176 } 177 }
177 else 178 else
178 { 179 {
179 GNNtQuerySystemInformation = NULL; 180 GNNtQuerySystemInformation = NULL;
180 } 181 }
181 182
182 /* Functions to get information about a network adapter */ 183 /* Functions to get information about a network adapter */
183 hIphlpapi = LoadLibrary ("iphlpapi.dll"); 184 hIphlpapi = LoadLibrary("iphlpapi.dll");
184 if (hIphlpapi) 185 if (hIphlpapi)
185 { 186 {
186 GNGetIfEntry = (TGetIfEntry) GetProcAddress (hIphlpapi, "GetIfEntry"); 187 GNGetIfEntry = (TGetIfEntry)GetProcAddress(hIphlpapi, "GetIfEntry");
187 GNGetIpAddrTable = 188 GNGetIpAddrTable =
188 (TGetIpAddrTable) GetProcAddress (hIphlpapi, "GetIpAddrTable"); 189 (TGetIpAddrTable)GetProcAddress(hIphlpapi, "GetIpAddrTable");
189 GNGetIfTable = (TGetIfTable) GetProcAddress (hIphlpapi, "GetIfTable"); 190 GNGetIfTable = (TGetIfTable)GetProcAddress(hIphlpapi, "GetIfTable");
190 GNGetBestInterfaceEx = 191 GNGetBestInterfaceEx =
191 (TGetBestInterfaceEx) GetProcAddress (hIphlpapi, "GetBestInterfaceEx"); 192 (TGetBestInterfaceEx)GetProcAddress(hIphlpapi, "GetBestInterfaceEx");
192 GNGetAdaptersInfo = 193 GNGetAdaptersInfo =
193 (TGetAdaptersInfo) GetProcAddress (hIphlpapi, "GetAdaptersInfo"); 194 (TGetAdaptersInfo)GetProcAddress(hIphlpapi, "GetAdaptersInfo");
194 } 195 }
195 else 196 else
196 { 197 {
197 GNGetIfEntry = NULL; 198 GNGetIfEntry = NULL;
198 GNGetIpAddrTable = NULL; 199 GNGetIpAddrTable = NULL;
199 GNGetIfTable = NULL; 200 GNGetIfTable = NULL;
200 GNGetBestInterfaceEx = NULL; 201 GNGetBestInterfaceEx = NULL;
201 GNGetAdaptersInfo = NULL; 202 GNGetAdaptersInfo = NULL;
202 } 203 }
203 204
204 /* Service & Account functions */ 205 /* Service & Account functions */
205 hAdvapi = LoadLibrary ("advapi32.dll"); 206 hAdvapi = LoadLibrary("advapi32.dll");
206 if (hAdvapi) 207 if (hAdvapi)
207 { 208 {
208 GNOpenSCManager = 209 GNOpenSCManager =
209 (TOpenSCManager) GetProcAddress (hAdvapi, "OpenSCManagerA"); 210 (TOpenSCManager)GetProcAddress(hAdvapi, "OpenSCManagerA");
210 GNCreateService = 211 GNCreateService =
211 (TCreateService) GetProcAddress (hAdvapi, "CreateServiceA"); 212 (TCreateService)GetProcAddress(hAdvapi, "CreateServiceA");
212 GNCloseServiceHandle = 213 GNCloseServiceHandle =
213 (TCloseServiceHandle) GetProcAddress (hAdvapi, "CloseServiceHandle"); 214 (TCloseServiceHandle)GetProcAddress(hAdvapi, "CloseServiceHandle");
214 GNDeleteService = 215 GNDeleteService =
215 (TDeleteService) GetProcAddress (hAdvapi, "DeleteService"); 216 (TDeleteService)GetProcAddress(hAdvapi, "DeleteService");
216 GNRegisterServiceCtrlHandler = 217 GNRegisterServiceCtrlHandler =
217 (TRegisterServiceCtrlHandler) GetProcAddress (hAdvapi, 218 (TRegisterServiceCtrlHandler)GetProcAddress(hAdvapi,
218 "RegisterServiceCtrlHandlerA"); 219 "RegisterServiceCtrlHandlerA");
219 GNSetServiceStatus = 220 GNSetServiceStatus =
220 (TSetServiceStatus) GetProcAddress (hAdvapi, "SetServiceStatus"); 221 (TSetServiceStatus)GetProcAddress(hAdvapi, "SetServiceStatus");
221 GNStartServiceCtrlDispatcher = 222 GNStartServiceCtrlDispatcher =
222 (TStartServiceCtrlDispatcher) GetProcAddress (hAdvapi, 223 (TStartServiceCtrlDispatcher)GetProcAddress(hAdvapi,
223 "StartServiceCtrlDispatcherA"); 224 "StartServiceCtrlDispatcherA");
224 GNControlService = 225 GNControlService =
225 (TControlService) GetProcAddress (hAdvapi, "ControlService"); 226 (TControlService)GetProcAddress(hAdvapi, "ControlService");
226 GNOpenService = (TOpenService) GetProcAddress (hAdvapi, "OpenServiceA"); 227 GNOpenService = (TOpenService)GetProcAddress(hAdvapi, "OpenServiceA");
227 228
228 GNLsaOpenPolicy = 229 GNLsaOpenPolicy =
229 (TLsaOpenPolicy) GetProcAddress (hAdvapi, "LsaOpenPolicy"); 230 (TLsaOpenPolicy)GetProcAddress(hAdvapi, "LsaOpenPolicy");
230 GNLsaAddAccountRights = 231 GNLsaAddAccountRights =
231 (TLsaAddAccountRights) GetProcAddress (hAdvapi, "LsaAddAccountRights"); 232 (TLsaAddAccountRights)GetProcAddress(hAdvapi, "LsaAddAccountRights");
232 GNLsaRemoveAccountRights = 233 GNLsaRemoveAccountRights =
233 (TLsaRemoveAccountRights) GetProcAddress (hAdvapi, 234 (TLsaRemoveAccountRights)GetProcAddress(hAdvapi,
234 "LsaRemoveAccountRights"); 235 "LsaRemoveAccountRights");
235 GNLsaClose = (TLsaClose) GetProcAddress (hAdvapi, "LsaClose"); 236 GNLsaClose = (TLsaClose)GetProcAddress(hAdvapi, "LsaClose");
236 GNLookupAccountName = 237 GNLookupAccountName =
237 (TLookupAccountName) GetProcAddress (hAdvapi, "LookupAccountNameA"); 238 (TLookupAccountName)GetProcAddress(hAdvapi, "LookupAccountNameA");
238 239
239 GNGetFileSecurity = 240 GNGetFileSecurity =
240 (TGetFileSecurity) GetProcAddress (hAdvapi, "GetFileSecurityA"); 241 (TGetFileSecurity)GetProcAddress(hAdvapi, "GetFileSecurityA");
241 GNInitializeSecurityDescriptor = 242 GNInitializeSecurityDescriptor =
242 (TInitializeSecurityDescriptor) GetProcAddress (hAdvapi, 243 (TInitializeSecurityDescriptor)GetProcAddress(hAdvapi,
243 "InitializeSecurityDescriptor"); 244 "InitializeSecurityDescriptor");
244 GNGetSecurityDescriptorDacl = 245 GNGetSecurityDescriptorDacl =
245 (TGetSecurityDescriptorDacl) GetProcAddress (hAdvapi, 246 (TGetSecurityDescriptorDacl)GetProcAddress(hAdvapi,
246 "GetSecurityDescriptorDacl"); 247 "GetSecurityDescriptorDacl");
247 GNGetAclInformation = 248 GNGetAclInformation =
248 (TGetAclInformation) GetProcAddress (hAdvapi, "GetAclInformation"); 249 (TGetAclInformation)GetProcAddress(hAdvapi, "GetAclInformation");
249 GNInitializeAcl = 250 GNInitializeAcl =
250 (TInitializeAcl) GetProcAddress (hAdvapi, "InitializeAcl"); 251 (TInitializeAcl)GetProcAddress(hAdvapi, "InitializeAcl");
251 GNGetAce = (TGetAce) GetProcAddress (hAdvapi, "GetAce"); 252 GNGetAce = (TGetAce)GetProcAddress(hAdvapi, "GetAce");
252 GNEqualSid = (TEqualSid) GetProcAddress (hAdvapi, "EqualSid"); 253 GNEqualSid = (TEqualSid)GetProcAddress(hAdvapi, "EqualSid");
253 GNAddAce = (TAddAce) GetProcAddress (hAdvapi, "AddAce"); 254 GNAddAce = (TAddAce)GetProcAddress(hAdvapi, "AddAce");
254 GNAddAccessAllowedAce = 255 GNAddAccessAllowedAce =
255 (TAddAccessAllowedAce) GetProcAddress (hAdvapi, "AddAccessAllowedAce"); 256 (TAddAccessAllowedAce)GetProcAddress(hAdvapi, "AddAccessAllowedAce");
256 GNSetNamedSecurityInfo = 257 GNSetNamedSecurityInfo =
257 (TSetNamedSecurityInfo) GetProcAddress (hAdvapi, 258 (TSetNamedSecurityInfo)GetProcAddress(hAdvapi,
258 "SetNamedSecurityInfoA"); 259 "SetNamedSecurityInfoA");
259 } 260 }
260 else 261 else
261 { 262 {
262 GNOpenSCManager = NULL; 263 GNOpenSCManager = NULL;
263 GNCreateService = NULL; 264 GNCreateService = NULL;
264 GNCloseServiceHandle = NULL; 265 GNCloseServiceHandle = NULL;
265 GNDeleteService = NULL; 266 GNDeleteService = NULL;
266 GNRegisterServiceCtrlHandler = NULL; 267 GNRegisterServiceCtrlHandler = NULL;
267 GNSetServiceStatus = NULL; 268 GNSetServiceStatus = NULL;
268 GNStartServiceCtrlDispatcher = NULL; 269 GNStartServiceCtrlDispatcher = NULL;
269 GNControlService = NULL; 270 GNControlService = NULL;
270 GNOpenService = NULL; 271 GNOpenService = NULL;
271 272
272 GNLsaOpenPolicy = NULL; 273 GNLsaOpenPolicy = NULL;
273 GNLsaAddAccountRights = NULL; 274 GNLsaAddAccountRights = NULL;
274 GNLsaRemoveAccountRights = NULL; 275 GNLsaRemoveAccountRights = NULL;
275 GNLsaClose = NULL; 276 GNLsaClose = NULL;
276 GNLookupAccountName = NULL; 277 GNLookupAccountName = NULL;
277 278
278 GNGetFileSecurity = NULL; 279 GNGetFileSecurity = NULL;
279 GNInitializeSecurityDescriptor = NULL; 280 GNInitializeSecurityDescriptor = NULL;
280 GNGetSecurityDescriptorDacl = NULL; 281 GNGetSecurityDescriptorDacl = NULL;
281 GNGetAclInformation = NULL; 282 GNGetAclInformation = NULL;
282 GNInitializeAcl = NULL; 283 GNInitializeAcl = NULL;
283 GNGetAce = NULL; 284 GNGetAce = NULL;
284 GNEqualSid = NULL; 285 GNEqualSid = NULL;
285 GNAddAce = NULL; 286 GNAddAce = NULL;
286 GNAddAccessAllowedAce = NULL; 287 GNAddAccessAllowedAce = NULL;
287 GNSetNamedSecurityInfo = NULL; 288 GNSetNamedSecurityInfo = NULL;
288 } 289 }
289 290
290 /* Account function */ 291 /* Account function */
291 hNetapi = LoadLibrary ("netapi32.dll"); 292 hNetapi = LoadLibrary("netapi32.dll");
292 if (hNetapi) 293 if (hNetapi)
293 { 294 {
294 GNNetUserAdd = (TNetUserAdd) GetProcAddress (hNetapi, "NetUserAdd"); 295 GNNetUserAdd = (TNetUserAdd)GetProcAddress(hNetapi, "NetUserAdd");
295 GNNetUserSetInfo = 296 GNNetUserSetInfo =
296 (TNetUserSetInfo) GetProcAddress (hNetapi, "NetUserSetInfo"); 297 (TNetUserSetInfo)GetProcAddress(hNetapi, "NetUserSetInfo");
297 } 298 }
298 else 299 else
299 { 300 {
300 GNNetUserAdd = NULL; 301 GNNetUserAdd = NULL;
301 GNNetUserSetInfo = NULL; 302 GNNetUserSetInfo = NULL;
302 } 303 }
303 304
304 return ret; 305 return ret;
305} 306}
@@ -308,32 +309,32 @@ GNInitWinEnv ()
308 * Clean up Windows environment 309 * Clean up Windows environment
309 */ 310 */
310void 311void
311GNShutdownWinEnv () 312GNShutdownWinEnv()
312{ 313{
313 plibc_shutdown (); 314 plibc_shutdown();
314 315
315#ifdef W32_VEH 316#ifdef W32_VEH
316 if (GNWinVEH_handle != NULL) 317 if (GNWinVEH_handle != NULL)
317 { 318 {
318 RemoveVectoredExceptionHandler (GNWinVEH_handle); 319 RemoveVectoredExceptionHandler(GNWinVEH_handle);
319 GNWinVEH_handle = NULL; 320 GNWinVEH_handle = NULL;
320 } 321 }
321#endif 322#endif
322 323
323 FreeLibrary (hNTDLL); 324 FreeLibrary(hNTDLL);
324 FreeLibrary (hIphlpapi); 325 FreeLibrary(hIphlpapi);
325 FreeLibrary (hAdvapi); 326 FreeLibrary(hAdvapi);
326 FreeLibrary (hNetapi); 327 FreeLibrary(hNetapi);
327 328
328 CoUninitialize (); 329 CoUninitialize();
329} 330}
330 331
331#endif /* MINGW */ 332#endif /* MINGW */
332 333
333#if !HAVE_ATOLL 334#if !HAVE_ATOLL
334long long 335long long
335atoll (const char *nptr) 336atoll(const char *nptr)
336{ 337{
337 return atol (nptr); 338 return atol(nptr);
338} 339}
339#endif 340#endif