File: ctrl_dbus.c

package info (click to toggle)
baresip 1.1.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,328 kB
  • sloc: ansic: 53,606; cpp: 2,268; makefile: 332; objc: 320; python: 259; sh: 40; xml: 19
file content (482 lines) | stat: -rw-r--r-- 10,260 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
/**
 * @file ctrl_dbus.c  DBUS interface for baresip
 *
 * Communication channel to control and monitor Baresip via DBUS.
 *
 * It receives commands to be executed and notifies about events.
 *
 * DBUS slots:
 * invoke
 * - command (string) : Command to be executed with appended parameters. Use a
 *   blank to separate the command from its parameters! Multiple parameters are
 *   often separated by commas. But this depends on the implementation of the
 *   command.
 *
 * Returns:
 * - response (string) : The response of the command. Numbers will be converted
 *   to a string. Bool will be converted to "true"/"false".
 *
 * Command example:
 *
 \verbatim
 # With qdbus of Qt.
 qdbus com.github.Baresip /baresip com.github.Baresip.invoke reginfo

 # With gdbus of GLib.
 gdbus call -e -d com.github.Baresip -o /baresip \
	-m com.github.Baresip.invoke reginfo
 \endverbatim
 *
 *
 * Baresip UA events will be converted to DBUS
 * signals:
 *
 * - class     : Event class.
 * - type      : Event ID.
 * - param     : Specific event information. For UA-events param is a JSON
 *   encoded string representation of the UA-event.
 *
 *
 * Example of an UA-event
 *
 * class = "call"
 * type = "CALL_CLOSED"
 * param =
 \verbatim
 {
  "event"      : "true",
  "class"      : "call",
  "type"       : "CALL_CLOSED",
  "param"      : "Connection reset by peer",
  "accountaor" : "sip:alice@atlanta.com",
  "direction"  : "incoming",
  "peeruri"    : "sip:bob@biloxy.com",
  "id"         : "73a12546589651f8"
 }
 \endverbatim
 *
 * SIP messages are converted to DBUS signals
 *
 *
 * Copyright (C) 2020 commend.com - Christian Spielberger
 */

#include <string.h>
#include <stdint.h>
#include <unistd.h>
#include <re.h>
#include <baresip.h>
#include "baresipbus.h"


/**
 * @defgroup ctrl_dbus ctrl_dbus
 *
 */


struct ctrl_st {
	pthread_t tid;              /**< Thread ID of main loop  */
	GMainLoop *loop;            /**< Main loop               */
	bool run;                   /**< Main loop run flag      */

	guint bus_owner;            /**< Handle of dbus owner    */
	DBusBaresip *interface;     /**< dbus interface          */

	char *command;              /**< Current command                     */
	int fd[2];                  /**< Pipe file descriptors for wake-up   */
	struct mbuf *mb;            /**< Command response buffer             */

	struct {
		pthread_mutex_t mutex;
		pthread_cond_t cond;
	} wait;
};

static struct ctrl_st *m_st = NULL;

static int print_handler(const char *p, size_t size, void *arg)
{
	struct mbuf *mb = arg;

	return mbuf_write_mem(mb, (uint8_t *)p, size);
}


static void command_handler(int flags, void *arg)
{
	struct ctrl_st *st = arg;
	char buf[1];
	ssize_t n = 0;

	if (!st->command)
		goto out;

	st->mb = mbuf_alloc(128);
	struct re_printf pf = {print_handler, st->mb};
	int err;
	size_t len = strlen(st->command);

	if (len == 1) {
		/* Relay message to key commands */
		err = cmd_process(baresip_commands(),
					   NULL,
					   st->command[0],
					   &pf, NULL);
	}
	else {
		/* Relay message to long commands */
		err = cmd_process_long(baresip_commands(),
					   st->command,
					   len,
					   &pf, NULL);
	}

	if (err)
		warning("ctrl_dbus: error processing command (%m)\n", err);

	mbuf_set_pos(st->mb, 0);
	st->command = mem_deref(st->command);

out:
	pthread_mutex_lock(&st->wait.mutex);
	pthread_cond_signal(&st->wait.cond);
	n = read(st->fd[0], buf, sizeof(buf));

	pthread_mutex_unlock(&st->wait.mutex);

	if (n != 1) {
		warning("ctrl_dbus: detected a pipe error during read\n");
		info("ctrl_dbus: stopping here\n");
		st->run = false;
		g_main_loop_quit(st->loop);
	}
}


static gboolean
on_handle_invoke(DBusBaresip *interface,
		GDBusMethodInvocation *invocation,
		const gchar *command,
		gpointer arg)
{
	char *response = "";
	struct ctrl_st *st = arg;
	char buf[1] = {1};
	ssize_t n;
	int err;

	str_dup(&st->command, command);

	pthread_mutex_lock(&st->wait.mutex);
	n = write(st->fd[1], buf, sizeof(buf));
	if (n == 1)
		pthread_cond_wait(&st->wait.cond, &st->wait.mutex);

	pthread_mutex_unlock(&st->wait.mutex);

	if (st->mb) {
		err = mbuf_strdup(st->mb, &response, mbuf_get_left(st->mb));
		if (err)
			warning("ctrl_dbus: could not allocate response (%m)",
					err);

		dbus_baresip_complete_invoke(interface, invocation, response);
		mem_deref(response);
		st->mb = mem_deref(st->mb);
	}
	else {
		dbus_baresip_complete_invoke(interface, invocation,
				n == 1 ? "" : "invoke failed");
	}

	return true;
}


static int send_event(struct ctrl_st *st, const char *eclass,
		const char *etype, const char *param) {

	dbus_baresip_emit_event(st->interface, eclass, etype, param);
	return 0;
}


/*
 * Relay UA events
 */
static void ua_event_handler(struct ua *ua, enum ua_event ev,
			     struct call *call, const char *prm, void *arg)
{
	struct ctrl_st *st = arg;
	struct mbuf *buf;
	struct re_printf pf;
	struct odict *od = NULL;
	int err = 0;
	const struct odict_entry *eclass = NULL;
	const char *etype = uag_event_str(ev);

	if (!st->interface)
		return;

	buf = mbuf_alloc(192);
	err = odict_alloc(&od, 8);
	if (!buf || err)
		goto out;

	pf.vph = print_handler;
	pf.arg = buf;
	err = event_encode_dict(od, ua, ev, call, prm);
	if (err)
		goto out;

	eclass = odict_lookup(od, "class");
	err = json_encode_odict(&pf, od);
	if (err) {
		warning("ctrl_dbus: failed to encode json (%m)\n", err);
		goto out;
	}

	mbuf_write_u8(buf, 0);
	mbuf_set_pos(buf, 0);
	send_event(st, eclass ? eclass->u.str : "other", etype,
			(const char *) mbuf_buf(buf));

 out:
	mem_deref(buf);
	mem_deref(od);
}


static void message_handler(struct ua *ua, const struct pl *peer,
			    const struct pl *ctype,
			    struct mbuf *body, void *arg)
{
	struct ctrl_st *st = arg;
	char *buf1 = NULL;
	char *buf2 = NULL;
	char *buf3 = NULL;
	size_t pos = 0;
	const char *aor = account_aor(ua_account(ua));
	int err = 0;

	if (!st->interface)
		return;

	err |= pl_strdup(&buf1, peer);
	err |= pl_strdup(&buf2, ctype);
	if (body) {
		pos = body->pos;
		err |= mbuf_strdup(body, &buf3, mbuf_get_left(body));
		body->pos = pos;
	}

	if (err) {
		warning("ctrl_dbus: failed to convert SIP message (%m)\n",
				err);
		goto out;
	}

	dbus_baresip_emit_message(st->interface,
			aor ? aor : "",
			buf1, buf2, buf3);

out:
	mem_deref(buf1);
	mem_deref(buf2);
	mem_deref(buf3);
}


static void ctrl_destructor(void *arg)
{
	struct ctrl_st *st = arg;
	if (st->run) {
		st->run = false;
		g_main_loop_quit(st->loop);
		pthread_join(st->tid, NULL);
	}

	if (st == m_st)
		m_st = NULL;

	if (st->bus_owner) {
		g_bus_unown_name(st->bus_owner);
	}

	if (st->interface)
		g_object_unref (st->interface);

	g_main_loop_unref(st->loop);

	pthread_mutex_destroy(&st->wait.mutex);
	pthread_cond_destroy(&st->wait.cond);
}


static void *thread(void *arg)
{
	struct ctrl_st *st = arg;
	int err;

	if (pipe(st->fd) == -1) {
		warning("ctrl_dbus: could not create pipe (%m)\n", errno);
		return NULL;
	}

	err = fd_listen(st->fd[0], FD_READ, command_handler, st);
	if (err) {
		warning("ctrl_dbus: can not listen on pipe (%m)\n", err);
		return NULL;
	}

	st->run = true;
	while (st->run)
		g_main_loop_run(st->loop);

	fd_close(st->fd[0]);
	close(st->fd[0]);
	close(st->fd[1]);
	return NULL;
}


static int ctrl_alloc(struct ctrl_st **stp)
{
	struct ctrl_st *st;
	int err = 0;

	if (!stp)
		return EINVAL;

	st = mem_zalloc(sizeof(*st), ctrl_destructor);
	if (!st)
		return ENOMEM;

	pthread_mutex_init(&st->wait.mutex, NULL);
	pthread_cond_init(&st->wait.cond, NULL);

	st->loop = g_main_loop_new(NULL, false);
	if (!st->loop) {
		err = ENOMEM;
		goto out;
	}

	err = pthread_create(&st->tid, NULL, thread, st);
	if (err)
		st->run = false;

out:
	if (err)
		mem_deref(st);
	else
		*stp = st;

	return err;
}


static void
on_name_acquired(GDBusConnection *connection, const gchar *name, gpointer arg)
{
	GError *error;
	struct ctrl_st *st = arg;

	st->interface = dbus_baresip_skeleton_new();
	g_signal_connect (st->interface, "handle-invoke",
			G_CALLBACK (on_handle_invoke), st);
	error = NULL;
	if (!g_dbus_interface_skeleton_export(
				G_DBUS_INTERFACE_SKELETON (st->interface),
				connection, "/baresip", &error)) {
		warning("ctrl_dbus: dbus interface could not be exported\n");
		g_error_free (error);
	}

	info("ctrl_dbus: dbus interface %s exported\n", name);
	ua_event(NULL, UA_EVENT_CUSTOM, NULL, "ctrl_dbus: "
			"dbus_interface %s exported", name);
}


static void on_bus_aquired (GDBusConnection *connection,
                                      const gchar     *name,
                                      gpointer         arg)
{
	(void) connection;
	(void) arg;
	info("ctrl_dbus: bus aquired name=%s\n", name);
}


static void on_name_lost (GDBusConnection *connection,
                                      const gchar     *name,
                                      gpointer         arg)
{
	struct ctrl_st *st = arg;
	info("ctrl_dbus: dbus name lost %s\n", name);
	if (!st->interface)
		warning("ctrl_dbus: could not export dbus interface\n");
}


static int ctrl_init(void)
{
	int err;
	const char *name;
	const char syst[] = "system";
	struct pl use = {syst, sizeof(syst)};

	err = ctrl_alloc(&m_st);
	if (err)
		goto outerr;

	err = uag_event_register(ua_event_handler, m_st);
	if (err)
		goto outerr;

	err = message_listen(baresip_message(), message_handler, m_st);
	if (err)
		return err;

	(void)conf_get(conf_cur(), "ctrl_dbus_use", &use);
	name = dbus_baresip_interface_info()->name;
	m_st->bus_owner = g_bus_own_name(
			!pl_strcmp(&use, "session") ?
				G_BUS_TYPE_SESSION : G_BUS_TYPE_SYSTEM,
			name, G_BUS_NAME_OWNER_FLAGS_NONE, on_bus_aquired,
			on_name_acquired, on_name_lost, m_st, NULL);

	if (!m_st->bus_owner) {
		warning("ctrl_dbus: could not acquire %s on the %r-bus\n",
				name, &use);
		err = EINVAL;
		goto outerr;
	}

	info("ctrl_dbus: name %s acquired on the %r-bus bus_owner=%u\n",
			name, &use, m_st->bus_owner);
	return 0;

outerr:
	mem_deref(m_st);
	m_st = NULL;
	return err;
}


static int ctrl_close(void)
{
	uag_event_unregister(ua_event_handler);
	message_unlisten(baresip_message(), message_handler);
	m_st = mem_deref(m_st);
	return 0;
}


const struct mod_export DECL_EXPORTS(ctrl_dbus) = {
	"ctrl_dbus",
	"application",
	ctrl_init,
	ctrl_close
};