Debian Codegraph @

tools/common.c

raw symbols SCIP
1 // Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors.
2 // SPDX-License-Identifier: mit
3
4 #include "common.h"
5 #ifdef WITH_SSL
6 #include <rabbitmq-c/ssl_socket.h>
7 #endif
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <rabbitmq-c/tcp_socket.h>
11 #include <stdarg.h>
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <unistd.h>
16
17 #ifdef WINDOWS
18 #include "compat.h"
19 #endif
20
21 /* For when reading auth data from a file */
22 #define MAXAUTHTOKENLEN 128
23 #define USERNAMEPREFIX "username:"
24 #define PASSWORDPREFIX "password:"
25
26 void die(const char *fmt, ...) {
27 va_list ap;
28 va_start(ap, fmt);
29 vfprintf(stderr, fmt, ap);
30 va_end(ap);
31 fprintf(stderr, "\n");
32 exit(1);
33 }
34
35 void die_errno(int err, const char *fmt, ...) {
36 va_list ap;
37
38 if (err == 0) {
39 return;
40 }
41
42 va_start(ap, fmt);
43 vfprintf(stderr, fmt, ap);
44 va_end(ap);
45 fprintf(stderr, ": %s\n", strerror(err));
46 exit(1);
47 }
48
49 void die_amqp_error(int err, const char *fmt, ...) {
50 va_list ap;
51
52 if (err >= 0) {
53 return;
54 }
55
56 va_start(ap, fmt);
57 vfprintf(stderr, fmt, ap);
58 va_end(ap);
59 fprintf(stderr, ": %s\n", amqp_error_string2(err));
60 exit(1);
61 }
62
63 const char *amqp_server_exception_string(amqp_rpc_reply_t r) {
64 int res;
65 static char s[512];
66
67 switch (r.reply.id) {
68 case AMQP_CONNECTION_CLOSE_METHOD: {
69 amqp_connection_close_t *m = (amqp_connection_close_t *)r.reply.decoded;
70 res = snprintf(s, sizeof(s), "server connection error %d, message: %.*s",
71 m->reply_code, (int)m->reply_text.len,
72 (char *)m->reply_text.bytes);
73 break;
74 }
75
76 case AMQP_CHANNEL_CLOSE_METHOD: {
77 amqp_channel_close_t *m = (amqp_channel_close_t *)r.reply.decoded;
78 res = snprintf(s, sizeof(s), "server channel error %d, message: %.*s",
79 m->reply_code, (int)m->reply_text.len,
80 (char *)m->reply_text.bytes);
81 break;
82 }
83
84 default:
85 res = snprintf(s, sizeof(s), "unknown server error, method id 0x%08X",
86 r.reply.id);
87 break;
88 }
89
90 return res >= 0 ? s : NULL;
91 }
92
93 const char *amqp_rpc_reply_string(amqp_rpc_reply_t r) {
94 switch (r.reply_type) {
95 case AMQP_RESPONSE_NORMAL:
96 return "normal response";
97
98 case AMQP_RESPONSE_NONE:
99 return "missing RPC reply type";
100
101 case AMQP_RESPONSE_LIBRARY_EXCEPTION:
102 return amqp_error_string2(r.library_error);
103
104 case AMQP_RESPONSE_SERVER_EXCEPTION:
105 return amqp_server_exception_string(r);
106
107 default:
108 abort();
109 }
110 }
111
112 void die_rpc(amqp_rpc_reply_t r, const char *fmt, ...) {
113 va_list ap;
114
115 if (r.reply_type == AMQP_RESPONSE_NORMAL) {
116 return;
117 }
118
119 va_start(ap, fmt);
120 vfprintf(stderr, fmt, ap);
121 va_end(ap);
122 fprintf(stderr, ": %s\n", amqp_rpc_reply_string(r));
123 exit(1);
124 }
125
126 static char *amqp_url;
127 static char *amqp_server;
128 static int amqp_port = -1;
129 static char *amqp_vhost;
130 static char *amqp_username;
131 static char *amqp_password;
132 static int amqp_heartbeat = 0;
133 static char *amqp_authfile;
134 #ifdef WITH_SSL
135 static int amqp_ssl = 0;
136 static char *amqp_cacert = "/etc/ssl/certs/cacert.pem";
137 static char *amqp_key = NULL;
138 static char *amqp_cert = NULL;
139 static int amqp_no_default_cert_paths = 0;
140 #endif /* WITH_SSL */
141
142 const char *connect_options_title = "Connection options";
143 struct poptOption connect_options[] = {
144 {"url", 'u', POPT_ARG_STRING, &amqp_url, 0,
145 "the AMQP URL to connect to (overrides AMQP_URL env var)", "amqp://..."},
146 {"server", 's', POPT_ARG_STRING, &amqp_server, 0,
147 "the AMQP server to connect to", "hostname"},
148 {"port", 0, POPT_ARG_INT, &amqp_port, 0, "the port to connect on", "port"},
149 {"vhost", 0, POPT_ARG_STRING, &amqp_vhost, 0,
150 "the vhost to use when connecting", "vhost"},
151 {"username", 0, POPT_ARG_STRING, &amqp_username, 0,
152 "the username to login with", "username"},
153 {"password", 0, POPT_ARG_STRING, &amqp_password, 0,
154 "the password to login with", "password"},
155 {"heartbeat", 0, POPT_ARG_INT, &amqp_heartbeat, 0,
156 "heartbeat interval, set to 0 to disable", "heartbeat"},
157 {"authfile", 0, POPT_ARG_STRING, &amqp_authfile, 0,
158 "path to file containing username/password for authentication", "file"},
159 #ifdef WITH_SSL
160 {"ssl", 0, POPT_ARG_NONE, &amqp_ssl, 0, "connect over SSL/TLS", NULL},
161 {"cacert", 0, POPT_ARG_STRING, &amqp_cacert, 0,
162 "path to the CA certificate file", "cacert.pem"},
163 {"key", 0, POPT_ARG_STRING, &amqp_key, 0,
164 "path to the client private key file", "key.pem"},
165 {"cert", 0, POPT_ARG_STRING, &amqp_cert, 0,
166 "path to the client certificate file", "cert.pem"},
167 {"no-default-cert-paths", 0, POPT_ARG_NONE, &amqp_no_default_cert_paths, 0,
168 "do not use default certificate paths", NULL},
169 #endif /* WITH_SSL */
170 {NULL, '\0', 0, NULL, 0, NULL, NULL}};
171
172 static void read_authfile(const char *path) {
173 size_t n;
174 FILE *fp = NULL;
175 char token[MAXAUTHTOKENLEN];
176
177 if ((amqp_username = malloc(MAXAUTHTOKENLEN)) == NULL ||
178 (amqp_password = malloc(MAXAUTHTOKENLEN)) == NULL) {
179 die("Out of memory");
180 } else if ((fp = fopen(path, "r")) == NULL) {
181 die("Could not read auth data file %s", path);
182 }
183
184 if (fgets(token, MAXAUTHTOKENLEN, fp) == NULL ||
185 strncmp(token, USERNAMEPREFIX, strlen(USERNAMEPREFIX))) {
186 die("Malformed auth file (missing username)");
187 }
188 strncpy(amqp_username, &token[strlen(USERNAMEPREFIX)], MAXAUTHTOKENLEN);
189 /* Missing newline means token was cut off */
190 n = strlen(amqp_username);
191 if (amqp_username[n - 1] != '\n') {
192 die("Username too long");
193 } else {
194 amqp_username[n - 1] = '\0';
195 }
196
197 if (fgets(token, MAXAUTHTOKENLEN, fp) == NULL ||
198 strncmp(token, PASSWORDPREFIX, strlen(PASSWORDPREFIX))) {
199 die("Malformed auth file (missing password)");
200 }
201 strncpy(amqp_password, &token[strlen(PASSWORDPREFIX)], MAXAUTHTOKENLEN);
202 /* Missing newline means token was cut off */
203 n = strlen(amqp_password);
204 if (amqp_password[n - 1] != '\n') {
205 die("Password too long");
206 } else {
207 amqp_password[n - 1] = '\0';
208 }
209
210 (void)fgetc(fp);
211 if (!feof(fp)) {
212 die("Malformed auth file (trailing data)");
213 }
214 fclose(fp);
215 }
216
217 static void init_connection_info(struct amqp_connection_info *ci) {
218 ci->user = NULL;
219 ci->password = NULL;
220 ci->host = NULL;
221 ci->port = -1;
222 ci->vhost = NULL;
223 ci->user = NULL;
224
225 amqp_default_connection_info(ci);
226
227 /* If no connection options were given on the CLI, fall back to AMQP_URL env
228 * var. Any explicit CLI connection flag takes full precedence and bypasses
229 * the env var entirely. */
230 if (!amqp_url && !amqp_server && amqp_port < 0 && !amqp_username &&
231 !amqp_password && !amqp_vhost) {
232 const char *env_url = getenv("AMQP_URL");
233 if (env_url) {
234 amqp_url = (char *)env_url;
235 }
236 }
237
238 if (amqp_url)
239 die_amqp_error(amqp_parse_url(strdup(amqp_url), ci), "Parsing URL '%s'",
240 amqp_url);
241
242 if (amqp_server) {
243 char *colon;
244 if (amqp_url) {
245 die("--server and --url options cannot be used at the same time");
246 }
247
248 /* parse the server string into a hostname and a port */
249 colon = strchr(amqp_server, ':');
250 if (colon) {
251 char *port_end;
252 size_t host_len;
253
254 /* Deprecate specifying the port number with the
255 --server option, because it is not ipv6 friendly.
256 --url now allows connection options to be
257 specified concisely. */
258 fprintf(stderr,
259 "Specifying the port number with --server is deprecated\n");
260
261 host_len = colon - amqp_server;
262 ci->host = malloc(host_len + 1);
263 memcpy(ci->host, amqp_server, host_len);
264 ci->host[host_len] = 0;
265
266 if (amqp_port >= 0) {
267 die("both --server and --port options specify server port");
268 }
269
270 ci->port = strtol(colon + 1, &port_end, 10);
271 if (ci->port < 0 || ci->port > 65535 || port_end == colon + 1 ||
272 *port_end != 0)
273 die("bad server port number in '%s'", amqp_server);
274 } else {
275 ci->host = amqp_server;
276 ci->port = 5672;
277 #if WITH_SSL
278 if (amqp_ssl) {
279 ci->port = 5671;
280 }
281 #endif
282 }
283 }
284
285 #if WITH_SSL
286 if (amqp_ssl && !ci->ssl) {
287 if (amqp_url) {
288 die("the --ssl option specifies an SSL connection"
289 " but the --url option does not");
290 } else {
291 ci->ssl = 1;
292 }
293 }
294 #endif
295
296 if (amqp_port >= 0) {
297 if (amqp_url) {
298 die("--port and --url options cannot be used at the same time");
299 }
300
301 ci->port = amqp_port;
302 }
303
304 if (amqp_username) {
305 if (amqp_url) {
306 die("--username and --url options cannot be used at the same time");
307 } else if (amqp_authfile) {
308 die("--username and --authfile options cannot be used at the same time");
309 }
310
311 ci->user = amqp_username;
312 }
313
314 if (amqp_password) {
315 if (amqp_url) {
316 die("--password and --url options cannot be used at the same time");
317 } else if (amqp_authfile) {
318 die("--password and --authfile options cannot be used at the same time");
319 }
320
321 ci->password = amqp_password;
322 }
323
324 if (amqp_authfile) {
325 if (amqp_url) {
326 die("--authfile and --url options cannot be used at the same time");
327 }
328
329 read_authfile(amqp_authfile);
330 ci->user = amqp_username;
331 ci->password = amqp_password;
332 }
333
334 if (amqp_vhost) {
335 if (amqp_url) {
336 die("--vhost and --url options cannot be used at the same time");
337 }
338
339 ci->vhost = amqp_vhost;
340 }
341
342 if (amqp_heartbeat < 0) {
343 die("--heartbeat must be a positive value");
344 }
345 }
346
347 amqp_connection_state_t make_connection(void) {
348 int status;
349 amqp_socket_t *socket = NULL;
350 struct amqp_connection_info ci;
351 amqp_connection_state_t conn;
352
353 init_connection_info(&ci);
354 conn = amqp_new_connection();
355 if (ci.ssl) {
356 #ifdef WITH_SSL
357 socket = amqp_ssl_socket_new(conn);
358 if (!socket) {
359 die("creating SSL/TLS socket");
360 }
361 if (amqp_cacert) {
362 amqp_ssl_socket_set_cacert(socket, amqp_cacert);
363 }
364 if (amqp_key) {
365 amqp_ssl_socket_set_key(socket, amqp_cert, amqp_key);
366 }
367 if (!amqp_no_default_cert_paths) {
368 amqp_ssl_socket_enable_default_verify_paths(socket);
369 }
370 #else
371 die("librabbitmq was not built with SSL/TLS support");
372 #endif
373 } else {
374 socket = amqp_tcp_socket_new(conn);
375 if (!socket) {
376 die("creating TCP socket (out of memory)");
377 }
378 }
379 status = amqp_socket_open(socket, ci.host, ci.port);
380 if (status) {
381 die_amqp_error(status, "opening socket to %s:%d", ci.host, ci.port);
382 }
383 die_rpc(amqp_login(conn, ci.vhost, 0, 131072, amqp_heartbeat,
384 AMQP_SASL_METHOD_PLAIN, ci.user, ci.password),
385 "logging in to AMQP server");
386 if (!amqp_channel_open(conn, 1)) {
387 die_rpc(amqp_get_rpc_reply(conn), "opening channel");
388 }
389 return conn;
390 }
391
392 void close_connection(amqp_connection_state_t conn) {
393 int res;
394 die_rpc(amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS), "closing channel");
395 die_rpc(amqp_connection_close(conn, AMQP_REPLY_SUCCESS),
396 "closing connection");
397
398 res = amqp_destroy_connection(conn);
399 die_amqp_error(res, "closing connection");
400 }
401
402 amqp_bytes_t read_all(int fd) {
403 size_t space = 4096;
404 amqp_bytes_t bytes;
405
406 bytes.bytes = malloc(space);
407 bytes.len = 0;
408
409 for (;;) {
410 ssize_t res = read(fd, (char *)bytes.bytes + bytes.len, space - bytes.len);
411 if (res == 0) {
412 break;
413 }
414
415 if (res < 0) {
416 if (errno == EINTR) {
417 continue;
418 }
419
420 die_errno(errno, "reading");
421 }
422
423 bytes.len += res;
424 if (bytes.len == space) {
425 space *= 2;
426 bytes.bytes = realloc(bytes.bytes, space);
427 }
428 }
429
430 return bytes;
431 }
432
433 void write_all(int fd, amqp_bytes_t data) {
434 while (data.len > 0) {
435 ssize_t res = write(fd, data.bytes, data.len);
436 if (res < 0) {
437 die_errno(errno, "write");
438 }
439
440 data.len -= res;
441 data.bytes = (char *)data.bytes + res;
442 }
443 }
444
445 void copy_body(amqp_connection_state_t conn, int fd) {
446 size_t body_remaining;
447 amqp_frame_t frame;
448
449 int res = amqp_simple_wait_frame(conn, &frame);
450 die_amqp_error(res, "waiting for header frame");
451 if (frame.frame_type != AMQP_FRAME_HEADER) {
452 die("expected header, got frame type 0x%X", frame.frame_type);
453 }
454
455 body_remaining = frame.payload.properties.body_size;
456 while (body_remaining) {
457 res = amqp_simple_wait_frame(conn, &frame);
458 die_amqp_error(res, "waiting for body frame");
459 if (frame.frame_type != AMQP_FRAME_BODY) {
460 die("expected body, got frame type 0x%X", frame.frame_type);
461 }
462
463 write_all(fd, frame.payload.body_fragment);
464 body_remaining -= frame.payload.body_fragment.len;
465 }
466 }
467
468 poptContext process_options(int argc, const char **argv,
469 struct poptOption *options, const char *help) {
470 int c;
471 poptContext opts = poptGetContext(NULL, argc, argv, options, 0);
472 poptSetOtherOptionHelp(opts, help);
473
474 while ((c = poptGetNextOpt(opts)) >= 0) {
475 /* no options require explicit handling */
476 }
477
478 if (c < -1) {
479 fprintf(stderr, "%s: %s\n", poptBadOption(opts, POPT_BADOPTION_NOALIAS),
480 poptStrerror(c));
481 poptPrintUsage(opts, stderr, 0);
482 exit(1);
483 }
484
485 return opts;
486 }
487
488 void process_all_options(int argc, const char **argv,
489 struct poptOption *options) {
490 poptContext opts = process_options(argc, argv, options, "[OPTIONS]...");
491 const char *opt = poptPeekArg(opts);
492
493 if (opt) {
494 fprintf(stderr, "unexpected operand: %s\n", opt);
495 poptPrintUsage(opts, stderr, 0);
496 exit(1);
497 }
498
499 poptFreeContext(opts);
500 }
501
502 amqp_bytes_t cstring_bytes(const char *str) {
503 return str ? amqp_cstring_bytes(str) : amqp_empty_bytes;
504 }