int main(int ac, char *av[]) { int c; while ((c = getopt(ac, av, "a:b:hRs:v")) != -1) { switch (c) { case 'b': if (sscanf(optarg, "%zu", &g_ctx.block_sz) != 1) usage(av[0]); break; case 'v': g_ctx.verbose = true; break; case 's': if (sscanf(optarg, "%lld", (long long *)&g_ctx.sep.tv_sec) != 1) usage(av[0]); break; case 'a': if (parse_addr(optarg, g_ctx.addr, sizeof g_ctx.addr, &g_ctx.port)) usage(av[0]); break; case 'h': default: usage(av[0]); } } /* Initialize libevent and evcoap machinery. */ con_err_ifm (proxy_init(), "evcoap initialization failed"); /* Bind configured addresses. */ con_err_ifm (proxy_bind(), "proxy socket setup failed"); con_err_ifm (ec_register_fb(g_ctx.coap, proxy_req, NULL), "error registering proxy_req"); con_err_ifm (proxy_run(), "proxy failed"); proxy_term(); return EXIT_SUCCESS; err: proxy_term(); return EXIT_FAILURE; }
int proxy_bind(void) { /* Try to bind the requested address. */ con_err_ifm (ec_bind_socket(g_ctx.coap, g_ctx.addr, g_ctx.port), "error binding %s:%u", g_ctx.addr, g_ctx.port); return 0; err: return -1; }
/* Factor out (same code is used by client and server too) */ int parse_addr(const char *ap, char *a, size_t a_sz, uint16_t *p) { int tmp; char *ptr; size_t alen; dbg_return_if (ap == NULL, -1); dbg_return_if (a == NULL, -1); dbg_return_if (a_sz == 0, -1); dbg_return_if (p == NULL, -1); /* Extract port, if specified. */ if ((ptr = strchr(ap, '+')) != NULL && ptr[1] != '\0') { con_err_ifm (u_atoi(++ptr, &tmp), "could not parse port %s", ptr); con_err_ifm (tmp > UINT16_MAX || tmp <= 0, "Bad port %d", tmp); *p = (uint16_t) tmp; } else { ptr = (char *)(ap + strlen(ap) + 1); *p = EC_COAP_DEFAULT_PORT; } alen = (size_t)(ptr - ap - 1); con_err_ifm(alen >= a_sz, "not enough bytes (%zu vs %zu) to copy %s", alen, a_sz, ap); (void) strncpy(a, ap, alen); a[alen] = '\0'; return 0; err: return -1; }
int main(int argc, char **argv) { int rc = 0; memset(ctx, 0, sizeof(context_t)); /* parse command line parameters (and set ctx vars) */ dbg_err_if(parse_opt(argc, argv)); if(getenv("GATEWAY_INTERFACE")) ctx->cgi = 1; /* load config and initialize */ warn_err_ifm(app_init(), "kloned init error (more info in the log file)"); #ifdef HAVE_FORK /* daemonize if not -F */ if(ctx->daemon && !ctx->cgi) con_err_ifm(daemon(ctx->nochdir, 0), "daemon error"); #endif /* HAVE_FORK */ /* save the PID in a file */ if(ctx->pid_file) dbg_err_if(u_savepid(ctx->pid_file)); /* jump to the main loop */ rc = app_run(); dbg_err_if(app_term()); /* if debugging then call exit(3) because it's needed to gprof to dump its stats file (gmon.out) */ if(ctx->debug) return rc; /* don't use return because exit(3) will be called and we don't want FILE* buffers to be automatically flushed (klog_file_t will write same lines more times, once by the parent process and N times by any child created when FILE buffer was not empty) */ _exit(rc); err: app_term(); if(ctx->debug) return ~0; _exit(EXIT_FAILURE); }