blob: 758884dffd6f2baff588f2c271b142761338ba5c [file] [log] [blame]
Max5d42b8e2019-02-07 17:28:01 +01001/* Generic client structure and related helpers */
2
3/* (C) 2018 by Harald Welte <laforge@gnumonks.org>
4 * (C) 2019 by sysmocom - s.f.m.c. GmbH.
5 * All Rights Reserved.
6 *
7 * SPDX-License-Identifier: GPL-2.0+
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
22 * MA 02110-1301, USA.
23 */
24
25#include <stdbool.h>
26#include <string.h>
27#include <talloc.h>
28
29#include <osmocom/core/utils.h>
Max9a852f22019-01-31 15:58:57 +010030#include <osmocom/netif/stream.h>
Max5d42b8e2019-02-07 17:28:01 +010031
32#include "client.h"
33
34bool match_config(const struct host_cfg *cfg, const char *match, enum match_kind k)
35{
36 bool m_name = (strcmp(match, cfg->name) == 0),
37 m_host = (strcmp(match, cfg->remote_host) == 0);
38
39 switch (k) {
40 case MATCH_NAME:
41 return m_name;
42 case MATCH_HOST:
43 return m_host;
44 case MATCH_EITHER:
45 return m_name | m_host;
46 case MATCH_BOTH:
47 return m_name & m_host;
48 default:
49 return false;
50 }
51
52 return false;
53}
54
55struct host_cfg *host_cfg_alloc(void *ctx, const char *name, const char *host, uint16_t port)
56{
57 struct host_cfg *cfg = talloc_zero(ctx, struct host_cfg);
58 if (!cfg)
59 return NULL;
60
61 cfg->name = talloc_strdup(cfg, name);
62 cfg->remote_host = talloc_strdup(cfg, host);
63 cfg->remote_port = port;
64
65 return cfg;
66}
67
68char *make_authority(void *ctx, const struct host_cfg *cfg)
69{
70 if (!cfg->remote_host)
71 return NULL;
72
73 return talloc_asprintf(ctx, "%s:%u", cfg->remote_host, cfg->remote_port);
74}
Max9a852f22019-01-31 15:58:57 +010075
76struct osmo_stream_cli *make_tcp_client(struct host_cfg *cfg)
77{
78 struct osmo_stream_cli *cl = osmo_stream_cli_create(cfg);
79 if (cl) {
80 osmo_stream_cli_set_addr(cl, cfg->remote_host);
81 osmo_stream_cli_set_port(cl, cfg->remote_port);
82 }
83
84 return cl;
85}
86
87void update_name(struct host_cfg *cfg, const char *new_name)
88{
89 osmo_talloc_replace_string(cfg, (char **)&cfg->name, new_name);
90}
91
92void update_host(struct host_cfg *cfg, const char *new_host)
93{
94 osmo_talloc_replace_string(cfg, (char **)&cfg->remote_host, new_host);
95}