int module_load(const char *modules_path) { DIR *dir = opendir(modules_path); struct dirent *ent = NULL; void *module_handle = NULL; void (*module_init)() = NULL; if (dir == NULL) { log_error("%s","Error loading modules!\n"); return -1; } char file_path[256]; while ((ent = readdir(dir)) != NULL) { module_t *module = NULL; if (strcmp(ent->d_name, ".") == 0 || strcmp(ent->d_name, "..") == 0) continue; sprintf(file_path, "%s%s/%s%s.so", modules_path, ent->d_name, MODULES_PREFIX, ent->d_name); if (!fs_file_exists(file_path)) { log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. No such file!\n"); continue; } module_handle = dlopen(file_path, RTLD_LAZY); if (module_handle == NULL) { log_error("%s%s%s","Error loading mod_", ent->d_name, ".so. Invalid module!\n"); continue; } module_init = dlsym(module_handle, "init"); if (module_init == NULL) { log_error("%s%s%s","Module mod_", ent->d_name, ".so doesn`t have a init function. Ignoring...!\n"); dlclose(module_handle); continue; } log_message("%s%s\n","Loading module: mod_", ent->d_name); num_modules++; modules = util_alloc(modules, num_modules * sizeof(*module)); if (modules != NULL) { module_init(); module = malloc(sizeof(*module)); if (module != NULL) { module->name = malloc(strlen(ent->d_name) + strlen(MODULES_PREFIX) + 1); sprintf(module->name, "%s%s", MODULES_PREFIX, ent->d_name); module->handle = module_handle; modules[num_modules-1] = module; continue; } } log_message("%s%s\n", "Error allocating memory for module mod_", ent->d_name); dlclose(module_handle); num_modules--; return -1; } closedir(dir); return 0; }
static enum SCP_SERVER_STATES_E _scp_v1s_mng_check_response(struct SCP_CONNECTION *c, struct SCP_SESSION *s) { tui32 version; tui32 size; tui16 cmd; // tui8 dim; // char buf[257]; init_stream(c->in_s, c->in_s->size); if (0 != scp_tcp_force_recv(c->in_sck, c->in_s->data, 8)) { log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: network error", __LINE__); return SCP_SERVER_STATE_NETWORK_ERR; } in_uint32_be(c->in_s, version); if (version != 1) { log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: version error", __LINE__); return SCP_SERVER_STATE_VERSION_ERR; } in_uint32_be(c->in_s, size); init_stream(c->in_s, c->in_s->size); /* read the rest of the packet */ if (0 != scp_tcp_force_recv(c->in_sck, c->in_s->data, size - 8)) { log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: network error", __LINE__); return SCP_SERVER_STATE_NETWORK_ERR; } in_uint16_be(c->in_s, cmd); if (cmd != SCP_COMMAND_SET_MANAGE) { log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: sequence error", __LINE__); return SCP_SERVER_STATE_SEQUENCE_ERR; } in_uint16_be(c->in_s, cmd); if (cmd == SCP_CMD_MNG_LIST_REQ) /* request session list */ { log_message(LOG_LEVEL_INFO, "[v1s_mng:%d] request session list", __LINE__); return SCP_SERVER_STATE_MNG_LISTREQ; } else if (cmd == SCP_CMD_MNG_ACTION) /* execute an action */ { /*in_uint8(c->in_s, dim); buf[dim]='\0'; in_uint8a(c->in_s, buf, dim); scp_session_set_errstr(s, buf);*/ log_message(LOG_LEVEL_INFO, "[v1s_mng:%d] action request", __LINE__); return SCP_SERVER_STATE_MNG_ACTION; } /* else if (cmd == 20) / * password change * / { in_uint16_be(c->in_s, s->display); return SCP_SERVER_STATE_OK; } else if (cmd == 40) / * session list * / { return SCP_SERVER_STATE_SESSION_LIST; }*/ log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: sequence error", __LINE__); return SCP_SERVER_STATE_SEQUENCE_ERR; }
int8_t http_send_message(char *msg_out, char **msg_in) { CURLcode res; curl_easy_setopt(curl, CURLOPT_POSTFIELDS, msg_out); http_c.header_list = NULL; http_c.header_list = curl_slist_append(http_c.header_list, "Accept:"); if (!http_c.header_list) return -1; http_c.header_list = curl_slist_append(http_c.header_list, "User-Agent: easycwmp"); if (!http_c.header_list) return -1; http_c.header_list = curl_slist_append(http_c.header_list, "Content-Type: text/html; charset=utf-8"); if (!http_c.header_list) return -1; if (config->acs->http100continue_disable) { http_c.header_list = curl_slist_append(http_c.header_list, "Expect:"); if (!http_c.header_list) return -1; } if (msg_out) { curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long) strlen(msg_out)); http_c.header_list = curl_slist_append(http_c.header_list, "SOAPAction;"); if (!http_c.header_list) return -1; } else { curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, 0); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, http_c.header_list); curl_easy_setopt(curl, CURLOPT_WRITEDATA, msg_in); *msg_in = (char *) calloc (1, sizeof(char)); res = curl_easy_perform(curl); if (http_c.header_list) { curl_slist_free_all(http_c.header_list); http_c.header_list = NULL; } if (!strlen(*msg_in)) { FREE(*msg_in); } long httpCode = 0; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode); if (res || (httpCode != 200 && httpCode != 204)) { log_message(NAME, L_NOTICE, "sending http message failed\n"); return -1; } if (*msg_in) { DDF("+++ RECEIVED HTTP RESPONSE +++\n"); DDF("%s", *msg_in); DDF("--- RECEIVED HTTP RESPONSE ---\n"); } else { DDF("+++ RECEIVED EMPTY HTTP RESPONSE +++\n"); } return 0; }
void DEFAULT_CC scp_v1_process(struct SCP_CONNECTION *c, struct SCP_SESSION *s) { long data; int display; int retries; int current_try; enum SCP_SERVER_STATES_E e; struct SCP_DISCONNECTED_SESSION *slist; struct session_item *sitem; int scount; SCP_SID sid; retries = g_cfg->sec.login_retry; current_try = retries; data = auth_userpass(s->username, s->password,NULL); /*LOG_DBG("user: %s\npass: %s", s->username, s->password);*/ while ((!data) && ((retries == 0) || (current_try > 0))) { LOG_DBG("data %d - retry %d - currenttry %d - expr %d", data, retries, current_try, ((!data) && ((retries == 0) || (current_try > 0)))); e = scp_v1s_request_password(c, s, "Wrong username and/or password"); switch (e) { case SCP_SERVER_STATE_OK: /* all ok, we got new username and password */ data = auth_userpass(s->username, s->password,NULL); /* one try less */ if (current_try > 0) { current_try--; } break; default: /* we check the other errors */ parseCommonStates(e, "scp_v1s_list_sessions()"); scp_session_destroy(s); return; //break; } } if (!data) { scp_v1s_deny_connection(c, "Login failed"); log_message( LOG_LEVEL_INFO, "Login failed for user %s. Connection terminated", s->username); scp_session_destroy(s); return; } /* testing if login is allowed*/ if (0 == access_login_allowed(s->username)) { scp_v1s_deny_connection(c, "Access to Terminal Server not allowed."); log_message(LOG_LEVEL_INFO, "User %s not allowed on TS. Connection terminated", s->username); scp_session_destroy(s); return; } //check if we need password change /* list disconnected sessions */ slist = session_get_byuser(s->username, &scount, SESMAN_SESSION_STATUS_DISCONNECTED); if (scount == 0) { /* no disconnected sessions - start a new one */ log_message(LOG_LEVEL_DEBUG, "No disconnected sessions for this user" "- we create a new one"); if (0 != s->client_ip) { log_message(LOG_LEVEL_INFO, "++ created session (access granted): username %s, ip %s", s->username, s->client_ip); } else { log_message(LOG_LEVEL_INFO, "++ created session (access granted): username %s", s->username); } if (SCP_SESSION_TYPE_XVNC == s->type) { log_message(LOG_LEVEL_INFO, "starting Xvnc session..."); display = session_start(s->width, s->height, s->bpp, s->username, s->password, data, SESMAN_SESSION_TYPE_XVNC, s->domain, s->program, s->directory, s->client_ip); } else { log_message(LOG_LEVEL_INFO, "starting X11rdp session..."); display = session_start(s->width, s->height, s->bpp, s->username, s->password, data, SESMAN_SESSION_TYPE_XRDP, s->domain, s->program, s->directory, s->client_ip); } e = scp_v1s_connect_new_session(c, display); switch (e) { case SCP_SERVER_STATE_OK: /* all ok, we got new username and password */ break; default: /* we check the other errors */ parseCommonStates(e, "scp_v1s_connect_new_session()"); break; } } else { /* one or more disconnected sessions - listing */ e = scp_v1s_list_sessions(c, scount, slist, &sid); switch (e) { /*case SCP_SERVER_STATE_FORCE_NEW:*/ /* we should check for MaxSessions */ case SCP_SERVER_STATE_SELECTION_CANCEL: log_message( LOG_LEVEL_INFO, "Connection cancelled after session listing"); break; case SCP_SERVER_STATE_OK: /* ok, reconnecting... */ sitem = session_get_bypid(sid); if (0 == sitem) { e = scp_v1s_connection_error(c, "Internal error"); log_message(LOG_LEVEL_INFO, "Cannot find session item on the chain"); } else { display = sitem->display; /*e=scp_v1s_reconnect_session(c, sitem, display);*/ e = scp_v1s_reconnect_session(c, display); if (0 != s->client_ip) { log_message(LOG_LEVEL_INFO, "++ reconnected session: username %s, display :%d.0, session_pid %d, ip %s", s->username, display, sitem->pid, s->client_ip); } else { log_message(LOG_LEVEL_INFO, "++ reconnected session: username %s, display :%d.0, session_pid %d", s->username, display, sitem->pid); } g_free(sitem); } break; default: /* we check the other errors */ parseCommonStates(e, "scp_v1s_list_sessions()"); break; } } /* resource management */ if ((e == SCP_SERVER_STATE_OK) && (s->rsr)) { /* here goes scp resource sharing code */ } /* cleanup */ scp_session_destroy(s); auth_end(data); g_free(slist); }
// main application int main(int argc, char *argv[]) { // first set some default values app_cfg.tts_file = "play.wav"; app_cfg.record_call = 0; app_cfg.repetition_limit = 3; app_cfg.silent_mode = 0; app_cfg.sip_realm = "*"; // parse arguments if (argc > 1) { int arg; for( arg = 1; arg < argc; arg+=2 ) { // check if usage info needs to be displayed if (!strcasecmp(argv[arg], "--help")) { // display usage info and exit app usage(0); exit(0); } // check for sip domain if (try_get_argument(arg, "-sd", &app_cfg.sip_domain, argc, argv) == 1) { continue; } // check for sip realm if (try_get_argument(arg, "-sr", &app_cfg.sip_realm, argc, argv) == 1) { continue; } // check for sip user if (try_get_argument(arg, "-su", &app_cfg.sip_user, argc, argv) == 1) { continue; } // check for sip password if (try_get_argument(arg, "-sp", &app_cfg.sip_password, argc, argv) == 1) { continue; } // check for target phone number if (try_get_argument(arg, "-pn", &app_cfg.phone_number, argc, argv) == 1) { continue; } // check for text to speak if (try_get_argument(arg, "-tts", &app_cfg.tts, argc, argv) == 1) { continue; } // check for wave file to play (no tts) if (try_get_argument(arg, "-wav", &app_cfg.wav_file, argc, argv) == 1) { continue; } // check for record call option if (try_get_argument(arg, "-ttsf", &app_cfg.tts_file, argc, argv) == 1) { continue; } // check for record call option if (try_get_argument(arg, "-rcf", &app_cfg.record_file, argc, argv) == 1) { app_cfg.record_call = 1; continue; } // check for message repetition option char *mr; if (try_get_argument(arg, "-mr", &mr, argc, argv) == 1) { app_cfg.repetition_limit = atoi(mr); continue; } // check for silent mode option char *s; try_get_argument(arg, "-s", &s, argc, argv); if (!strcasecmp(s, "1")) { app_cfg.silent_mode = 1; continue; } } } else { // no arguments specified - display usage info and exit app usage(1); exit(1); } if (!app_cfg.sip_domain || !app_cfg.sip_user || !app_cfg.sip_password || !app_cfg.phone_number || !(app_cfg.tts || app_cfg.wav_file)) { // too few arguments specified - display usage info and exit app usage(1); exit(1); } // print infos log_message("SIP Call - Simple TTS-based Automated Calls\n"); log_message("===========================================\n"); // register signal handler for break-in-keys (e.g. ctrl+c) signal(SIGINT, signal_handler); signal(SIGKILL, signal_handler); if (!app_cfg.wav_file) { // synthesize speech synthesize_speech(app_cfg.tts_file); } // setup up sip library pjsua setup_sip(); // create account and register to sip server register_sip(); // Short delay beetween registering and calling pj_thread_sleep(500); // initiate call make_sip_call(); // app loop for (;;) { pj_thread_sleep(100); } // exit app app_exit(); return 0; }
int ocsp_main(int argc, char **argv) { BIO *acbio = NULL, *cbio = NULL, *derbio = NULL, *out = NULL; const EVP_MD *cert_id_md = NULL, *rsign_md = NULL; STACK_OF(OPENSSL_STRING) *rsign_sigopts = NULL; int trailing_md = 0; CA_DB *rdb = NULL; EVP_PKEY *key = NULL, *rkey = NULL; OCSP_BASICRESP *bs = NULL; OCSP_REQUEST *req = NULL; OCSP_RESPONSE *resp = NULL; STACK_OF(CONF_VALUE) *headers = NULL; STACK_OF(OCSP_CERTID) *ids = NULL; STACK_OF(OPENSSL_STRING) *reqnames = NULL; STACK_OF(X509) *sign_other = NULL, *verify_other = NULL, *rother = NULL; STACK_OF(X509) *issuers = NULL; X509 *issuer = NULL, *cert = NULL; STACK_OF(X509) *rca_cert = NULL; X509 *signer = NULL, *rsigner = NULL; X509_STORE *store = NULL; X509_VERIFY_PARAM *vpm = NULL; const char *CAfile = NULL, *CApath = NULL; char *header, *value; char *host = NULL, *port = NULL, *path = "/", *outfile = NULL; char *rca_filename = NULL, *reqin = NULL, *respin = NULL; char *reqout = NULL, *respout = NULL, *ridx_filename = NULL; char *rsignfile = NULL, *rkeyfile = NULL; char *sign_certfile = NULL, *verify_certfile = NULL, *rcertfile = NULL; char *signfile = NULL, *keyfile = NULL; char *thost = NULL, *tport = NULL, *tpath = NULL; int noCAfile = 0, noCApath = 0; int accept_count = -1, add_nonce = 1, noverify = 0, use_ssl = -1; int vpmtouched = 0, badsig = 0, i, ignore_err = 0, nmin = 0, ndays = -1; int req_text = 0, resp_text = 0, ret = 1; int req_timeout = -1; long nsec = MAX_VALIDITY_PERIOD, maxage = -1; unsigned long sign_flags = 0, verify_flags = 0, rflags = 0; OPTION_CHOICE o; reqnames = sk_OPENSSL_STRING_new_null(); if (reqnames == NULL) goto end; ids = sk_OCSP_CERTID_new_null(); if (ids == NULL) goto end; if ((vpm = X509_VERIFY_PARAM_new()) == NULL) return 1; prog = opt_init(argc, argv, ocsp_options); while ((o = opt_next()) != OPT_EOF) { switch (o) { case OPT_EOF: case OPT_ERR: opthelp: BIO_printf(bio_err, "%s: Use -help for summary.\n", prog); goto end; case OPT_HELP: ret = 0; opt_help(ocsp_options); goto end; case OPT_OUTFILE: outfile = opt_arg(); break; case OPT_TIMEOUT: #ifndef OPENSSL_NO_SOCK req_timeout = atoi(opt_arg()); #endif break; case OPT_URL: OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); thost = tport = tpath = NULL; if (!OCSP_parse_url(opt_arg(), &host, &port, &path, &use_ssl)) { BIO_printf(bio_err, "%s Error parsing URL\n", prog); goto end; } thost = host; tport = port; tpath = path; break; case OPT_HOST: host = opt_arg(); break; case OPT_PORT: port = opt_arg(); break; case OPT_IGNORE_ERR: ignore_err = 1; break; case OPT_NOVERIFY: noverify = 1; break; case OPT_NONCE: add_nonce = 2; break; case OPT_NO_NONCE: add_nonce = 0; break; case OPT_RESP_NO_CERTS: rflags |= OCSP_NOCERTS; break; case OPT_RESP_KEY_ID: rflags |= OCSP_RESPID_KEY; break; case OPT_NO_CERTS: sign_flags |= OCSP_NOCERTS; break; case OPT_NO_SIGNATURE_VERIFY: verify_flags |= OCSP_NOSIGS; break; case OPT_NO_CERT_VERIFY: verify_flags |= OCSP_NOVERIFY; break; case OPT_NO_CHAIN: verify_flags |= OCSP_NOCHAIN; break; case OPT_NO_CERT_CHECKS: verify_flags |= OCSP_NOCHECKS; break; case OPT_NO_EXPLICIT: verify_flags |= OCSP_NOEXPLICIT; break; case OPT_TRUST_OTHER: verify_flags |= OCSP_TRUSTOTHER; break; case OPT_NO_INTERN: verify_flags |= OCSP_NOINTERN; break; case OPT_BADSIG: badsig = 1; break; case OPT_TEXT: req_text = resp_text = 1; break; case OPT_REQ_TEXT: req_text = 1; break; case OPT_RESP_TEXT: resp_text = 1; break; case OPT_REQIN: reqin = opt_arg(); break; case OPT_RESPIN: respin = opt_arg(); break; case OPT_SIGNER: signfile = opt_arg(); break; case OPT_VAFILE: verify_certfile = opt_arg(); verify_flags |= OCSP_TRUSTOTHER; break; case OPT_SIGN_OTHER: sign_certfile = opt_arg(); break; case OPT_VERIFY_OTHER: verify_certfile = opt_arg(); break; case OPT_CAFILE: CAfile = opt_arg(); break; case OPT_CAPATH: CApath = opt_arg(); break; case OPT_NOCAFILE: noCAfile = 1; break; case OPT_NOCAPATH: noCApath = 1; break; case OPT_V_CASES: if (!opt_verify(o, vpm)) goto end; vpmtouched++; break; case OPT_VALIDITY_PERIOD: opt_long(opt_arg(), &nsec); break; case OPT_STATUS_AGE: opt_long(opt_arg(), &maxage); break; case OPT_SIGNKEY: keyfile = opt_arg(); break; case OPT_REQOUT: reqout = opt_arg(); break; case OPT_RESPOUT: respout = opt_arg(); break; case OPT_PATH: path = opt_arg(); break; case OPT_ISSUER: issuer = load_cert(opt_arg(), FORMAT_PEM, "issuer certificate"); if (issuer == NULL) goto end; if (issuers == NULL) { if ((issuers = sk_X509_new_null()) == NULL) goto end; } sk_X509_push(issuers, issuer); break; case OPT_CERT: X509_free(cert); cert = load_cert(opt_arg(), FORMAT_PEM, "certificate"); if (cert == NULL) goto end; if (cert_id_md == NULL) cert_id_md = EVP_sha1(); if (!add_ocsp_cert(&req, cert, cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; trailing_md = 0; break; case OPT_SERIAL: if (cert_id_md == NULL) cert_id_md = EVP_sha1(); if (!add_ocsp_serial(&req, opt_arg(), cert_id_md, issuer, ids)) goto end; if (!sk_OPENSSL_STRING_push(reqnames, opt_arg())) goto end; trailing_md = 0; break; case OPT_INDEX: ridx_filename = opt_arg(); break; case OPT_CA: rca_filename = opt_arg(); break; case OPT_NMIN: opt_int(opt_arg(), &nmin); if (ndays == -1) ndays = 0; break; case OPT_REQUEST: opt_int(opt_arg(), &accept_count); break; case OPT_NDAYS: ndays = atoi(opt_arg()); break; case OPT_RSIGNER: rsignfile = opt_arg(); break; case OPT_RKEY: rkeyfile = opt_arg(); break; case OPT_ROTHER: rcertfile = opt_arg(); break; case OPT_RMD: /* Response MessageDigest */ if (!opt_md(opt_arg(), &rsign_md)) goto end; break; case OPT_RSIGOPT: if (rsign_sigopts == NULL) rsign_sigopts = sk_OPENSSL_STRING_new_null(); if (rsign_sigopts == NULL || !sk_OPENSSL_STRING_push(rsign_sigopts, opt_arg())) goto end; break; case OPT_HEADER: header = opt_arg(); value = strchr(header, '='); if (value == NULL) { BIO_printf(bio_err, "Missing = in header key=value\n"); goto opthelp; } *value++ = '\0'; if (!X509V3_add_value(header, value, &headers)) goto end; break; case OPT_MD: if (trailing_md) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } if (!opt_md(opt_unknown(), &cert_id_md)) goto opthelp; trailing_md = 1; break; case OPT_MULTI: # ifdef OCSP_DAEMON multi = atoi(opt_arg()); # endif break; } } if (trailing_md) { BIO_printf(bio_err, "%s: Digest must be before -cert or -serial\n", prog); goto opthelp; } argc = opt_num_rest(); if (argc != 0) goto opthelp; /* Have we anything to do? */ if (req == NULL && reqin == NULL && respin == NULL && !(port != NULL && ridx_filename != NULL)) goto opthelp; out = bio_open_default(outfile, 'w', FORMAT_TEXT); if (out == NULL) goto end; if (req == NULL && (add_nonce != 2)) add_nonce = 0; if (req == NULL && reqin != NULL) { derbio = bio_open_default(reqin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; req = d2i_OCSP_REQUEST_bio(derbio, NULL); BIO_free(derbio); if (req == NULL) { BIO_printf(bio_err, "Error reading OCSP request\n"); goto end; } } if (req == NULL && port != NULL) { acbio = init_responder(port); if (acbio == NULL) goto end; } if (rsignfile != NULL) { if (rkeyfile == NULL) rkeyfile = rsignfile; rsigner = load_cert(rsignfile, FORMAT_PEM, "responder certificate"); if (rsigner == NULL) { BIO_printf(bio_err, "Error loading responder certificate\n"); goto end; } if (!load_certs(rca_filename, &rca_cert, FORMAT_PEM, NULL, "CA certificate")) goto end; if (rcertfile != NULL) { if (!load_certs(rcertfile, &rother, FORMAT_PEM, NULL, "responder other certificates")) goto end; } rkey = load_key(rkeyfile, FORMAT_PEM, 0, NULL, NULL, "responder private key"); if (rkey == NULL) goto end; } if (ridx_filename != NULL && (rkey == NULL || rsigner == NULL || rca_cert == NULL)) { BIO_printf(bio_err, "Responder mode requires certificate, key, and CA.\n"); goto end; } if (ridx_filename != NULL) { rdb = load_index(ridx_filename, NULL); if (rdb == NULL || index_index(rdb) <= 0) { ret = 1; goto end; } } # ifdef OCSP_DAEMON if (multi && acbio != NULL) spawn_loop(); if (acbio != NULL && req_timeout > 0) signal(SIGALRM, sock_timeout); #endif if (acbio != NULL) log_message(LOG_INFO, "waiting for OCSP client connections..."); redo_accept: if (acbio != NULL) { # ifdef OCSP_DAEMON if (index_changed(rdb)) { CA_DB *newrdb = load_index(ridx_filename, NULL); if (newrdb != NULL && index_index(newrdb) > 0) { free_index(rdb); rdb = newrdb; } else { free_index(newrdb); log_message(LOG_ERR, "error reloading updated index: %s", ridx_filename); } } # endif req = NULL; if (!do_responder(&req, &cbio, acbio, req_timeout)) goto redo_accept; if (req == NULL) { resp = OCSP_response_create(OCSP_RESPONSE_STATUS_MALFORMEDREQUEST, NULL); send_ocsp_response(cbio, resp); goto done_resp; } } if (req == NULL && (signfile != NULL || reqout != NULL || host != NULL || add_nonce || ridx_filename != NULL)) { BIO_printf(bio_err, "Need an OCSP request for this operation!\n"); goto end; } if (req != NULL && add_nonce) OCSP_request_add1_nonce(req, NULL, -1); if (signfile != NULL) { if (keyfile == NULL) keyfile = signfile; signer = load_cert(signfile, FORMAT_PEM, "signer certificate"); if (signer == NULL) { BIO_printf(bio_err, "Error loading signer certificate\n"); goto end; } if (sign_certfile != NULL) { if (!load_certs(sign_certfile, &sign_other, FORMAT_PEM, NULL, "signer certificates")) goto end; } key = load_key(keyfile, FORMAT_PEM, 0, NULL, NULL, "signer private key"); if (key == NULL) goto end; if (!OCSP_request_sign (req, signer, key, NULL, sign_other, sign_flags)) { BIO_printf(bio_err, "Error signing OCSP request\n"); goto end; } } if (req_text && req != NULL) OCSP_REQUEST_print(out, req, 0); if (reqout != NULL) { derbio = bio_open_default(reqout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; i2d_OCSP_REQUEST_bio(derbio, req); BIO_free(derbio); } if (rdb != NULL) { make_ocsp_response(bio_err, &resp, req, rdb, rca_cert, rsigner, rkey, rsign_md, rsign_sigopts, rother, rflags, nmin, ndays, badsig); if (cbio != NULL) send_ocsp_response(cbio, resp); } else if (host != NULL) { # ifndef OPENSSL_NO_SOCK resp = process_responder(req, host, path, port, use_ssl, headers, req_timeout); if (resp == NULL) goto end; # else BIO_printf(bio_err, "Error creating connect BIO - sockets not supported.\n"); goto end; # endif } else if (respin != NULL) { derbio = bio_open_default(respin, 'r', FORMAT_ASN1); if (derbio == NULL) goto end; resp = d2i_OCSP_RESPONSE_bio(derbio, NULL); BIO_free(derbio); if (resp == NULL) { BIO_printf(bio_err, "Error reading OCSP response\n"); goto end; } } else { ret = 0; goto end; } done_resp: if (respout != NULL) { derbio = bio_open_default(respout, 'w', FORMAT_ASN1); if (derbio == NULL) goto end; i2d_OCSP_RESPONSE_bio(derbio, resp); BIO_free(derbio); } i = OCSP_response_status(resp); if (i != OCSP_RESPONSE_STATUS_SUCCESSFUL) { BIO_printf(out, "Responder Error: %s (%d)\n", OCSP_response_status_str(i), i); if (!ignore_err) goto end; } if (resp_text) OCSP_RESPONSE_print(out, resp, 0); /* If running as responder don't verify our own response */ if (cbio != NULL) { /* If not unlimited, see if we took all we should. */ if (accept_count != -1 && --accept_count <= 0) { ret = 0; goto end; } BIO_free_all(cbio); cbio = NULL; OCSP_REQUEST_free(req); req = NULL; OCSP_RESPONSE_free(resp); resp = NULL; goto redo_accept; } if (ridx_filename != NULL) { ret = 0; goto end; } if (store == NULL) { store = setup_verify(CAfile, CApath, noCAfile, noCApath); if (!store) goto end; } if (vpmtouched) X509_STORE_set1_param(store, vpm); if (verify_certfile != NULL) { if (!load_certs(verify_certfile, &verify_other, FORMAT_PEM, NULL, "validator certificate")) goto end; } bs = OCSP_response_get1_basic(resp); if (bs == NULL) { BIO_printf(bio_err, "Error parsing response\n"); goto end; } ret = 0; if (!noverify) { if (req != NULL && ((i = OCSP_check_nonce(req, bs)) <= 0)) { if (i == -1) BIO_printf(bio_err, "WARNING: no nonce in response\n"); else { BIO_printf(bio_err, "Nonce Verify error\n"); ret = 1; goto end; } } i = OCSP_basic_verify(bs, verify_other, store, verify_flags); if (i <= 0 && issuers) { i = OCSP_basic_verify(bs, issuers, store, OCSP_TRUSTOTHER); if (i > 0) ERR_clear_error(); } if (i <= 0) { BIO_printf(bio_err, "Response Verify Failure\n"); ERR_print_errors(bio_err); ret = 1; } else { BIO_printf(bio_err, "Response verify OK\n"); } } print_ocsp_summary(out, bs, req, reqnames, ids, nsec, maxage); end: ERR_print_errors(bio_err); X509_free(signer); X509_STORE_free(store); X509_VERIFY_PARAM_free(vpm); sk_OPENSSL_STRING_free(rsign_sigopts); EVP_PKEY_free(key); EVP_PKEY_free(rkey); X509_free(cert); sk_X509_pop_free(issuers, X509_free); X509_free(rsigner); sk_X509_pop_free(rca_cert, X509_free); free_index(rdb); BIO_free_all(cbio); BIO_free_all(acbio); BIO_free_all(out); OCSP_REQUEST_free(req); OCSP_RESPONSE_free(resp); OCSP_BASICRESP_free(bs); sk_OPENSSL_STRING_free(reqnames); sk_OCSP_CERTID_free(ids); sk_X509_pop_free(sign_other, X509_free); sk_X509_pop_free(verify_other, X509_free); sk_CONF_VALUE_pop_free(headers, X509V3_conf_free); OPENSSL_free(thost); OPENSSL_free(tport); OPENSSL_free(tpath); return ret; }
/* manipulate add/remove rs according to alive state */ void perform_svr_state(int alive, virtual_server_t * vs, real_server_t * rs) { /* * | ISALIVE(rs) | alive | context * | 0 | 0 | first check failed under alpha mode, unreachable here * | 0 | 1 | RS went up, add it to the pool * | 1 | 0 | RS went down, remove it from the pool * | 1 | 1 | first check succeeded w/o alpha mode, unreachable here */ if (!ISALIVE(rs) && alive) { log_message(LOG_INFO, "%s service %s to VS %s" , (rs->inhibit) ? "Enabling" : "Adding" , FMT_RS(rs) , FMT_VS(vs)); /* Add only if we have quorum or no sorry server */ if (vs->quorum_state == UP || !vs->s_svr || !ISALIVE(vs->s_svr)) { ipvs_cmd(LVS_CMD_ADD_DEST, check_data->vs_group, vs, rs); } rs->alive = alive; if (rs->notify_up) { log_message(LOG_INFO, "Executing [%s] for service %s in VS %s" , rs->notify_up , FMT_RS(rs) , FMT_VS(vs)); notify_exec(rs->notify_up); } #ifdef _WITH_SNMP_ check_snmp_rs_trap(rs, vs); #endif /* We may have gained quorum */ update_quorum_state(vs); } if (ISALIVE(rs) && !alive) { log_message(LOG_INFO, "%s service %s from VS %s" , (rs->inhibit) ? "Disabling" : "Removing" , FMT_RS(rs) , FMT_VS(vs)); /* server is down, it is removed from the LVS realserver pool * Remove only if we have quorum or no sorry server */ if (vs->quorum_state == UP || !vs->s_svr || !ISALIVE(vs->s_svr)) { ipvs_cmd(LVS_CMD_DEL_DEST, check_data->vs_group, vs, rs); } rs->alive = alive; if (rs->notify_down) { log_message(LOG_INFO, "Executing [%s] for service %s in VS %s" , rs->notify_down , FMT_RS(rs) , FMT_VS(vs)); notify_exec(rs->notify_down); } #ifdef _WITH_SNMP_ check_snmp_rs_trap(rs, vs); #endif /* We may have lost quorum */ update_quorum_state(vs); } }
struct storage_backend * init_storage_rados(const char * connection_string) { #ifndef HAVE_LIBRADOS log_message(STORE_LOGLVL_ERR,"init_storage_rados: Support for rados has not been compiled into this program"); return NULL; #else struct rados_ctx * ctx = malloc(sizeof(struct rados_ctx)); struct storage_backend * store = malloc(sizeof(struct storage_backend)); char * conf = NULL; const char * tmp; int err; int i; if (ctx == NULL) { return NULL; } tmp = &(connection_string[strlen("rados://")]); i = 0; while ((tmp[i] != '/') && (tmp[i] != 0)) i++; ctx->pool = calloc(i + 1, sizeof(char)); memcpy(ctx->pool, tmp, i*sizeof(char)); conf = strdup(&(tmp[i])); err = rados_create(&(ctx->cluster), NULL); if (err < 0) { log_message(STORE_LOGLVL_ERR,"init_storage_rados: cannot create a cluster handle: %s", strerror(-err)); free(ctx); free(store); return NULL; } err = rados_conf_read_file(ctx->cluster, conf); if (err < 0) { log_message(STORE_LOGLVL_ERR,"init_storage_rados: failed to read rados config file %s: %s", conf, strerror(-err)); free(ctx); free(store); return NULL; } pthread_mutex_lock(&qLock); err = rados_connect(ctx->cluster); pthread_mutex_unlock(&qLock); if (err < 0) { log_message(STORE_LOGLVL_ERR,"init_storage_rados: failed to connect to rados cluster: %s", strerror(-err)); free(ctx); free(store); return NULL; } err = rados_ioctx_create(ctx->cluster, ctx->pool, &(ctx->io)); if (err < 0) { log_message(STORE_LOGLVL_ERR,"init_storage_rados: failed to initialise rados io context to pool %s: %s", ctx->pool, strerror(-err)); rados_shutdown(ctx->cluster); free(ctx); free(store); return NULL; } log_message(STORE_LOGLVL_DEBUG,"init_storage_rados: Initialised rados backend for pool %s with config %s", ctx->pool, conf); ctx->metadata_cache.data = malloc(sizeof(struct stat_info) + sizeof(struct meta_layout) + METATILE*METATILE*sizeof(struct entry)); if (ctx->metadata_cache.data == NULL) { rados_ioctx_destroy(ctx->io); rados_shutdown(ctx->cluster); free(ctx); free(store); return NULL; } free(conf); ctx->metadata_cache.x = -1; ctx->metadata_cache.y = -1; ctx->metadata_cache.z = -1; ctx->metadata_cache.xmlname[0] = 0; store->storage_ctx = ctx; store->tile_read = &rados_tile_read; store->tile_stat = &rados_tile_stat; store->metatile_write = &rados_metatile_write; store->metatile_delete = &rados_metatile_delete; store->metatile_expire = &rados_metatile_expire; store->tile_storage_id = &rados_tile_storage_id; store->close_storage = &rados_close_storage; return store; #endif }
/** @brief replace a tring by another * @param source * @param length the length of the source buffer (including '\0') * @param can_realloc Is the source string allocated by a malloc or fixed. The realloc is done only when the dest is bigger * @param toreplace the pattern to replace * @param replacement the replacement string for the pattern */ char *mumu_string_replace(char *source, int *length, int can_realloc, char *toreplace, char *replacement) { char *pospattern; char *reallocresult; char *tempstring=NULL; int lengthpattern; int lengthreplacment; int lengthtempstring; int lengthsource; pospattern=strstr(source,toreplace); if(pospattern==NULL) return source; lengthpattern=strlen(toreplace); lengthreplacment=strlen(replacement); lengthsource=strlen(source); lengthtempstring=lengthsource+1; tempstring=malloc(sizeof(char)*lengthtempstring); if(tempstring==NULL) { log_message(log_module, MSG_ERROR,"Problem with malloc : %s file : %s line %d\n",strerror(errno),__FILE__,__LINE__); return NULL; } strcpy(tempstring,source); pospattern=strstr(tempstring,toreplace); while(pospattern!=NULL) { if(lengthreplacment>lengthpattern) { tempstring=realloc(tempstring,sizeof(char)*(lengthtempstring+lengthreplacment-lengthpattern+1)); if(tempstring==NULL) { log_message(log_module, MSG_ERROR,"Problem with realloc : %s file : %s line %d\n",strerror(errno),__FILE__,__LINE__); return NULL; } pospattern=strstr(tempstring,toreplace); } memmove(pospattern+lengthreplacment,pospattern+lengthpattern,lengthtempstring-((int)(pospattern-tempstring))-lengthpattern); memcpy(pospattern,replacement,lengthreplacment); lengthtempstring+=lengthreplacment-lengthpattern; pospattern=strstr(tempstring,toreplace); } tempstring[lengthtempstring-1]='\0'; if(can_realloc) { if(lengthtempstring>*length) { reallocresult=realloc(source,sizeof(char)*(lengthtempstring)); if(reallocresult==NULL) { log_message(log_module, MSG_ERROR,"Problem with realloc : %s file : %s line %d\n",strerror(errno),__FILE__,__LINE__); return NULL; } source=reallocresult; *length=lengthtempstring; } strcpy(source,tempstring); } else if(lengthtempstring<=*length) { strcpy(source,tempstring); } else { strncpy(source,tempstring,*length-1); source[*length-1]='\0'; } free(tempstring); return source; }
/* mounts, creating the device if needed+possible */ int my_mount(const char *dev, const char *location, const char *fs, int force_rw) { unsigned long flags = MS_MGC_VAL | (force_rw ? 0 : MS_RDONLY); char * opts = NULL; struct stat buf; int rc; if (strcmp(fs, "nfs")) { rc = ensure_dev_exists(dev); if (rc != 0) { log_message("could not create required device file"); return -1; } } log_message("mounting %s on %s as type %s", dev, location, fs); if (stat(location, &buf)) { if (mkdir(location, 0755)) { log_perror("could not create location dir"); return -1; } } else if (!S_ISDIR(buf.st_mode)) { log_message("not a dir %s, will unlink and mkdir", location); if (unlink(location)) { log_perror("could not unlink"); return -1; } if (mkdir(location, 0755)) { log_perror("could not create location dir"); return -1; } } #ifndef DISABLE_MEDIAS if (!strcmp(fs, "vfat")) { my_modprobe("nls_cp437", ANY_DRIVER_TYPE, NULL); my_modprobe("nls_iso8859_1", ANY_DRIVER_TYPE, NULL); my_modprobe("vfat", ANY_DRIVER_TYPE, NULL); opts = (char*)"check=relaxed"; } if (!strcmp(fs, "ntfs")) { my_modprobe("ntfs", ANY_DRIVER_TYPE, NULL); } if (!strcmp(fs, "reiserfs")) my_modprobe("reiserfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "reiser4")) my_modprobe("reiser4", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "jfs")) my_modprobe("jfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "xfs")) my_modprobe("xfs", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "ext4")) my_modprobe("ext4", ANY_DRIVER_TYPE, NULL); if (!strcmp(fs, "btrfs")) my_modprobe("btrfs", ANY_DRIVER_TYPE, NULL); #endif if (!strcmp(fs, "iso9660")) my_modprobe("isofs", ANY_DRIVER_TYPE, NULL); #ifndef DISABLE_NETWORK if (!strcmp(fs, "nfs")) { my_modprobe("nfs", ANY_DRIVER_TYPE, NULL); log_message("preparing nfsmount for %s", dev); rc = nfsmount_prepare(dev, &opts); if (rc != 0) return rc; } #endif rc = mount(dev, location, fs, flags, opts); if (rc != 0) { log_perror("mount failed"); rmdir(location); } return rc; }
void* scp_process_start(void *sck) { struct SCP_CONNECTION scon; struct SCP_SESSION *sdata; /* making a local copy of the socket (it's on the stack) */ /* probably this is just paranoia */ scon.in_sck = g_thread_sck; LOG_DBG("started scp thread on socket %d", scon.in_sck); /* unlocking g_thread_sck */ lock_socket_release(); make_stream(scon.in_s); make_stream(scon.out_s); init_stream(scon.in_s, 8192); init_stream(scon.out_s, 8192); switch (scp_vXs_accept(&scon, &(sdata))) { case SCP_SERVER_STATE_OK: if (sdata->version == 0) { /* starts processing an scp v0 connection */ LOG_DBG("accept ok, go on with scp v0\n", 0); scp_v0_process(&scon, sdata); } else { LOG_DBG("accept ok, go on with scp v1\n", 0); /*LOG_DBG("user: %s\npass: %s",sdata->username, sdata->password);*/ scp_v1_process(&scon, sdata); } break; case SCP_SERVER_STATE_START_MANAGE: /* starting a management session */ log_message(LOG_LEVEL_WARNING, "starting a sesman management session..."); scp_v1_mng_process(&scon, sdata); break; case SCP_SERVER_STATE_VERSION_ERR: /* an unknown scp version was requested, so we shut down the */ /* connection (and log the fact) */ log_message(LOG_LEVEL_WARNING, "unknown protocol version specified. connection refused."); break; case SCP_SERVER_STATE_NETWORK_ERR: log_message(LOG_LEVEL_WARNING, "libscp network error."); break; case SCP_SERVER_STATE_SEQUENCE_ERR: log_message(LOG_LEVEL_WARNING, "libscp sequence error."); break; case SCP_SERVER_STATE_INTERNAL_ERR: /* internal error occurred (eg. malloc() error, ecc.) */ log_message(LOG_LEVEL_ERROR, "libscp internal error occurred."); break; default: log_message(LOG_LEVEL_ALWAYS, "unknown return from scp_vXs_accept()"); } g_tcp_close(scon.in_sck); free_stream(scon.in_s); free_stream(scon.out_s); return 0; }
static int spf(milter_stage_t stage, char *name, var_t *attrs) { SPF_request_t *req = NULL; SPF_response_t *res = NULL; SPF_response_t *res_2mx = NULL; char *helo; char *envfrom; char from[321]; char *envrcpt; char rcpt[321]; char *spfstr; char *spfreason; struct sockaddr_storage *ss; struct sockaddr_in *sin; struct sockaddr_in6 *sin6; int r; if (acl_symbol_dereference(attrs, "hostaddr", &ss, "envfrom", &envfrom, "envrcpt", &envrcpt, "helo", &helo, NULL)) { log_error("spf: acl_symbol_dereference failed"); goto error; } sin = (struct sockaddr_in *) ss; sin6 = (struct sockaddr_in6 *) ss; if (util_strmail(from, sizeof from, envfrom) == -1 || util_strmail(rcpt, sizeof rcpt, envrcpt) == -1) { log_error("spf: util_strmail failed"); goto error; } req = SPF_request_new(spf_server); if (req == NULL) { log_error("spf: SPF_request_new failed"); goto error; } /* * Set client address */ if (ss->ss_family == AF_INET6) { r = SPF_request_set_ipv6(req, sin6->sin6_addr); } else { r = SPF_request_set_ipv4(req, sin->sin_addr); } if (r) { log_error("spf: SPF_request_set_ip failed"); goto error; } /* * Set helo */ r = SPF_request_set_helo_dom(req, helo); if (r) { log_error("spf: SPF_request_set_helo_dom failed"); goto error; } /* * Set envelope from */ r = SPF_request_set_env_from(req, from); if (r) { log_error("spf_query: SPF_request_set_env_from failed"); goto error; } /* * Perform SPF query */ SPF_request_query_mailfrom(req, &res); if(SPF_response_result(res) == SPF_RESULT_PASS) { goto result; } /* * If SPF fails check if we received the email from a secondary mx. */ SPF_request_query_rcptto(req, &res_2mx, rcpt); if(SPF_response_result(res_2mx) != SPF_RESULT_PASS) { goto result; } /* * Secondary mx */ log_notice("spf: \"%s\" is a secodary mx for \"%s\"", helo, rcpt); goto exit; result: spfstr = (char *) SPF_strresult(SPF_response_result(res)); if (spfstr == NULL) { log_error("spf: SPF_strresult failed"); goto error; } spfreason = (char *) SPF_strreason(SPF_response_result(res)); if (spfreason == NULL) { log_error("spf: SPF_strreason failed"); goto error; } log_message(LOG_ERR, attrs, "spf: helo=%s from=%s spf=%s", helo, from, spfstr); if (vtable_setv(attrs, VT_STRING, "spf", spfstr, VF_KEEP, VT_STRING, "spf_reason", spfreason, VF_KEEP, VT_NULL)) { log_error("spf: vtable_setv failed"); goto error; } exit: SPF_request_free(req); SPF_response_free(res); if(res_2mx) { SPF_response_free(res_2mx); } return 0; error: if(req) { SPF_request_free(req); } if(res) { SPF_response_free(res); } if(res_2mx) { SPF_response_free(res_2mx); } return -1; }
int main_program(int argc, char **argv) { int i; char *program_name; /* Check for -config, -console and -vsid before initializing the user interface. -config => use specified configuration file -console => no user interface -vsid => user interface in separate process */ console_mode = 0; video_disabled_mode = 0; vsid_mode=0; machine_class = VICE_MACHINE_C64; //machine_class = VICE_MACHINE_CBM6x0; archdep_init(&argc, argv); if (atexit(emulator_shutdown) < 0) { archdep_startup_log_error("atexit"); return -1; } maincpu_early_init(); machine_setup_context(); drive_setup_context(); machine_early_init(); /* Initialize system file locator. */ sysfile_init(machine_name); gfxoutput_early_init(); if (init_resources() < 0 || init_cmdline_options() < 0) return -1; /* Set factory defaults. */ if (resources_set_defaults() < 0) { archdep_startup_log_error("Cannot set defaults.\n"); return -1; } /* Initialize the user interface. `ui_init()' might need to handle the command line somehow, so we call it before parsing the options. (e.g. under X11, the `-display' option is handled independently). */ if (!console_mode && ui_init(&argc, argv) < 0) { archdep_startup_log_error("Cannot initialize the UI.\n"); return -1; } if (initcmdline_check_args(argc, argv) < 0) return -1; program_name = archdep_program_name(); /* VICE boot sequence. */ #if 0 log_message(LOG_DEFAULT, "*** VICE Version %s ***", VERSION); log_message(LOG_DEFAULT, "OS compiled for: %s", platform_get_compile_time_os()); log_message(LOG_DEFAULT, "GUI compiled for: %s", platform_get_ui()); log_message(LOG_DEFAULT, "CPU compiled for: %s", platform_get_compile_time_cpu()); log_message(LOG_DEFAULT, "Compiler used: %s", platform_get_compile_time_compiler()); log_message(LOG_DEFAULT, "Current OS: %s", platform_get_runtime_os()); log_message(LOG_DEFAULT, "Current CPU: %s", platform_get_runtime_cpu()); log_message(LOG_DEFAULT, " "); log_message(LOG_DEFAULT, "Welcome to %s, the free portable %s Emulator.", program_name, machine_name); log_message(LOG_DEFAULT, " "); log_message(LOG_DEFAULT, "Current VICE team members:"); log_message(LOG_DEFAULT, "A. Boose, D. Lem, T. Biczo, A. Dehmel, T. Bretz, A. Matthies,"); log_message(LOG_DEFAULT, "M. Pottendorfer, M. Brenner, S. Trikaliotis, M. van den Heuvel,"); log_message(LOG_DEFAULT, "C. Vogelgsang, F. Gennari, H. Nuotio, D. Kahlin, A. Lankila."); log_message(LOG_DEFAULT, " "); log_message(LOG_DEFAULT, "This is free software with ABSOLUTELY NO WARRANTY."); log_message(LOG_DEFAULT, "See the \"About VICE\" command for more info."); log_message(LOG_DEFAULT, " "); #endif lib_free(program_name); /* Complete the GUI initialization (after loading the resources and parsing the command-line) if necessary. */ if (!console_mode && ui_init_finish() < 0) return -1; if (!console_mode && video_init() < 0) return -1; if (initcmdline_check_psid() < 0) return -1; if (init_main() < 0) return -1; initcmdline_check_attach(); init_done = 1; /* Let's go... */ #ifdef CELL_DEBUG printf("Main CPU: starting at ($FFFC).\n"); #endif maincpu_mainloop(); #ifdef CELL_DEBUG printf("perkele!\n"); #endif return 0; }
int main( int argc, char *argv[] ) { int i = 0; char *old_cwd = NULL; struct sigaction sig, old; /* Required to make iconv to ASCII//TRANSLIT work. This makes BitlBee system-locale-sensitive. :-( */ setlocale( LC_CTYPE, "" ); if( argc > 1 && strcmp( argv[1], "-x" ) == 0 ) return crypt_main( argc, argv ); log_init(); global.conf_file = g_strdup( CONF_FILE_DEF ); global.conf = conf_load( argc, argv ); if( global.conf == NULL ) return( 1 ); b_main_init(); /* libpurple doesn't like fork()s after initializing itself, so if we use it, do this init a little later (in case we're running in ForkDaemon mode). */ #ifndef WITH_PURPLE nogaim_init(); #endif /* Ugly Note: libotr and gnutls both use libgcrypt. libgcrypt has a process-global config state whose initialization happpens twice if libotr and gnutls are used together. libotr installs custom memory management functions for libgcrypt while our gnutls module uses the defaults. Therefore we initialize OTR after SSL. *sigh* */ ssl_init(); #ifdef OTR_BI otr_init(); #endif /* And in case OTR is loaded as a plugin, it'll also get loaded after this point. */ srand( time( NULL ) ^ getpid() ); global.helpfile = g_strdup( HELP_FILE ); if( help_init( &global.help, global.helpfile ) == NULL ) log_message( LOGLVL_WARNING, "Error opening helpfile %s.", HELP_FILE ); global.storage = storage_init( global.conf->primary_storage, global.conf->migrate_storage ); if( global.storage == NULL ) { log_message( LOGLVL_ERROR, "Unable to load storage backend '%s'", global.conf->primary_storage ); return( 1 ); } if( global.conf->runmode == RUNMODE_INETD ) { log_link( LOGLVL_ERROR, LOGOUTPUT_IRC ); log_link( LOGLVL_WARNING, LOGOUTPUT_IRC ); i = bitlbee_inetd_init(); log_message( LOGLVL_INFO, "%s %s starting in inetd mode.", PACKAGE, BITLBEE_VERSION ); } else if( global.conf->runmode == RUNMODE_DAEMON ) { log_link( LOGLVL_ERROR, LOGOUTPUT_CONSOLE ); log_link( LOGLVL_WARNING, LOGOUTPUT_CONSOLE ); i = bitlbee_daemon_init(); log_message( LOGLVL_INFO, "%s %s starting in daemon mode.", PACKAGE, BITLBEE_VERSION ); } else if( global.conf->runmode == RUNMODE_FORKDAEMON ) { log_link( LOGLVL_ERROR, LOGOUTPUT_CONSOLE ); log_link( LOGLVL_WARNING, LOGOUTPUT_CONSOLE ); /* In case the operator requests a restart, we need this. */ old_cwd = g_malloc( 256 ); if( getcwd( old_cwd, 255 ) == NULL ) { log_message( LOGLVL_WARNING, "Could not save current directory: %s", strerror( errno ) ); g_free( old_cwd ); old_cwd = NULL; } i = bitlbee_daemon_init(); log_message( LOGLVL_INFO, "%s %s starting in forking daemon mode.", PACKAGE, BITLBEE_VERSION ); } if( i != 0 ) return( i ); if( ( global.conf->user && *global.conf->user ) && ( global.conf->runmode == RUNMODE_DAEMON || global.conf->runmode == RUNMODE_FORKDAEMON ) && ( !getuid() || !geteuid() ) ) { struct passwd *pw = NULL; pw = getpwnam( global.conf->user ); if( pw ) { initgroups( global.conf->user, pw->pw_gid ); setgid( pw->pw_gid ); setuid( pw->pw_uid ); } else { log_message( LOGLVL_WARNING, "Failed to look up user %s.", global.conf->user ); } } /* Catch some signals to tell the user what's happening before quitting */ memset( &sig, 0, sizeof( sig ) ); sig.sa_handler = sighandler; sigaction( SIGCHLD, &sig, &old ); sigaction( SIGPIPE, &sig, &old ); sig.sa_flags = SA_RESETHAND; sigaction( SIGINT, &sig, &old ); sigaction( SIGILL, &sig, &old ); sigaction( SIGBUS, &sig, &old ); sigaction( SIGFPE, &sig, &old ); sigaction( SIGSEGV, &sig, &old ); sigaction( SIGTERM, &sig, &old ); sigaction( SIGQUIT, &sig, &old ); sigaction( SIGXCPU, &sig, &old ); if( !getuid() || !geteuid() ) log_message( LOGLVL_WARNING, "BitlBee is running with root privileges. Why?" ); b_main_run(); /* Mainly good for restarting, to make sure we close the help.txt fd. */ help_free( &global.help ); if( global.restart ) { char *fn = ipc_master_save_state(); char *env; env = g_strdup_printf( "_BITLBEE_RESTART_STATE=%s", fn ); putenv( env ); g_free( fn ); /* Looks like env should *not* be freed here as putenv doesn't make a copy. Odd. */ i = chdir( old_cwd ); close( global.listen_socket ); if( execv( argv[0], argv ) == -1 ) /* Apparently the execve() failed, so let's just jump back into our own/current main(). */ /* Need more cleanup code to make this work. */ return 1; /* main( argc, argv ); */ } return( 0 ); }
/* new_request_stat() * * Register statistics about client requests. Returns the newly generated * and unique id. * */ int new_request_stat (unsigned long ip_num, const char * type, char * user_agent) { int i, auto_id, client_id_len, child_id; char * query, * server_id, * client_id, * tmp_id; unsigned char * uchar_sign; GeoIPRecord * record; MYSQL_RES * result; MYSQL_ROW row; char * add_info; /* TODO: browser and opsys detection. */ const char browser [] = UNKNOWN_FIELD; const char opsys [] = UNKNOWN_FIELD; /* Check if statistic data gathering is enabled. */ if (stats_enabled != 1) { return (EXIT_SUCCESS); } child_id = get_child_pos(); server_id = (char *)get_server_name(); /* Calculate unique digest. */ uchar_sign = malloc(SHA_DIGEST_LENGTH); client_id = malloc(SIGN_LEN + 1); client_id_len = asprintf(&tmp_id, "%lu", ip_num); SHA1((unsigned char *)tmp_id, client_id_len, uchar_sign); free(tmp_id); for (i = 0; i < SHA_DIGEST_LENGTH; i++) { sprintf(client_id + i * 2, "%02x", uchar_sign[i]); } free(uchar_sign); if ((record = GeoIP_record_by_ipnum(gi_db, ip_num)) != NULL) { asprintf(&query, "INSERT INTO requests (%s) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', CURRENT_TIMESTAMP())", REQUEST_FIELDS, client_id, server_id, child_id, type, browser, opsys, record->city, record->country_name); GeoIPRecord_delete(record); } else { asprintf(&query, "INSERT INTO requests (%s) VALUES ('%s', '%s', %d, '%s', '%s', '%s', '%s', '%s', CURRENT_TIMESTAMP())", REQUEST_FIELDS, client_id, server_id, child_id, type, browser, opsys, UNKNOWN_FIELD, UNKNOWN_FIELD); } /* MySQL threaded interaction. * Multithread clients sharing the same connection *must* enclose * mysql_query() and mysql_store_result() in a lock to prevent access * from other threads. * */ /* Insert data and get the last autoincremented value. */ pthread_mutex_lock(&stat_lock); if (mysql_query(db_conn, query) != 0) { pthread_mutex_unlock(&stat_lock); log_message(ERROR, EMSG_INSERT, query); free(client_id); free(server_id); free(query); return (ECOD_INSERT); } pthread_mutex_unlock(&stat_lock); free(client_id); free(query); asprintf(&query, "SELECT MAX(id) FROM requests WHERE server_id = '%s' AND child_id = %d", server_id, child_id); free(server_id); pthread_mutex_lock(&stat_lock); if (mysql_query(db_conn, query) != 0) { pthread_mutex_unlock(&stat_lock); log_message(ERROR, EMSG_SELECT, query); free(query); return (ECOD_SELECT); } if ((result = mysql_store_result(db_conn)) != NULL) { pthread_mutex_unlock(&stat_lock); free(query); row = mysql_fetch_row(result); auto_id = atoi(row[0]); mysql_free_result(result); asprintf(&add_info, "Request ID: %d\n", auto_id); log_message(MESSAGE, IMSG_NEWREQSTAT, add_info); free(add_info); } else { pthread_mutex_unlock(&stat_lock); log_message(ERROR, EMSG_SELECT, query); free(query); return (ECOD_SELECT); } return (auto_id); }
int DEFAULT_CC env_set_user(char* username, char* passwd_file, int display) { int error; int pw_uid; int pw_gid; int uid; char pw_shell[256]; char pw_dir[256]; char pw_gecos[256]; char text[256]; error = g_getuser_info(username, &pw_gid, &pw_uid, pw_shell, pw_dir, pw_gecos); if (error == 0) { g_rm_temp_dir(); error = g_setgid(pw_gid); if (error == 0) { error = g_initgroups(username, pw_gid); } if (error == 0) { uid = pw_uid; error = g_setuid(uid); } g_mk_temp_dir(0); if (error == 0) { g_clearenv(); g_setenv("SHELL", pw_shell, 1); g_setenv("PATH", "/bin:/usr/bin:/usr/X11R6/bin:/usr/local/bin", 1); g_setenv("USER", username, 1); g_sprintf(text, "%d", uid); g_setenv("UID", text, 1); g_setenv("HOME", pw_dir, 1); g_set_current_dir(pw_dir); g_sprintf(text, ":%d.0", display); g_setenv("DISPLAY", text, 1); if (passwd_file != 0) { if (0 == g_cfg->auth_file_path) { /* if no auth_file_path is set, then we go for $HOME/.vnc/sesman_username_passwd */ g_mkdir(".vnc"); g_sprintf(passwd_file, "%s/.vnc/sesman_%s_passwd", pw_dir, username); } else { /* we use auth_file_path as requested */ g_sprintf(passwd_file, g_cfg->auth_file_path, username); } LOG_DBG(&(g_cfg->log), "pass file: %s", passwd_file); } } } else { log_message(&(g_cfg->log), LOG_LEVEL_ERROR, "error getting user info for user %s", username); } return error; }
/* init_stat() * * Initialize MySQL and GeoIP API. * Needs a 'path' to a passwd file. If it is NULL or does not exist, * will use the 'DEFAULT_PATH' constant defined previously. * However, 'host' can not be NULL. * */ int init_stat (char * host, char * path) { char * contents, * entry, * user, * passwd, * add_info; if (host == NULL) { log_message(ERROR, EMSG_DBHOST, NULL); return (ECOD_DBHOST); } /* Find required login and password. * If 'path' is NULL or does not exist, use a default value. * */ if ((path == NULL) || (!check_file_exists(path))) { contents = (char *)get_file_contents(DEFAULT_PATH); } else { contents = (char *)get_file_contents(path); } entry = strstr(contents, DATABASE); entry = strchr(entry, '=') + 1; if ((user = get_first_substr(entry, ',')) == NULL) { free(contents); log_message(ERROR, EMSG_STATDBUSER, NULL); return (ECOD_STATDBUSER); } if ((passwd = get_between_delim(entry, ',', ';')) == NULL) { free(user); free(contents); log_message(ERROR, EMSG_STATDBPASS, NULL); return (ECOD_STATDBPASS); } free(contents); /* Connect to MySQL database. */ if (((db_conn = mysql_init(NULL)) == NULL) || (mysql_real_connect(db_conn, host, user, passwd, DATABASE, 0, NULL, 0) == NULL)) { free(user); free(passwd); mysql_close(db_conn); log_message(ERROR, EMSG_DBSTATCONN, NULL); return (ECOD_DBSTATCONN); } free(user); free(passwd); /* GeoIP, only for request statistics. * Initialization is done here to avoid performance and memory usage * problems while analyzing request data. * */ if ((gi_db = GeoIP_open("/usr/share/GeoIP/GeoLiteCity.dat", GEOIP_STANDARD)) == NULL) { log_message(ERROR, EMSG_GISTATINIT, NULL); return (ECOD_GISTATINIT); } asprintf(&add_info, "Server: %s\n", host); log_message(MESSAGE, IMSG_STATSENABLED, add_info); free(add_info); stats_enabled = 1; return (EXIT_SUCCESS); }
int io_writeDump(sParameterStruct * sSO2Parameters, sConfigStruct * config) { FILE *imageFile; FILE *fp; char headerfile[512]; int headerfilelength = 512; char rawfile[512]; int rawfilelength = 512; int fwriteReturn; int state = 0; char iso_date[25]; /* generate filenames */ state = createFilename(sSO2Parameters, config, headerfile, headerfilelength, "txt"); if(state){ log_error("could not create txt filename"); } state = createFilename(sSO2Parameters, config, rawfile, rawfilelength, "raw"); if (state) { log_error("could not create txt filename"); } /* Open a new file for the image (writeable, binary) */ imageFile = fopen(rawfile, "wb"); if (imageFile != NULL) { fwriteReturn = fwrite(sSO2Parameters->stBuffer, 1, config->dBufferlength * 2, imageFile); if(fwriteReturn != config->dBufferlength * 2){ log_debug("could not write raw file %i != %i", config->dBufferlength, fwriteReturn); log_error("could not write raw file"); } fclose(imageFile); } else { log_error("not opened raw file"); } /* write a text file containing header information */ fp = fopen(headerfile, "ab"); if (fp != NULL) { fprintf(fp, "dBufferlength %i\n", config->dBufferlength); fprintf(fp, "dHistMinInterval %i\n", config->dHistMinInterval); fprintf(fp, "dHistPercentage %i\n", config->dHistPercentage); fprintf(fp, "dDarkCurrent %i\n", (int)sSO2Parameters->dDarkCurrent); fprintf(fp, "dImageCounter %i\n", (int)config->dImageCounter); fprintf(fp, "dInterFrameDelay %i\n", (int)config->dInterFrameDelay); fprintf(fp, "dTriggerPulseWidth %i\n", (int)sSO2Parameters->dTriggerPulseWidth); fprintf(fp, "dExposureTime %f\n", sSO2Parameters->dExposureTime); fprintf(fp, "cConfigFileName %s\n", config->cConfigFileName); fprintf(fp, "cFileNamePrefix %s\n", config->cFileNamePrefix); fprintf(fp, "cImagePath %s\n", config->cImagePath); fprintf(fp, "dFixTime %i\n", config->dFixTime); dateStructToISO8601(sSO2Parameters->timestampBefore, iso_date); fprintf(fp, "timestampBefore %s\n", iso_date); fclose(fp); } else { log_error("not opened text file"); } log_message("dumb image written"); return 0; }
/* set quorum state depending on current weight of real servers */ static void update_quorum_state(virtual_server_t * vs) { long unsigned weight_sum = weigh_live_realservers(vs); long signed up_threshold = vs->quorum + vs->hysteresis; long signed down_threshold = vs->quorum - vs->hysteresis; /* If we have just gained quorum, it's time to consider notify_up. */ if (vs->quorum_state == DOWN && weight_sum >= up_threshold) { vs->quorum_state = UP; log_message(LOG_INFO, "Gained quorum %lu+%lu=%li <= %lu for VS %s" , vs->quorum , vs->hysteresis , up_threshold , weight_sum , FMT_VS(vs)); if (vs->s_svr && ISALIVE(vs->s_svr)) { log_message(LOG_INFO, "%s sorry server %s from VS %s" , (vs->s_svr->inhibit ? "Disabling" : "Removing") , FMT_RS(vs->s_svr) , FMT_VS(vs)); ipvs_cmd(LVS_CMD_DEL_DEST, check_data->vs_group, vs, vs->s_svr); vs->s_svr->alive = 0; /* Adding back alive real servers */ perform_quorum_state(vs, 1); } if (vs->quorum_up) { log_message(LOG_INFO, "Executing [%s] for VS %s" , vs->quorum_up , FMT_VS(vs)); notify_exec(vs->quorum_up); } #ifdef _WITH_SNMP_ check_snmp_quorum_trap(vs); #endif return; } /* If we have just lost quorum for the VS, we need to consider * VS notify_down and sorry_server cases */ if (vs->quorum_state == UP && ( !weight_sum || weight_sum < down_threshold) ) { vs->quorum_state = DOWN; log_message(LOG_INFO, "Lost quorum %lu-%lu=%li > %lu for VS %s" , vs->quorum , vs->hysteresis , down_threshold , weight_sum , FMT_VS(vs)); if (vs->quorum_down) { log_message(LOG_INFO, "Executing [%s] for VS %s" , vs->quorum_down , FMT_VS(vs)); notify_exec(vs->quorum_down); } if (vs->s_svr) { log_message(LOG_INFO, "%s sorry server %s to VS %s" , (vs->s_svr->inhibit ? "Enabling" : "Adding") , FMT_RS(vs->s_svr) , FMT_VS(vs)); /* the sorry server is now up in the pool, we flag it alive */ ipvs_cmd(LVS_CMD_ADD_DEST, check_data->vs_group, vs, vs->s_svr); vs->s_svr->alive = 1; /* Remove remaining alive real servers */ perform_quorum_state(vs, 0); } #ifdef _WITH_SNMP_ check_snmp_quorum_trap(vs); #endif return; } }
int io_writeImage(sParameterStruct * sSO2Parameters, sConfigStruct * config) { FILE *fp; short *stBuffer; IplImage *img; CvMat *png; int l; int writen_bytes; char filename[512]; int filenamelength = 512; int state; char *buffer; stBuffer = sSO2Parameters->stBuffer; /* generate filenames */ state = createFilename(sSO2Parameters, config, filename, filenamelength, "png"); if (state) { log_error("could not create txt filename"); return state; } log_debug("filename created: %s", filename); /* convert the image buffer to an openCV image */ // TODO: check if this has already been done // TODO: check return code img = bufferToImage(stBuffer); /* * encode image as png to buffer * playing with the compression is a huge waste of time with no benefit */ png = cvEncodeImage(".png", img, 0); l = png->rows * png->cols; cvReleaseImage(&img); // pry the actual buffer pointer from png buffer = (char *)malloc(l); memcpy(buffer, png->data.s, l); cvReleaseMat(&png); /* add headers */ log_debug("insert headers %i", l); l = insertHeaders(&buffer, sSO2Parameters, config, l); /* save image to disk */ log_debug("open new png file %i", l); fp = fopen(filename, "wb"); if (fp) { writen_bytes = fwrite(buffer, 1, l, fp); state = writen_bytes == l ? 0 : 1; if (state) { log_error("PNG image wasn't written correctly"); } fclose(fp); } else { state = 1; log_error("Couldn't open png file"); } /* cleanup */ free(buffer); if (!state) { log_message("png image written"); } return state; }
/* Register VRRP thread */ int start_vrrp_child(void) { #ifndef _DEBUG_ pid_t pid; int ret; /* Initialize child process */ pid = fork(); if (pid < 0) { log_message(LOG_INFO, "VRRP child process: fork error(%s)" , strerror(errno)); return -1; } else if (pid) { vrrp_child = pid; log_message(LOG_INFO, "Starting VRRP child process, pid=%d" , pid); /* Start respawning thread */ thread_add_child(master, vrrp_respawn_thread, NULL, pid, RESPAWN_TIMER); return 0; } /* Opening local VRRP syslog channel */ openlog(PROG_VRRP, LOG_PID | (debug & 1) ? LOG_CONS : 0, (log_facility==LOG_DAEMON) ? LOG_LOCAL1 : log_facility); /* Child process part, write pidfile */ if (!pidfile_write(vrrp_pidfile, getpid())) { /* Fatal error */ log_message(LOG_INFO, "VRRP child process: cannot write pidfile"); exit(0); } /* Create the new master thread */ signal_handler_destroy(); thread_destroy_master(master); master = thread_make_master(); /* change to / dir */ ret = chdir("/"); /* Set mask */ umask(0); #endif /* If last process died during a reload, we can get there and we * don't want to loop again, because we're not reloading anymore. */ UNSET_RELOAD; /* Signal handling initialization */ vrrp_signal_init(); /* Start VRRP daemon */ start_vrrp(); /* Launch the scheduling I/O multiplexer */ launch_scheduler(); /* Finish VRRP daemon process */ stop_vrrp(); exit(0); }
int io_uninit(sConfigStruct * config) { log_message("io_uninit"); return 0; }
void free_user (USER * user) { LIST *list; USERDB *db; whowas_t *who; ip_info_t *info; ASSERT (validate_user (user)); if (ISUSER (user->con) && Servers && !user->con->killed) { /* local user, notify peers of this user's departure */ pass_message_args (user->con, MSG_CLIENT_QUIT, "%s", user->nick); } /* remove this user from any channels they were on */ if (user->channels) { for (list = user->channels; list; list = list->next) { /* notify locally connected clients in the same channel that this user has parted */ part_channel (list->data, user); } list_free (user->channels, 0); } /* check the global hotlist for this user to see if anyone wants notice of this user's departure */ for (list = hashlist_lookup (Hotlist, user->nick); list; list = list->next) { ASSERT (validate_connection (list->data)); send_cmd (list->data, MSG_SERVER_USER_SIGNOFF, "%s", user->nick); } ASSERT (Num_Files >= user->shared); Num_Files -= user->shared; ASSERT (Num_Gigs >= user->libsize); if (Num_Gigs < user->libsize) { log_message ("free_user: bad total lib size: Num_Gigs=%f user->libsize=%u", Num_Gigs, user->libsize); Num_Gigs = user->libsize; /* prevent negative value */ } Num_Gigs -= user->libsize; /* this is in kB */ #ifndef ROUTING_ONLY if (ISUSER (user->con)) { if (user->shared > Local_Files) { log_message ("free_user: local file count error, %s is sharing %d, more than %d", user->nick, user->shared, Local_Files); Local_Files = 0; } else Local_Files -= user->shared; } #endif /* !ROUTING_ONLY */ /* record the log off time */ if ((db = hash_lookup (User_Db, user->nick))) db->lastSeen = global.current_time; /* save info in the who-was table */ who = hash_lookup (Who_Was, user->nick); if (!who) { who = CALLOC (1, sizeof (whowas_t)); if (!who) { OUTOFMEMORY ("free_user"); FREE (user->nick); } else { who->nick = user->nick; hash_add (Who_Was, who->nick, who); } } else FREE (user->nick); if (who) { who->ip = user->ip; who->when = global.current_time; who->server = user->server; who->clientinfo = user->clientinfo; } memset (user->pass, 0, strlen (user->pass)); FREE (user->pass); /* decrement the clone count */ info = hash_lookup (Clones, (void *) user->ip); if (info->users <= 0) { log_message ("free_user: ERROR, info->users <= 0"); info->users = 0; } else info->users--; /* NOTE: user->server is just a ref, not a malloc'd pointer */ memset (user, 0xff, sizeof (USER)); /* catch refs to bad memory */ FREE (user); }
int riotcore_snapshot_read_module(riot_context_t *riot_context, snapshot_t *p) { BYTE vmajor, vminor; BYTE byte_r_N; BYTE byte; WORD word_r_divider; WORD word_r_write_clk; snapshot_module_t *m; m = snapshot_module_open(p, riot_context->myname, &vmajor, &vminor); if (m == NULL) { log_message(riot_context->log, "Could not find snapshot module %s", riot_context->myname); return -1; } /* Do not accept versions higher than current */ if (vmajor > RIOT_DUMP_VER_MAJOR || vminor > RIOT_DUMP_VER_MINOR) { snapshot_set_error(SNAPSHOT_MODULE_HIGHER_VERSION); snapshot_module_close(m); return -1; } /* just to be safe */ alarm_unset(riot_context->alarm); if (0 || SMR_B(m, &(riot_context->riot_io)[0]) < 0 || SMR_B(m, &(riot_context->riot_io)[1]) < 0 || SMR_B(m, &(riot_context->riot_io)[2]) < 0 || SMR_B(m, &(riot_context->riot_io)[3]) < 0 || SMR_B(m, &(riot_context->r_edgectrl)) < 0 || SMR_B(m, &(riot_context->r_irqfl)) < 0 || SMR_B(m, &byte_r_N) < 0 || SMR_W(m, &word_r_divider) < 0 || SMR_W(m, &word_r_write_clk) < 0 || SMR_B(m, &byte) < 0) { snapshot_module_close(m); return -1; } riot_context->old_pa = riot_context->riot_io[0] | ~(riot_context->riot_io)[1]; riot_context->undump_pra(riot_context, riot_context->old_pa); riot_context->old_pb = riot_context->riot_io[2] | ~(riot_context->riot_io)[3]; riot_context->undump_prb(riot_context, riot_context->old_pb); riot_context->r_N = byte_r_N; riot_context->r_divider = word_r_divider; riot_context->r_write_clk = *(riot_context->clk_ptr) - word_r_write_clk; if (riot_context->r_irqfl & 1) { riot_context->r_irqline = 1; riot_context->restore_irq(riot_context, 1); } riot_context->r_irqfl &= 0xc0; riot_context->r_irqen = byte; if (riot_context->r_irqen) { alarm_set(riot_context->alarm, riot_context->r_write_clk + riot_context->r_N * riot_context->r_divider); } riot_context->read_clk = 0; return snapshot_module_close(m); }
/** @brief The thread function for getting cw's from oscam */ static void *getcwthread_func(void* arg) { struct getcw_params_t *getcw_params; getcw_params= (struct getcw_params_t *) arg; scam_parameters_t *scam_params; mumu_chan_p_t *chan_p; scam_params=getcw_params->scam_params; chan_p=getcw_params->chan_p; int curr_channel = 0; int curr_pid = 0; unsigned char buff[sizeof(int) + sizeof(ca_descr_t)]; int cRead, *request; //Loop while(!scam_params->getcwthread_shutdown) { cRead = recv(scam_params->net_socket_fd, &buff, sizeof(buff), 0); if (cRead <= 0) break; request = (int *) &buff; if (*request == CA_SET_DESCR) { memcpy((&(scam_params->ca_descr)), &buff[sizeof(int)], sizeof(ca_descr_t)); log_message( log_module, MSG_DEBUG, "Got CA_SET_DESCR request index: %d, parity %d, key %02x %02x %02x %02x %02x %02x %02x %02x\n", scam_params->ca_descr.index, scam_params->ca_descr.parity, scam_params->ca_descr.cw[0], scam_params->ca_descr.cw[1], scam_params->ca_descr.cw[2], scam_params->ca_descr.cw[3], scam_params->ca_descr.cw[4], scam_params->ca_descr.cw[5], scam_params->ca_descr.cw[6], scam_params->ca_descr.cw[7]); if(scam_params->ca_descr.index != (unsigned) -1) { pthread_mutex_lock(&chan_p->lock); for (curr_channel = 0; curr_channel < chan_p->number_of_channels; curr_channel++) { mumudvb_channel_t *channel = &chan_p->channels[curr_channel]; pthread_mutex_lock(&channel->cw_lock); if (channel->ca_idx == scam_params->ca_descr.index + 1) { if (scam_params->ca_descr.parity) { memcpy(channel->odd_cw,scam_params->ca_descr.cw,8); channel->got_key_odd=1; } else { memcpy(channel->even_cw,scam_params->ca_descr.cw,8); channel->got_key_even=1; } } pthread_mutex_unlock(&channel->cw_lock); } pthread_mutex_unlock(&chan_p->lock); } else { log_message( log_module, MSG_DEBUG, "Got CA_SET_DESCR removal request, ignoring"); } } if (*request == CA_SET_PID) { memcpy((&(scam_params->ca_pid)), &buff[sizeof(int)], sizeof(ca_pid_t)); log_message( log_module, MSG_DEBUG, "Got CA_SET_PID request index: %d pid: %d\n",scam_params->ca_pid.index, scam_params->ca_pid.pid); if(scam_params->ca_pid.index == -1) { log_message( log_module, MSG_DEBUG, "Got CA_SET_PID removal request, removing pid: %d\n", scam_params->ca_pid.pid); pthread_mutex_lock(&chan_p->lock); for (curr_channel = 0; curr_channel < chan_p->number_of_channels; curr_channel++) { mumudvb_channel_t *channel = &chan_p->channels[curr_channel]; for (curr_pid = 1; curr_pid < channel->num_pids; curr_pid++) { if ((channel->pids_type[curr_pid] != PID_EXTRA_VBIDATA) && (channel->pids_type[curr_pid] != PID_EXTRA_VBITELETEXT) && (channel->pids_type[curr_pid] != PID_EXTRA_TELETEXT) && (channel->pids_type[curr_pid] != PID_EXTRA_SUBTITLE) && (channel->pids[curr_pid] == (int) scam_params->ca_pid.pid)) { pthread_mutex_lock(&channel->cw_lock); --channel->ca_idx_refcnt; if (!channel->ca_idx_refcnt) { channel->ca_idx = 0; log_message( log_module, MSG_DEBUG, "Got CA_SET_PID removal request: %d setting channel %s with ca_idx to 0 %d\n", scam_params->ca_pid.pid, channel->name, scam_params->ca_pid.index+1); } pthread_mutex_unlock(&channel->cw_lock); break; } } } pthread_mutex_unlock(&chan_p->lock); } else { pthread_mutex_lock(&chan_p->lock); for (curr_channel = 0; curr_channel < chan_p->number_of_channels; curr_channel++) { mumudvb_channel_t *channel = &chan_p->channels[curr_channel]; for (curr_pid = 1; curr_pid < channel->num_pids; curr_pid++) { if ((channel->pids_type[curr_pid] != PID_EXTRA_VBIDATA) && (channel->pids_type[curr_pid] != PID_EXTRA_VBITELETEXT) && (channel->pids_type[curr_pid] != PID_EXTRA_TELETEXT) && (channel->pids_type[curr_pid] != PID_EXTRA_SUBTITLE) && (channel->pids[curr_pid] == (int) scam_params->ca_pid.pid)) { pthread_mutex_lock(&channel->cw_lock); if(!channel->ca_idx_refcnt) { channel->ca_idx = scam_params->ca_pid.index+1; log_message( log_module, MSG_DEBUG, "Got CA_SET_PID with pid: %d setting channel %s ca_idx %d\n", scam_params->ca_pid.pid, channel->name, scam_params->ca_pid.index+1); } ++channel->ca_idx_refcnt; pthread_mutex_unlock(&channel->cw_lock); break; } } } pthread_mutex_unlock(&chan_p->lock); } } } free(getcw_params); return 0; }
/* 006 */ enum SCP_SERVER_STATES_E scp_v1s_mng_list_sessions(struct SCP_CONNECTION *c, struct SCP_SESSION *s, int sescnt, struct SCP_DISCONNECTED_SESSION *ds) { tui32 version = 1; tui32 size = 12; tui16 cmd = SCP_CMD_MNG_LIST; int pktcnt; int idx; int sidx; int pidx; struct SCP_DISCONNECTED_SESSION *cds; /* calculating the number of packets to send */ pktcnt = sescnt / SCP_SERVER_MAX_LIST_SIZE; if ((sescnt % SCP_SERVER_MAX_LIST_SIZE) != 0) { pktcnt++; } for (idx = 0; idx < pktcnt; idx++) { /* ok, we send session session list */ init_stream(c->out_s, c->out_s->size); /* size: ver+size+cmdset+cmd+sescnt+continue+count */ size = 4 + 4 + 2 + 2 + 4 + 1 + 1; /* header */ s_push_layer(c->out_s, channel_hdr, 8); out_uint16_be(c->out_s, SCP_COMMAND_SET_MANAGE); out_uint16_be(c->out_s, cmd); /* session count */ out_uint32_be(c->out_s, sescnt); /* setting the continue flag */ if ((idx + 1)*SCP_SERVER_MAX_LIST_SIZE >= sescnt) { out_uint8(c->out_s, 0); /* setting session count for this packet */ pidx = sescnt - (idx * SCP_SERVER_MAX_LIST_SIZE); out_uint8(c->out_s, pidx); } else { out_uint8(c->out_s, 1); /* setting session count for this packet */ pidx = SCP_SERVER_MAX_LIST_SIZE; out_uint8(c->out_s, pidx); } /* adding session descriptors */ for (sidx = 0; sidx < pidx; sidx++) { /* shortcut to the current session to send */ cds = ds + ((idx) * SCP_SERVER_MAX_LIST_SIZE) + sidx; /* session data */ out_uint32_be(c->out_s, cds->SID); /* session id */ out_uint8(c->out_s, cds->type); out_uint16_be(c->out_s, cds->height); out_uint16_be(c->out_s, cds->width); out_uint8(c->out_s, cds->bpp); out_uint8(c->out_s, cds->idle_days); out_uint8(c->out_s, cds->idle_hours); out_uint8(c->out_s, cds->idle_minutes); size += 13; out_uint16_be(c->out_s, cds->conn_year); out_uint8(c->out_s, cds->conn_month); out_uint8(c->out_s, cds->conn_day); out_uint8(c->out_s, cds->conn_hour); out_uint8(c->out_s, cds->conn_minute); out_uint8(c->out_s, cds->addr_type); size += 7; if (cds->addr_type == SCP_ADDRESS_TYPE_IPV4) { in_uint32_be(c->out_s, cds->ipv4addr); size += 4; } else if (cds->addr_type == SCP_ADDRESS_TYPE_IPV6) { in_uint8a(c->out_s, cds->ipv6addr, 16); size += 16; } } s_pop_layer(c->out_s, channel_hdr); out_uint32_be(c->out_s, version); out_uint32_be(c->out_s, size); if (0 != scp_tcp_force_send(c->in_sck, c->out_s->data, size)) { log_message(LOG_LEVEL_WARNING, "[v1s_mng:%d] connection aborted: network error", __LINE__); return SCP_SERVER_STATE_NETWORK_ERR; } } return _scp_v1s_mng_check_response(c, s); }