1 #include <platform/cbassert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <libconflate/conflate.h>
6 #include "conflate_internal.h"
7 #include "rest.h"
8 
9 /* Randomly generated by a fair dice roll */
10 #define INITIALIZATION_MAGIC 142285011
11 #define HTTP_PREFIX "HTTP:"
12 
13 void run_conflate(void *);
14 
15 
dup_conf(conflate_config_t c)16 conflate_config_t* dup_conf(conflate_config_t c) {
17     conflate_config_t *rv = calloc(sizeof(conflate_config_t), 1);
18     cb_assert(rv);
19 
20     rv->jid = safe_strdup(c.jid);
21     rv->pass = safe_strdup(c.pass);
22     if (c.host) {
23         rv->host = safe_strdup(c.host);
24     }
25     rv->software = safe_strdup(c.software);
26     rv->version = safe_strdup(c.version);
27     rv->save_path = safe_strdup(c.save_path);
28     rv->userdata = c.userdata;
29     rv->log = c.log;
30     rv->new_config = c.new_config;
31 
32     rv->initialization_marker = (void*)INITIALIZATION_MAGIC;
33 
34     return rv;
35 }
36 
init_conflate(conflate_config_t *conf)37 void init_conflate(conflate_config_t *conf)
38 {
39     cb_assert(conf);
40     memset(conf, 0x00, sizeof(conflate_config_t));
41     conf->log = conflate_stderr_logger;
42     conf->initialization_marker = (void*)INITIALIZATION_MAGIC;
43 }
44 
start_conflate(conflate_config_t conf)45 bool start_conflate(conflate_config_t conf) {
46     conflate_handle_t *handle;
47     void (*run_func)(void*) = NULL;
48 
49     /* Don't start if we don't believe initialization has occurred. */
50     if (conf.initialization_marker != (void*)INITIALIZATION_MAGIC) {
51         cb_assert(conf.initialization_marker == (void*)INITIALIZATION_MAGIC);
52         return false;
53     }
54 
55     handle = calloc(1, sizeof(conflate_handle_t));
56     cb_assert(handle);
57 
58     if (strncmp(HTTP_PREFIX, conf.host, strlen(HTTP_PREFIX))) {
59         run_func = &run_rest_conflate;
60     } else {
61         run_func = &run_conflate;
62         conflate_init_commands();
63     }
64 
65     handle->conf = dup_conf(conf);
66 
67     if (cb_create_thread(&handle->thread, run_func, handle, 1) == 0) {
68         return true;
69     } else {
70         perror("Failed to create thread");
71     }
72 
73     return false;
74 }
75