/* EXECNEWTASK -- Called from the EXEC instruction after all param and stdio * processing for the new task is complete. Here we actually run the new task, * either directly in the case of a builtin function, or as a new case for * main()'s loop. Do not set newtask to NULL so that run() can tell what it * exec'd. */ void execnewtask (void) { /* VMS C V2.1 cannot handle this (see below). * register struct pfile *pfp; */ static struct pfile *pfp; struct param *pp; FILE *fopen(); if (newtask == NULL) /* if this ever happens, i don't want to know about it. */ return; currentask->t_pc = pc; /* instruction after EXEC */ if (cldebug) eprintf ("execnewtask: pc = %d\n", pc); if (newtask->t_flags & T_BUILTIN) { /* set yyin in case a builtin reads someday; none do now. * unlink newtask's fake param file and reset top of dictionary * to what it was before the fake param file was added; it is * still there, however, for the builtin to use. this is done * since some builtins (eg task) want to add things that are * to stay on the dictionary and the tools all start at topd. * the return is back to run(); it will continue since it will * see that newtask was just a builtin. * note that we do not reset pf_n, as with other fake pfiles, * as this is the way builtins get their number of arguments * (it's faster than building them a $nargs). */ yyin = newtask->t_in = currentask->t_in; /* inherit pipe */ newtask->t_out = currentask->t_out; newtask->t_modep = currentask->t_modep; /* inherit mode */ /* VMS C 2.1 Optimizer cannot handle this. * parhead = dereference (reference (pfile, parhead)->pf_npf); */ pfp = reference (pfile, parhead); parhead = dereference (pfp->pf_npf); topd = currentask->t_topd; currentask = newtask; newtask->t_flags |= T_RUNNING; if (cldebug) eprintf ("execnewtask: calling new task@%x\n", newtask); if (cltrace) eprintf ("\t----- exec %s %s -----\n", (newtask->t_flags & T_FOREIGN) ? "foreign" : "builtin", newtask->t_ltp->lt_lname); (*newtask->t_ltp->lt_f)(); oneof(); /* proceed as though this task saw eof */ return; } pfp = newtask->t_pfp; /* If the new task is a cl, we are not running in background and * its t_in is stdin, it is interactive. Note that when a package * is loaded by a script task rather than interactively by the user, * the t_in of the cl() in the package script task will be reading * from the calling script task rather than from the original stdin * (the user terminal), hence is not interactive. If this task is * flagged interactive, taskunwind() may elect to restart it on an * error so save present state for restor(). */ if (newtask->t_flags & T_CL) { if (cldebug) eprintf ("execnewtask: new task is the CL\n"); if (cltrace) eprintf ("\t----- exec cl -----\n"); /* Call set_clio to set the command input and output streams * t_in and t_out for a cl() or package_name() command. */ set_clio (newtask); /* This code is a temporary patch to allow packages to be * loaded from within scripts regardless of whether there * are enclosing brackets. If a CL statement is executed * within a script which is itself called within another * script, then we will do an implicit keep before the CL. */ if (topcs + 2*TASKSIZ <= STACKSIZ) if ((strcmp (newtask->t_ltp->lt_lname, "cl") == 0) || (strcmp (newtask->t_ltp->lt_lname, "clbye") == 0)) if ((currentask->t_flags & T_SCRIPT) && (prevtask->t_flags & T_SCRIPT)) keep(prevtask); /* If newtask is cleof(), close the input stream of the current * task (the task whose input contained the cleof), and reopen * as the null file. */ if (newtask->t_flags & T_CLEOF) { if (currentask->t_in != stdin) fclose (currentask->t_in); if (currentask != firstask) currentask->t_in = fopen ("dev$null", "r"); } if (!(firstask->t_flags & T_BATCH) && (newtask->t_in == stdin) && (newtask->t_out == stdout)) { newtask->t_flags |= T_INTERACTIVE; newtask->t_topd = topd; newtask->t_topos = topos; newtask->t_topcs = topcs; newtask->t_curpack = curpack; } } /* Standardize the pfile. * Set (or create if necessary) `$nargs', number of command line args, * based on pf_n which is set for each command line argument by * posargset, et al. * If this ltask had no paramfile and we built one up from the * command line, then we need to add a `mode' param. If it did have * a paramfile, then pfileload has already added it for us. * Point t_modep to the mode param for newtask. */ pp = paramfind (pfp, "$nargs", 0, YES); if (pp == NULL || (XINT)pp == ERR) { char nabuf[FAKEPARAMLEN]; sprintf (nabuf, "$nargs,i,h,%d\n", pfp->pf_n); pp = addparam (pfp, nabuf, NULL); pp->p_mode |= M_FAKE; /* never flush out $nargs */ } else pp->p_val.v_i = pfp->pf_n; if (pfp->pf_flags & PF_FAKE) { newtask->t_modep = addparam (pfp, "mode,s,h,q\n", NULL); /* pf_n will be used by paramsrch() to count positional arg * matches; see it and param.h. */ pfp->pf_n = 0; } else { newtask->t_modep = paramfind (pfp, "mode", 0, YES); } if (newtask->t_modep == NULL) cl_error (E_IERR, "no mode param for task `%s'", newtask->t_ltp->lt_lname); /* If task is being run in menu mode, call up eparam so that the user * can edit/inspect the parameters. If eparam is exited with ctrl/c * do not run the task or update the pfile. The parameter editor * will make a copy of the task's pfile(s), edit it, and if necessary * update the incore version created earlier by callnewtask(). */ if ((taskmode(newtask) & M_MENU) || (newtask->t_flags & T_PSET)) { if (epset (newtask->t_ltp->lt_lname) == ERR) { if (newtask->t_flags & T_PSET) cl_error (E_UERR, "parameter file not updated"); else cl_error (E_UERR, "menu mode task execution aborted"); } } /* Set up bascode so new task has a good place to start building * code. See how the pc is set up before each call to the parser in * main() loop. */ newtask->t_bascode = topos + 1; /* Set up io paths. If the new task is cl(), it's command input * and output streams are connected to those of the task which * called currentask. If the currentask is the firstask, there * was no caller (no prevtask), so we must watch out for that. * In the case of a script, commands are read from the script. * In the case of a process, commands are read from the process. */ if (newtask->t_flags & T_PSET) { newtask->t_in = fopen ("dev$null", "r"); newtask->t_out = newtask->t_stdout; } else if (newtask->t_flags & T_SCRIPT) { if (cltrace) eprintf ("\t----- exec script %s (%s) -----\n", newtask->t_ltp->lt_lname, newtask->t_ltp->lt_pname); newtask->t_in = fopen (newtask->t_ltp->lt_pname, "r"); if (newtask->t_in == NULL) cl_error (E_UERR|E_P, "can not open script file `%s'", newtask->t_ltp->lt_pname); newtask->t_out = newtask->t_stdout; } else if (newtask->t_flags & T_CL) { /* The command streams t_in and t_out have already been * set up above by set_clio() in the test for T_INTERACTIVE. */ /* Do nothing */ } else { char startup_msg[SZ_STARTUPMSG+1]; int timeit; /* Connect to an executable process. */ mk_startupmsg (newtask, startup_msg, SZ_STARTUPMSG); timeit = (newtask->t_flags & T_TIMEIT) != 0; if (cltrace) eprintf ("\t----- exec external task %s -----\n", newtask->t_ltp->lt_lname); newtask->t_pid = pr_connect ( findexe (newtask->t_ltp->lt_pkp, newtask->t_ltp->lt_pname), startup_msg, &newtask->t_in, &newtask->t_out, newtask->t_stdin, newtask->t_stdout, newtask->t_stderr, newtask->t_stdgraph, newtask->t_stdimage, newtask->t_stdplot, timeit); } yyin = newtask->t_in; /* set the input for the parser */ /* Tell parser what to expect. */ parse_state = PARSE_FREE; if (newtask->t_flags & T_SCRIPT) { proc_script = (newtask->t_flags & T_PSET) ? NO : procscript(yyin); if (proc_script) { parse_state = PARSE_BODY; /* Skip to the BEGIN statement */ newtask->t_scriptln = skip_to (yyin, "begin"); if (newtask->t_scriptln == ERR) cl_error (E_UERR, "No BEGIN statement in procedure script"); /* Reset pointer here. */ proc_script = NO; } } /* Log a start message for script and executable tasks. */ if (keeplog() && log_trace()) if (newtask->t_flags & T_SCRIPT || newtask->t_pid != -1) { char logmsg[SZ_LINE]; sprintf (logmsg, "Start (%s)", newtask->t_ltp->lt_pname); putlog (newtask, logmsg); } newtask->t_flags |= T_RUNNING; currentask = newtask; /* continue as new the new task; at last. */ if (cldebug) eprintf ("Returning from execnewtask.yyin, ct_in, nt_in:%d %d %d\n", yyin, currentask->t_in, newtask->t_in); }
int main(int argc, char *argv[]) { int r; endpoint_t user, caller; message m; int ipc_status; env_setargs(argc, argv); r = i2cdriver_env_parse(&bus, &address, valid_addrs); if (r < 0) { log_warn(&log, "Expecting -args 'bus=X address=0xYY'\n"); log_warn(&log, "Example -args 'bus=1 address=0x24'\n"); return EXIT_FAILURE; } else if (r > 0) { log_warn(&log, "Invalid slave address for device, expecting 0x24\n"); return EXIT_FAILURE; } sef_local_startup(); while (TRUE) { /* Receive Message */ r = sef_receive_status(ANY, &m, &ipc_status); if (r != OK) { log_warn(&log, "sef_receive_status() failed\n"); continue; } log_trace(&log, "Got a message 0x%x from 0x%x\n", m.m_type, m.m_source); if (is_ipc_notify(ipc_status)) { switch (m.m_source) { case DS_PROC_NR: /* bus driver changed state, update endpoint */ i2cdriver_handle_bus_update(&bus_endpoint, bus, address); break; case HARDWARE: intr_handler(); break; default: break; } /* Do not reply to notifications. */ continue; } caller = m.m_source; user = m.USER_ENDPT; /* * Handle Message * * So far this driver only deals with notifications * so it always replies to non-notifications with EINVAL. */ /* Send Reply */ m.m_type = TASK_REPLY; m.REP_ENDPT = user; m.REP_STATUS = EINVAL; r = sendnb(caller, &m); if (r != OK) { log_warn(&log, "sendnb() failed\n"); continue; } } return 0; }
int BackendSync::Client::copy(){ if(this->iter == NULL){ log_info("new iterator, last_key: '%s'", hexmem(last_key.data(), last_key.size()).c_str()); std::string key = this->last_key; if(this->last_key.empty()){ key.push_back(DataType::MIN_PREFIX); } this->iter = backend->ssdb->iterator(key, "", -1); log_info("iterator created, last_key: '%s'", hexmem(last_key.data(), last_key.size()).c_str()); } int ret = 0; int iterate_count = 0; int64_t stime = time_ms(); while(true){ // Prevent copy() from blocking too long if(++iterate_count > 1000 || link->output->size() > 2 * 1024 * 1024){ break; } if(!iter->next()){ goto copy_end; } Bytes key = iter->key(); if(key.size() == 0){ continue; } // finish copying all valid data types if(key.data()[0] > DataType::MAX_PREFIX){ goto copy_end; } Bytes val = iter->val(); this->last_key = key.String(); char cmd = 0; char data_type = key.data()[0]; if(data_type == DataType::KV){ cmd = BinlogCommand::KSET; }else if(data_type == DataType::HASH){ cmd = BinlogCommand::HSET; }else if(data_type == DataType::ZSET){ cmd = BinlogCommand::ZSET; }else if(data_type == DataType::QUEUE){ cmd = BinlogCommand::QPUSH_BACK; }else{ continue; } ret++; Binlog log(this->last_seq, BinlogType::COPY, cmd, slice(key)); log_trace("fd: %d, %s", link->fd(), log.dumps().c_str()); link->send(log.repr(), val); if(time_ms() - stime > 3000){ log_info("copy blocks too long, flush"); break; } } return ret; copy_end: log_info("%s:%d fd: %d, copy end", link->remote_ip, link->remote_port, link->fd()); this->status = Client::SYNC; delete this->iter; this->iter = NULL; Binlog log(this->last_seq, BinlogType::COPY, BinlogCommand::END, ""); log_trace("fd: %d, %s", link->fd(), log.dumps().c_str()); link->send(log.repr(), "copy_end"); return 1; }
CK_RV C_Login(CK_SESSION_HANDLE hSession, /* the session's handle */ CK_USER_TYPE userType, /* the user type */ CK_CHAR_PTR pPin, /* the user's PIN */ CK_ULONG ulPinLen) /* the length of the PIN */ { int ret; P11_SESSION *pSession = NULL; P11_SLOT *pSlot = NULL; CK_TOKEN_INFO tokeninfo; printf("\n********************\n"); printf("CK_RV C_Login called\n"); //return(CKR_OK); log_trace(WHERE, "I: enter"); ret = p11_lock(); //printf("p11_lock returns: %s\n",!ret ? "OK" : "ERROR"); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); //printf("LOCK failled!\n"); //printf("\n********************\n"); return ret; } if (isAcroread()) { return CKR_OK; } memset(&tokeninfo, 0, sizeof(CK_TOKEN_INFO)); log_trace(WHERE, "S: Login (session %d)", hSession); printf("Login (session %d)\n",hSession); if (userType != CKU_USER && userType != CKU_SO) { ret = CKR_USER_TYPE_INVALID; //printf("TIPO DE UTILIZADOR INVALIDO\n"); goto cleanup; } ret = p11_get_session(hSession, &pSession); if (ret) { //log_trace(WHERE, "E: Invalid session handle (%d)", hSession); //printf("INVALID SESSION HANDLE - %d -\n",hSession); goto cleanup; } pSlot = p11_get_slot(pSession->hslot); if (pSlot == NULL) { log_trace(WHERE, "E: Slot not found for session %d", hSession); ret = CKR_SESSION_HANDLE_INVALID; //printf("SLOT NOT FOUND FOR SESSION\n"); goto cleanup; } if (pSlot->login_type >= 0) { // Needed for Acrobat, in case you want to sign with a 2nd card ret = CKR_OK; //CKR_USER_ALREADY_LOGGED_IN; //printf("Acrobat caso especial!"); goto cleanup; } /* ret = cal_get_token_info(pSlot, &tokeninfo); if (ret != CKR_OK) { log_trace(WHERE, "E: could not find tokeninfo for slot %d", pSession->hslot); goto cleanup; } if ( !(tokeninfo.flags & CKF_USER_PIN_INITIALIZED) ) { ret = CKR_USER_PIN_NOT_INITIALIZED; goto cleanup; }*/ ret = cal_logon(pSession->hslot, ulPinLen, pPin, 0); if (ret == CKR_OK){ pSlot->login_type = userType; //printf("Tudo OK! - ret = %d\n",ret); } cleanup: p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); //printf("RET = %d\n",ret); //printf("\n********************\n"); return ret; }
int p11_add_slot_object(P11_SLOT *pSlot, CK_ATTRIBUTE_PTR pTemplate, CK_ULONG ulCount, CK_BBOOL bToken, CK_ULONG type, CK_ULONG id, CK_BBOOL bPrivate, CK_ULONG *phObject) { int ret = CKR_OK; P11_OBJECT *pObject = NULL; //unsigned int hObject = 0; *phObject = 0; ret = p11_new_slot_object(pSlot, phObject); if ((ret != 0) || (*phObject == 0)) { log_trace(WHERE, "E: could not add new slot object during init of objects"); return(ret); } pObject = p11_get_slot_object(pSlot, *phObject); //add room for attributes as in template pObject->pAttr = (CK_ATTRIBUTE_PTR) malloc(ulCount * sizeof(CK_ATTRIBUTE)); if (pObject->pAttr == NULL) { log_trace(WHERE, "E: alloc error for attribute"); return (CKR_HOST_MEMORY); } //set the size of the object attributes pObject->count = ulCount; //copy the template to the new object ret = p11_copy_object(pTemplate, ulCount, pObject->pAttr); if (ret) { log_trace(WHERE, "E: p11_copy_object() returned %d", ret); goto cleanup; } //CKA_TOKEN ret = p11_set_attribute_value(pObject->pAttr, ulCount, CKA_TOKEN, (CK_VOID_PTR) &bToken, sizeof(CK_BBOOL)); if (ret) { log_trace(WHERE, "E: p11_set_attribute_value(CKA_TOKEN) returned %d", ret); goto cleanup; } //CKA_CLASS ret = p11_set_attribute_value(pObject->pAttr, ulCount, CKA_CLASS, (CK_VOID_PTR) &type, sizeof(CK_ULONG)); if (ret) { log_trace(WHERE, "E: p11_set_attribute_value(CKA_CLASS) returned %d", ret); goto cleanup; } //CKA_ID ret = p11_set_attribute_value(pObject->pAttr, ulCount, CKA_ID, (CK_VOID_PTR) &id, sizeof(CK_ULONG)); if (ret) { log_trace(WHERE, "E: p11_set_attribute_value(CKA_ID) returned %d", ret); goto cleanup; } //CKA_PRIVATE ret = p11_set_attribute_value(pObject->pAttr, ulCount, CKA_PRIVATE, (CK_VOID_PTR) &bPrivate, sizeof(CK_BBOOL)); if (ret) { log_trace(WHERE, "E: p11_set_attribute_value(CKA_PRIVATE) returned %d", ret); goto cleanup; } cleanup: return (ret); }
void smisk_SessionStore_dealloc(smisk_SessionStore *self) { log_trace("ENTER"); Py_DECREF(self->name); self->ob_type->tp_free((PyObject*)self); }
PyObject *smisk_SessionStore_destroy(smisk_SessionStore *self, PyObject *session_id) { log_trace("ENTER"); PyErr_SetString(PyExc_NotImplementedError, "destroy"); return NULL; }
static uint16_t get_name_helper(const char* data, uint16_t data_len, const char* payload, uint16_t payload_len, char* name, uint16_t name_len, uint16_t recursion_level) { log_trace("dns", "_get_name_helper IN, datalen: %d namelen: %d recusion: %d", data_len, name_len, recursion_level); if (data_len == 0 || name_len == 0 || payload_len == 0) { log_trace("dns", "_get_name_helper OUT, err. 0 length field. datalen %d namelen %d payloadlen %d", data_len, name_len, payload_len); return 0; } if (recursion_level > MAX_LABEL_RECURSION) { log_trace("dns", "_get_name_helper OUT. ERR, MAX RECUSION"); return 0; } uint16_t bytes_consumed = 0; // The start of data is either a sequence of labels or a ptr. while(data_len > 0) { uint8_t byte = data[0]; // Is this a pointer? if (byte >= 0xc0) { log_trace("dns", "_get_name_helper, ptr encountered"); // Do we have enough bytes to check ahead? if (data_len < 2) { log_trace("dns", "_get_name_helper OUT. ptr byte encountered. No offset. ERR."); return 0; } // No. ntohs isn't needed here. It's because of // the upper 2 bits indicating a pointer. uint16_t offset = ((byte & 0x03) << 8) | (uint8_t)data[1]; log_trace("dns", "_get_name_helper. ptr offset 0x%x", offset); if (offset >= payload_len) { log_trace("dns", "_get_name_helper OUT. offset exceeded payload len %d ERR", payload_len); return 0; } // We need to add a dot if we are: // -- Not first level recursion. // -- have consumed bytes if (recursion_level > 0 || bytes_consumed > 0) { if (name_len < 1) { log_warn("dns", "Exceeded static name field allocation."); return 0; } name[0] = '.'; name++; name_len--; } uint16_t rec_bytes_consumed = get_name_helper(payload + offset, payload_len - offset, payload, payload_len, name, name_len, recursion_level + 1); // We are done so don't bother to increment the pointers. if (rec_bytes_consumed == 0) { log_trace("dns", "_get_name_helper OUT. rec level %d failed", recursion_level); return 0; } else { bytes_consumed += 2; log_trace("dns", "_get_name_helper OUT. rec level %d success. %d rec bytes consumed. %d bytes consumed.", recursion_level, rec_bytes_consumed, bytes_consumed); return bytes_consumed; } } else if (byte == '\0') { // don't bother with pointer incrementation. We're done. bytes_consumed += 1; log_trace("dns", "_get_name_helper OUT. rec level %d success. %d bytes consumed.", recursion_level, bytes_consumed); return bytes_consumed; } else { log_trace("dns", "_get_name_helper, segment 0x%hx encountered", byte); // We've now consumed a byte. ++data; --data_len; // Mark byte consumed after we check for first iteration. // Do we have enough data left (must have null byte too)? if ((byte+1) > data_len) { log_trace("dns", "_get_name_helper OUT. ERR. Not enough data for segment %hd"); return 0; } // If we've consumed any bytes and are in a label, we're in a // label chain. We need to add a dot. if (bytes_consumed > 0) { if (name_len < 1) { log_warn("dns", "Exceeded static name field allocation."); return 0; } name[0] = '.'; name++; name_len--; } // Now we've consumed a byte. ++bytes_consumed; // Did we run out of our arbitrary buffer? if (byte > name_len) { log_warn("dns", "Exceeded static name field allocation."); return 0; } assert(data_len > 0); memcpy(name, data, byte); name += byte; name_len -= byte; data_len -= byte; data += byte; bytes_consumed += byte; // Handled in the byte+1 check above. assert(data_len > 0); } } // We should never get here. // For each byte we either have: // -- a ptr, which terminates // -- a null byte, which terminates // -- a segment length which either terminates or ensures we keep looping assert(0); return 0; }
static bool process_response_answer(char **data, uint16_t* data_len, const char* payload, uint16_t payload_len, fieldset_t* list) { log_trace("dns", "call to process_response_answer, data_len: %d", *data_len); // Payload is the start of the DNS packet, including header // data is handle to the start of this RR // data_len is a pointer to the how much total data we have to work with. // This is awful. I'm bad and should feel bad. uint16_t bytes_consumed = 0; char* answer_name = get_name(*data, *data_len, payload, payload_len, &bytes_consumed); // Error. if (answer_name == NULL) { return 1; } assert(bytes_consumed > 0); if ( (bytes_consumed + sizeof(dns_answer_tail)) > *data_len) { free(answer_name); return 1; } dns_answer_tail* tail = (dns_answer_tail*)(*data + bytes_consumed); uint16_t type = ntohs(tail->type); uint16_t class = ntohs(tail->class); uint32_t ttl = ntohl(tail->ttl); uint16_t rdlength = ntohs(tail->rdlength); char* rdata = tail->rdata; if ((rdlength + bytes_consumed + sizeof(dns_answer_tail)) > *data_len) { free(answer_name); return 1; } // Build our new question fieldset fieldset_t *afs = fs_new_fieldset(); fs_add_unsafe_string(afs, "name", answer_name, 1); fs_add_uint64(afs, "type", type); if (type > MAX_QTYPE || qtype_qtype_to_strid[type] == BAD_QTYPE_VAL) { fs_add_string(afs, "type_str", (char*) BAD_QTYPE_STR, 0); } else { // I've written worse things than this 3rd arg. But I want to be fast. fs_add_string(afs, "type_str", (char*)qtype_strs[qtype_qtype_to_strid[type]], 0); } fs_add_uint64(afs, "class", class); fs_add_uint64(afs, "ttl", ttl); fs_add_uint64(afs, "rdlength", rdlength); // XXX Fill this out for the other types we care about. if (type == DNS_QTYPE_NS || type == DNS_QTYPE_CNAME) { uint16_t rdata_bytes_consumed = 0; char* rdata_name = get_name(rdata, rdlength, payload, payload_len, &rdata_bytes_consumed); if (rdata_name == NULL) { fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { fs_add_uint64(afs, "rdata_is_parsed", 1); fs_add_unsafe_string(afs, "rdata", rdata_name, 1); } } else if (type == DNS_QTYPE_MX) { uint16_t rdata_bytes_consumed = 0; if (rdlength <= 4) { fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { char* rdata_name = get_name(rdata + 2, rdlength-2, payload, payload_len, &rdata_bytes_consumed); if (rdata_name == NULL) { fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { // (largest value 16bit) + " " + answer + null char* rdata_with_pref = xmalloc(5 + 1 + strlen(rdata_name) + 1); uint8_t num_printed = snprintf(rdata_with_pref, 6, "%hu ", ntohs( *(uint16_t*)rdata)); memcpy(rdata_with_pref + num_printed, rdata_name, strlen(rdata_name)); fs_add_uint64(afs, "rdata_is_parsed", 1); fs_add_unsafe_string(afs, "rdata", rdata_with_pref, 1); } } } else if (type == DNS_QTYPE_TXT) { if (rdlength >= 1 && (rdlength - 1) != *(uint8_t*)rdata ) { log_warn("dns", "TXT record with wrong TXT len. Not processing."); fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { fs_add_uint64(afs, "rdata_is_parsed", 1); char* txt = xmalloc(rdlength); memcpy(txt, rdata + 1, rdlength-1); fs_add_unsafe_string(afs, "rdata", txt, 1); } } else if (type == DNS_QTYPE_A) { if (rdlength != 4) { log_warn("dns", "A record with IP of length %d. Not processing.", rdlength); fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { fs_add_uint64(afs, "rdata_is_parsed", 1); char* addr = strdup(inet_ntoa( *(struct in_addr*)rdata )); fs_add_unsafe_string(afs, "rdata", addr, 1); } } else if (type == DNS_QTYPE_AAAA) { if (rdlength != 16) { log_warn("dns", "AAAA record with IP of length %d. Not processing.", rdlength); fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } else { fs_add_uint64(afs, "rdata_is_parsed", 1); char* ipv6_str = xmalloc(INET6_ADDRSTRLEN); inet_ntop(AF_INET6, (struct sockaddr_in6*)rdata, ipv6_str,INET6_ADDRSTRLEN); fs_add_unsafe_string(afs, "rdata", ipv6_str, 1); } } else { fs_add_uint64(afs, "rdata_is_parsed", 0); fs_add_binary(afs, "rdata", rdlength, rdata, 0); } // Now we're adding the new fs to the list. fs_add_fieldset(list, NULL, afs); // Now update the pointers. *data = *data + bytes_consumed + sizeof(dns_answer_tail) + rdlength; *data_len = *data_len - bytes_consumed - sizeof(dns_answer_tail) - rdlength; log_trace("dns", "return success from process_response_answer, data_len: %d", *data_len); return 0; }
bool Connection::readHandshake() { log_trace("Connection::readHandshake"); std::streambuf* sb = _ios->rdbuf(); if( ! sb) return true; _maxImport = sb->in_avail(); _wantRead = false; _isReading = true; OSStatus status = SSLHandshake(_context); _isReading = false; log_debug("SSLHandshake returns " << status); if( status == noErr ) { log_debug("SSL handshake completed"); _connected = true; return false; } #ifdef PT_IOS if(status == errSSLPeerAuthCompleted) #else if(status == errSSLServerAuthCompleted) #endif { log_debug("authenticating peer"); if( _ctx->verifyMode() != NoVerify ) { log_debug("evaluating trust"); SecTrustRef trust = NULL; SSLCopyPeerTrust(_context, &trust); CFArrayRef caArr = _ctx->impl()->caCertificates(); SecTrustSetAnchorCertificates(trust, caArr); SecTrustSetAnchorCertificatesOnly(trust, true); SecTrustResultType result; OSStatus evalErr = SecTrustEvaluate(trust, &result); if(evalErr) throw HandshakeFailed("SSL handshake failed"); CFIndex count = SecTrustGetCertificateCount(trust); log_debug("SecTrustEvaluate: " << result << " certs: " << count); if(trust) CFRelease(trust); // if peer presented no certificate, SecTrustGetCertificateCount // should return 0. If we require one because AlwaysVerify is // set, the handshake is considered to be failed if(_ctx->verifyMode() == AlwaysVerify && count == 0) throw HandshakeFailed("SSL handshake failed"); if( (result != kSecTrustResultProceed) && (result != kSecTrustResultUnspecified) ) throw HandshakeFailed("SSL handshake failed"); log_debug("authentication successful"); } return readHandshake(); } if( status != errSSLWouldBlock ) { throw HandshakeFailed("SSL handshake failed"); } return _wantRead; }
static void on_psub_disconnect(struct evhttp_connection *evcon, void *arg){ log_trace("presence subscriber disconnected"); PresenceSubscriber *psub = (PresenceSubscriber *)arg; Server *serv = psub->serv; serv->psub_end(psub); }
int BackendSync::Client::sync(SyncLogQueue *logs){ Buffer *output = link->output; uint64_t expect_seq = this->last_seq + 1; Synclog log; int ret; if(this->status == Client::DUMP && this->last_seq == 0){ ret = logs->find_last(&log); }else{ ret = logs->find(expect_seq, &log); } if(ret == 0){ return 0; } /* log_trace("fd: %d, seq: %llu, key: %s", link->fd(), log.seq(), hexmem(log.key().data(), log.key().size()).c_str()); */ // writes that are out of dumped range will be discarded. if(this->iter && log.key() > this->last_key){ // update last_seq this->last_seq = log.seq(); log_trace("fd: %d, seq: %llu, drop: %s, last_key: %s", link->fd(), log.seq(), hexmem(log.key().data(), log.key().size()).c_str(), hexmem(this->last_key.data(), this->last_key.size()).c_str()); return 1; } if(this->last_seq != 0 && log.seq() != expect_seq){ log_warn("fd: %d, OUT_OF_SYNC! seq: %llu, last_seq: %llu", link->fd(), log.seq(), expect_seq ); this->status = Client::OUT_OF_SYNC; return 1; } // update last_seq this->last_seq = log.seq(); char seq_buf[20]; snprintf(seq_buf, sizeof(seq_buf), "%llu", log.seq()); char log_type = log.type(); // a synclog from a mirror server will not be send to another mirror server if(this->is_mirror && (log_type == Synclog::MIRROR_SET || log_type == Synclog::MIRROR_DEL)){ if(this->last_seq - this->last_noop_seq >= logs->total/2){ this->last_noop_seq = this->last_seq; log_trace("fd: %d, sync noop %llu", link->fd(), log.seq()); output->append_record("noop"); output->append_record(seq_buf); output->append('\n'); } }else if(log_type == Synclog::SET || log_type == Synclog::MIRROR_SET){ std::string val; int ret = backend->ssdb->raw_get(log.key(), &val); if(ret == -1){ log_error("raw_get error!"); }else if(ret == 0){ log_trace("skip not found: %s", hexmem(log.key().data(), log.key().size()).c_str()); // not found, ignore }else{ log_trace("fd: %d, sync_set %llu %s", link->fd(), log.seq(), hexmem(log.key().data(), log.key().size()).c_str()); output->append_record("sync_set"); output->append_record(seq_buf); output->append_record(log.key()); output->append_record(val); output->append('\n'); } }else if(log_type == Synclog::DEL || log_type == Synclog::MIRROR_DEL){ log_trace("fd: %d, sync_del %llu %s", link->fd(), log.seq(), hexmem(log.key().data(), log.key().size()).c_str()); output->append_record("sync_del"); output->append_record(seq_buf); output->append_record(log.key()); output->append('\n'); }else{ log_error("unknown sync log type: %d", log.type()); } return 1; }
Vector::Vector(const QString& name, QStringList labels, double x, double y, double z, double w) : Base(ComponentType, name), m_labels(labels), m_values{ {x,y,z,w} } { this->m_output = nullptr; log_trace(Log::New, this); }
/* IOFINISH -- Flush out and wrap up all pending io for given task. * Called when the task is dying and it wants to close all files it opened. * This includes a pipe if it used one, a file if it was a script and io * redirections as indicated by the T_MYXXX flags. The T_MYXXX flags are * set only when the redirections were done for this task, ie, they were * not simply inherited. * Just as a fail-safe measure, always check that a real stdio file is * not being closed. * Don't call error() because in trying to restor to an interactive task * it might call us again and cause an inf. loop. */ void iofinish ( register struct task *tp ) { register FILE *fp; int flags; flags = tp->t_flags; /* Make sure we do not close files more than once. */ if (flags & T_RUNNING) tp->t_flags &= ~T_RUNNING; else return; if (cldebug) eprintf ("flushing io for task `%s'\n", tp->t_ltp->lt_lname); if (flags & T_MYIN) { fp = tp->t_stdin; if (fp != stdin) fclose (fp); } if (flags & T_MYOUT) { fflush (fp = tp->t_stdout); if (fp != stdout) fclose (fp); } if (flags & T_MYERR) { fflush (fp = tp->t_stderr); if (fp != stderr) fclose (fp); } /* Close any redirected graphics output streams. */ if (flags & (T_MYSTDGRAPH|T_MYSTDIMAGE|T_MYSTDPLOT)) { if (flags & T_MYSTDGRAPH) if (tp->t_stdgraph != tp->t_stdimage && tp->t_stdgraph != tp->t_stdplot) fclose (tp->t_stdgraph); if (flags & T_MYSTDIMAGE) if (tp->t_stdimage != tp->t_stdplot) fclose (tp->t_stdimage); if (flags & T_MYSTDPLOT) fclose (tp->t_stdplot); } /* If task i/o is redirected to a subprocess send the done message. */ if (flags & T_IPCIO) fputs (IPCDONEMSG, tp->t_out); fflush (tp->t_out); /* Close files only for script task, not for a cl, a builtin, or * a process. Do call disconnect if the task lives in a process. */ if (flags & T_SCRIPT) { fp = tp->t_in; if (fp != stdin) fclose (fp); } else if (flags & (T_CL|T_BUILTIN)) { ; } else if (tp->t_pid != -1) pr_disconnect (tp->t_pid); /* Log a stop message for script and executable tasks. */ if (keeplog() && log_trace()) if (tp->t_flags & T_SCRIPT || tp->t_pid != -1) putlog (tp, "Stop"); }
int smisk_SessionStore_register_types(PyObject *module) { log_trace("ENTER"); if (PyType_Ready(&smisk_SessionStoreType) == 0) return PyModule_AddObject(module, "SessionStore", (PyObject *)&smisk_SessionStoreType); return -1; }
CK_RV C_GetSlotList(CK_BBOOL tokenPresent, /* only slots with token present */ CK_SLOT_ID_PTR pSlotList, /* receives the array of slot IDs */ CK_ULONG_PTR pulCount) /* receives the number of slots */ { P11_SLOT *pSlot; CK_RV ret = CKR_OK; int h; CK_ULONG c = 0; static int l=0; log_trace(WHERE, "I: enter"); if (p11_get_init() != BEIDP11_INITIALIZED) { log_trace(WHERE, "I: leave, CKR_CRYPTOKI_NOT_INITIALIZED"); return (CKR_CRYPTOKI_NOT_INITIALIZED); } ret = p11_lock(); log_trace(WHERE, "I: p11_lock() acquiered"); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return (ret); } if (++l<LOG_MAX_REC) log_trace(WHERE, "S: C_GetSlotList()"); if (pulCount == NULL_PTR) { ret = CKR_ARGUMENTS_BAD; goto cleanup; } #ifdef PKCS11_V2_20 if(pSlotList == NULL){ ret = cal_refresh_readers(); } #endif //init slots allready done //update info on tokens in slot, could be removed if thread keeps track of these token states //BUG in Adobe Acrobat reader: adobe asks for slots with pSlotList = NULL, so only nr of slots will be returned. This is ok. //a second time Adobe calls this, pSlotList still is NULL, so the array with SlotIDs cannot be returned, again, nr of slots is returned. //Adobe just assumes that the first slot has ID=0 !!! and uses this ID=0 for all further actions. //to overcome this problem, we start our SlotIDs from 0 and not 1 !!! log_trace(WHERE, "I: h=0"); //Do not show the virtual reader (used to capture the reader connect events) //for (h=0; h < (p11_get_nreaders()-1); h++) for (h=0; h < p11_get_nreaders(); h++) { log_trace(WHERE, "I: h=%i",h); pSlot = p11_get_slot(h); if (l < LOG_MAX_REC) log_trace(WHERE, "I: slot[%d]: %s", h, pSlot->name); if (tokenPresent == CK_TRUE) { int pPresent = 0; ret = cal_token_present(h, &pPresent); if(ret != CKR_OK && ret != CKR_TOKEN_NOT_RECOGNIZED) { goto cleanup; } if (pPresent) { log_trace(WHERE, "I: cal_token_present"); c++; if ((pSlotList != NULL_PTR) && (c <= *pulCount) ) pSlotList[c-1] = h; } continue; } else { //get all slots c++; if ((pSlotList != NULL_PTR) && (c <= *pulCount) ) { pSlotList[c-1] = h; } continue; } } //end for #ifdef PKCS11_FF //return the fake slotID for the attached/removed reader if (cal_getgnFFReaders()!= 0) { //return a higher number of slots, so FF starts waiting for slotchanges again if(pSlotList == NULL) { c = cal_getgnFFReaders(); } else { for(; h < cal_getgnFFReaders(); h++) { log_trace(WHERE, "I: h=%i",h); c++; if (c <= *pulCount ) pSlotList[c-1] = h; } } } #endif //if more slots are found than can be returned in slotlist, return buffer too smal if ((c > *pulCount) && (pSlotList != NULL_PTR) ) ret = CKR_BUFFER_TOO_SMALL; //number of slots should always be returned. *pulCount = c; cleanup: log_trace(WHERE, "I: p11_unlock()"); p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); return ret; }
int smisk_SessionStore_init(smisk_SessionStore *self, PyObject *args, PyObject *kwargs) { log_trace("ENTER"); return 0; }
CK_RV C_GetSlotInfo(CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo) { CK_RV ret; P11_SLOT *slot; static int l=0; int isPresent = 0; log_trace(WHERE, "I: enter"); if (p11_get_init() != BEIDP11_INITIALIZED) { log_trace(WHERE, "I: leave, CKR_CRYPTOKI_NOT_INITIALIZED"); return (CKR_CRYPTOKI_NOT_INITIALIZED); } ret = p11_lock(); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return ret; } if (++l < LOG_MAX_REC) log_trace(WHERE, "S: C_GetSlotInfo(slot %d)", slotID); if (pInfo == NULL_PTR) { log_trace(WHERE, "E: pInfo = NULL"); CLEANUP(CKR_ARGUMENTS_BAD); } slot = p11_get_slot(slotID); if (slot == NULL) { log_trace(WHERE, "E: p11_get_slot(%d) returns null", slotID); CLEANUP(CKR_SLOT_ID_INVALID); } //fill in slot info strcpy_n(pInfo->slotDescription, slot->name, 64, ' '); strcpy_n(pInfo->manufacturerID, "_ID_", 32, ' '); pInfo->flags = CKF_REMOVABLE_DEVICE | CKF_HW_SLOT; pInfo->hardwareVersion.major = 1; pInfo->hardwareVersion.minor = 0; pInfo->firmwareVersion.major = 1; pInfo->firmwareVersion.minor = 0; //check if token is present ret = (cal_token_present(slotID, &isPresent)); if(ret != CKR_OK) goto cleanup; if (isPresent) { pInfo->flags |= CKF_TOKEN_PRESENT; } cleanup: p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); return ret; }
PyObject *smisk_SessionStore_write(smisk_SessionStore *self, PyObject *args) { log_trace("ENTER"); PyErr_SetString(PyExc_NotImplementedError, "write"); return NULL; }
CK_RV C_Initialize(CK_VOID_PTR pReserved) { int ret = CKR_OK; CK_C_INITIALIZE_ARGS_PTR p_args; unsigned char initial_state = p11_get_init(); #if _DEBUG log_init(DEFAULT_LOG_FILE, LOG_LEVEL_PKCS11_INFO); #else log_init(DEFAULT_LOG_FILE, LOG_LEVEL_PKCS11_NONE); #endif log_trace(WHERE, "I: enter pReserved = %p",pReserved); if (p11_get_init() != BEIDP11_NOT_INITIALIZED) { ret = CKR_CRYPTOKI_ALREADY_INITIALIZED; log_trace(WHERE, "I: Module is allready initialized"); } else { //g_init = BEIDP11_INITIALIZED; p11_set_init(BEIDP11_INITIALIZING); if (pReserved != NULL) { p_args = (CK_C_INITIALIZE_ARGS *)pReserved; if(p_args->pReserved != NULL) { ret = CKR_ARGUMENTS_BAD; goto cleanup; } if( (p_args->CreateMutex == NULL) || (p_args->DestroyMutex == NULL) || \ (p_args->LockMutex == NULL) || (p_args->UnlockMutex == NULL) ) { log_trace(WHERE, "S: use supplied locking mechanism"); //If some, but not all, of the supplied function pointers to C_Initialize are non-NULL_PTR, //then C_Initialize should return with the value CKR_ARGUMENTS_BAD. if(!((p_args->CreateMutex == NULL) && (p_args->DestroyMutex == NULL) && \ (p_args->LockMutex == NULL) && (p_args->UnlockMutex == NULL))) { ret = CKR_ARGUMENTS_BAD; goto cleanup; } } log_trace(WHERE, "S: p11_init_lock"); p11_init_lock(p_args); } cal_init(); p11_set_init(BEIDP11_INITIALIZED); log_trace(WHERE, "S: Initialize this PKCS11 Module"); log_trace(WHERE, "S: ============================="); /*#ifdef PKCS11_FF cal_init_pcsc(); #endif*/ } cleanup: log_trace(WHERE, "I: leave, ret = %i",ret); if (ret != CKR_OK) { p11_set_init(initial_state); } return ret; }
CK_RV C_GetSessionInfo(CK_SESSION_HANDLE hSession, /* the session's handle */ CK_SESSION_INFO_PTR pInfo) /* receives session information */ { int ret; char buf[256]; P11_SESSION *pSession = NULL; P11_SLOT *pSlot = NULL; CK_TOKEN_INFO tokeninfo; log_trace(WHERE, "I: enter"); ret = p11_lock(); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return ret; } log_trace(WHERE, "S: C_GetSessionInfo(session %d)", hSession); if (pInfo == NULL_PTR) { ret = CKR_ARGUMENTS_BAD; goto cleanup; } ret = p11_get_session(hSession, &pSession); if (ret) { log_trace(WHERE, "E: Invalid session handle (%d) (%s)", hSession, log_map_error(ret)); goto cleanup; } pInfo->slotID = pSession->hslot; pInfo->flags = pSession->flags; pInfo->ulDeviceError = 0; pSlot = p11_get_slot(pSession->hslot); if (pSlot == NULL) { log_trace(WHERE, "E: slot not found for session %d", hSession); ret = CKR_SESSION_HANDLE_INVALID; goto cleanup; } //SO only can create RW_SO sessions if (pSlot->login_type == CKU_SO) { pInfo->state = CKS_RW_SO_FUNCTIONS; } //USER can create RW or RO sessions else if (pSlot->login_type == CKU_USER) { pInfo->state = (pSession->flags & CKF_RW_SESSION)? CKS_RW_USER_FUNCTIONS : CKS_RO_USER_FUNCTIONS; } //if login not required => we can also get USER sessions without being logged on else { ret = cal_get_token_info(pSession->hslot, &tokeninfo); if ( (ret == CKR_OK) && !(tokeninfo.flags & CKF_LOGIN_REQUIRED) ) pInfo->state = (pSession->flags & CKF_RW_SESSION)? CKS_RW_USER_FUNCTIONS : CKS_RO_USER_FUNCTIONS; else pInfo->state = (pSession->flags & CKF_RW_SESSION) ? CKS_RW_PUBLIC_SESSION : CKS_RO_PUBLIC_SESSION; } cleanup: p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); return ret; }
CK_RV C_WaitForSlotEvent(CK_FLAGS flags, /* blocking/nonblocking flag */ CK_SLOT_ID_PTR pSlot, /* location that receives the slot ID */ CK_VOID_PTR pReserved) /* reserved. Should be NULL_PTR */ { CK_RV ret = CKR_OK; int h; P11_SLOT *p11Slot = NULL; int i = 0; CK_BBOOL locked = CK_FALSE; #ifdef PKCS11_FF CK_BBOOL bRunning = CK_TRUE; long error = 0; #endif log_trace(WHERE, "I: enter"); //need to check initialization before lock, as lock might be in progress of being set up if (p11_get_init() != BEIDP11_INITIALIZED) { log_trace(WHERE, "I: leave, CKR_CRYPTOKI_NOT_INITIALIZED"); return (CKR_CRYPTOKI_NOT_INITIALIZED); } #ifdef PKCS11_FF /*error = cal_check_pcsc(&bRunning); if(bRunning == CK_FALSE) { while( (error == 0) && (bRunning == CK_FALSE) ) { cal_wait (500); error = cal_check_pcsc(&bRunning); //check if pkcs11 isn't finalizing if (p11_get_init() != BEIDP11_INITIALIZED) { log_trace(WHERE, "I: leave, CKR_CRYPTOKI_NO_LONGER_INITIALIZED"); return (CKR_CRYPTOKI_NOT_INITIALIZED); } } //pcsc just got launched, so establish a new context ret = p11_lock(); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return ret; } //check if nowhere else the context has been reestablished //TODO : if() cal_re_establish_context(); p11_unlock(); }*/ #endif ret = p11_lock(); if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return ret; } //check again, in case c_finalize got the lock right before we did //(then c_finalize will give us a chance to fall through, right before he resets the lock)) if (p11_get_init() != BEIDP11_INITIALIZED) { log_trace(WHERE, "I: leave, CKR_CRYPTOKI_NOT_INITIALIZED"); p11_unlock(); return (CKR_CRYPTOKI_NOT_INITIALIZED); } locked = CK_TRUE; log_trace(WHERE, "S: C_WaitForSlotEvent(flags = 0x%0x)", flags); // Doesn't seem to work on Linux: if you insert a card then Mozilla freezes // until you remove the card. This function however seems to work fine. #ifndef _WIN32 CLEANUP(CKR_FUNCTION_NOT_SUPPORTED); #endif //first check if no events are set for slots in previous run //this could happen if more cards are inserted/removed at the same time for (i=0; i < p11_get_nreaders(); i++) { p11Slot = p11_get_slot(i); if(p11Slot == NULL) CLEANUP(CKR_FUNCTION_FAILED); if (p11Slot->ievent != P11_EVENT_NONE) { #ifdef PKCS11_FF //in case the upnp reader caused the event, return a new slotnumber if( (i+1) == p11_get_nreaders()) { if(cal_getgnFFReaders() == 0) { cal_setgnFFReaders(p11_get_nreaders()+1); } else { cal_incgnFFReaders(); } i = (cal_getgnFFReaders()-1); } #endif *pSlot = i; //clear event p11Slot->ievent = P11_EVENT_NONE; CLEANUP(CKR_OK); } } if (flags & CKF_DONT_BLOCK) { ret = cal_wait_for_slot_event(0);//0 means don't block } else { ret = cal_wait_for_slot_event(1);//1 means block, lock will get released here //ret is 0x30 when SCardGetStatusChange gets cancelled if ((p11_get_init() == BEIDP11_NOT_INITIALIZED ) || (p11_get_init() == BEIDP11_DEINITIALIZING) || (ret == CKR_CRYPTOKI_NOT_INITIALIZED) ) { log_trace(WHERE, "I: CKR_CRYPTOKI_NOT_INITIALIZED"); p11_unlock(); return(CKR_CRYPTOKI_NOT_INITIALIZED); } } if(ret != CKR_OK) goto cleanup; ret = cal_get_slot_changes(&h); if (ret == CKR_OK) *pSlot = h; //else CKR_NO_EVENT /* Firefox 1.5 tries to call this function (with the blocking flag) * in a separate thread; and this causes the pkcs11 lib to hang on Linux * So we might have to return "not supported" in which case Ff 1.5 defaults * to polling in the main thread, like before. */ cleanup: if(locked == CK_TRUE) p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); return ret; }
CK_RV C_OpenSession(CK_SLOT_ID slotID, /* the slot's ID */ CK_FLAGS flags, /* defined in CK_SESSION_INFO */ CK_VOID_PTR pApplication, /* pointer passed to callback */ CK_NOTIFY Notify, /* notification callback function */ CK_SESSION_HANDLE_PTR phSession) /* receives new session handle */ { int ret; P11_SLOT* pSlot = NULL; P11_SESSION *pSession = NULL; // CAutoMutex(&g_oSlotMutex); log_trace(WHERE, "I: enter"); ret = p11_lock(slotID); /* mutex per slot slot 0 tot 9 FF=global slot*/ if (ret != CKR_OK) { log_trace(WHERE, "I: leave, p11_lock failed with %i",ret); return ret; } log_trace(WHERE, "S: C_OpenSession (slot %d)", slotID); if (!(flags & CKF_SERIAL_SESSION)) { ret = CKR_SESSION_PARALLEL_NOT_SUPPORTED; goto cleanup; } //XXX check this /* if (flags & ~(CKF_SERIAL_SESSION | CKF_RW_SESSION)) { ret = CKR_ARGUMENTS_BAD; goto cleanup; }*/ pSlot = p11_get_slot(slotID); if (pSlot == NULL) { log_trace(WHERE, "E: p11_get_slot(%d) returns null", slotID); ret = CKR_SLOT_ID_INVALID; goto cleanup; } /* Check that no conflictions sessions exist */ /* RO session when SO session exists is not allowed */ if ( !(flags & CKF_RW_SESSION) && (pSlot->login_type == CKU_SO)) { log_trace(WHERE, "E: R/W Session exists", slotID); ret = CKR_SESSION_READ_WRITE_SO_EXISTS; goto cleanup; } //get a free session object reserve it by setting inuse flag ret = p11_get_free_session(phSession, &pSession); if (ret != CKR_OK) { log_trace(WHERE, "E: p11_get_free_session() returns %d", ret); goto cleanup; } //connect to card if present ret = cal_connect(slotID); if (ret != CKR_OK) { //printf("Did not connect to card!!!!\n"); log_trace(WHERE, "E: cal_connect(slot %d) failed", slotID); //release session so it can be reused pSession->inuse = 0; goto cleanup; } //printf("in use? %d... slotID = %d\n",pSession->inuse,slotID); pSession->hslot = slotID; pSession->flags = flags; pSession->pdNotify = pApplication; pSession->pfNotify = Notify; //initial state pSession->state = P11_CARD_STILL_PRESENT; /* keep the nr of sessions for this slot */ pSlot->nsessions++; log_trace(WHERE, "S: Open session (slot %d: hsession = %d )", slotID, *phSession); cleanup: p11_unlock(); log_trace(WHERE, "I: leave, ret = %i",ret); return ret; }
void OpensslStream::accept(const OpensslServer& server, bool inherit) { log_trace("accept"); cxxtools::net::TcpSocket::accept(server, inherit); }
int read_bluetooth(time_t const bt_timeout, int const sfd, int *rr, unsigned char *received, int cc, unsigned char *last_sent, int *terminated ) { int bytes_read,i; unsigned char buf[1024]; /*read buffer*/ unsigned char header[3]; /*read buffer*/ struct timeval tv; fd_set readfds; tv.tv_sec = bt_timeout; // set timeout of reading tv.tv_usec = 0; memset(buf,0,1024); FD_ZERO(&readfds); FD_SET((sfd), &readfds); select((sfd)+1, &readfds, NULL, NULL, &tv); (*terminated) = 0; // Tag to tell if string has 7e termination // first read the header to get the record length if (FD_ISSET((sfd), &readfds)){ // did we receive anything within 5 seconds bytes_read = recv((sfd), header, sizeof(header), 0); //Get length of string (*rr) = 0; for( i=0; i<sizeof(header); i++ ) { received[(*rr)] = header[i]; // log_trace("%02x ", received[i]); (*rr)++; } } else { log_warning("Timeout reading bluetooth socket"); (*rr) = 0; memset(received,0,1024); return -1; } if (FD_ISSET((sfd), &readfds)){ // did we receive anything within 5 seconds bytes_read = recv((sfd), buf, header[1]-3, 0); //Read the length specified by header } else { log_warning("Timeout reading bluetooth socket"); (*rr) = 0; memset(received,0,1024); return -1; } if ( bytes_read > 0){ hlog_debug("Receiving - header", header, sizeof(header), 12); hlog_debug("Receiving - body ", buf, bytes_read, 0); if ((cc==bytes_read)&&(memcmp(received,last_sent,cc) == 0)){ log_error( "ERROR received what we sent!" ); abort(); //Need to do something } if( buf[ bytes_read-1 ] == 0x7e ) (*terminated) = 1; else (*terminated) = 0; for (i=0;i<bytes_read;i++){ //start copy the rec buffer in to received if (buf[i] == 0x7d){ //did we receive the escape char switch (buf[i+1]){ // act depending on the char after the escape char case 0x5e : received[(*rr)] = 0x7e; break; case 0x5d : received[(*rr)] = 0x7d; break; default : received[(*rr)] = buf[i+1] ^ 0x20; break; } i++; } else { received[(*rr)] = buf[i]; } // log_trace("%02x ", received[(*rr)]); (*rr)++; } fix_length_received( received, rr ); log_trace("received", received, *rr, 0); } return 0; }
int queue_message_commit(uint32_t msgid) { int r; char msgpath[PATH_MAX]; char tmppath[PATH_MAX]; FILE *ifp = NULL; FILE *ofp = NULL; profile_enter("queue_message_commit"); queue_message_path(msgid, msgpath, sizeof(msgpath)); if (env->sc_queue_flags & QUEUE_COMPRESSION) { bsnprintf(tmppath, sizeof tmppath, "%s.comp", msgpath); ifp = fopen(msgpath, "r"); ofp = fopen(tmppath, "w+"); if (ifp == NULL || ofp == NULL) goto err; if (! compress_file(ifp, ofp)) goto err; fclose(ifp); fclose(ofp); ifp = NULL; ofp = NULL; if (rename(tmppath, msgpath) == -1) { if (errno == ENOSPC) return (0); unlink(tmppath); log_warn("rename"); return (0); } } #ifdef HAVE_GCM_CRYPTO if (env->sc_queue_flags & QUEUE_ENCRYPTION) { bsnprintf(tmppath, sizeof tmppath, "%s.enc", msgpath); ifp = fopen(msgpath, "r"); ofp = fopen(tmppath, "w+"); if (ifp == NULL || ofp == NULL) goto err; if (! crypto_encrypt_file(ifp, ofp)) goto err; fclose(ifp); fclose(ofp); ifp = NULL; ofp = NULL; if (rename(tmppath, msgpath) == -1) { if (errno == ENOSPC) return (0); unlink(tmppath); log_warn("rename"); return (0); } } #endif r = handler_message_commit(msgid, msgpath); profile_leave(); /* in case it's not done by the backend */ unlink(msgpath); log_trace(TRACE_QUEUE, "queue-backend: queue_message_commit(%08"PRIx32") -> %d", msgid, r); return (r); err: if (ifp) fclose(ifp); if (ofp) fclose(ofp); return 0; }
int Slave::proc_sync(const Binlog &log, const std::vector<Bytes> &req){ switch(log.cmd()){ case BinlogCommand::KSET: { if(req.size() != 2){ break; } std::string key; if(decode_kv_key(log.key(), &key) == -1){ break; } log_trace("set %s", hexmem(key.data(), key.size()).c_str()); if(ssdb->set(key, req[1], log_type) == -1){ return -1; } } break; case BinlogCommand::KDEL: { std::string key; if(decode_kv_key(log.key(), &key) == -1){ break; } log_trace("del %s", hexmem(key.data(), key.size()).c_str()); if(ssdb->del(key, log_type) == -1){ return -1; } } break; case BinlogCommand::HSET: { if(req.size() != 2){ break; } std::string name, key; if(decode_hash_key(log.key(), &name, &key) == -1){ break; } log_trace("hset %s %s", hexmem(name.data(), name.size()).c_str(), hexmem(key.data(), key.size()).c_str()); if(ssdb->hset(name, key, req[1], log_type) == -1){ return -1; } } break; case BinlogCommand::HDEL: { std::string name, key; if(decode_hash_key(log.key(), &name, &key) == -1){ break; } log_trace("hdel %s %s", hexmem(name.data(), name.size()).c_str(), hexmem(key.data(), key.size()).c_str()); if(ssdb->hdel(name, key, log_type) == -1){ return -1; } } break; case BinlogCommand::ZSET: { if(req.size() != 2){ break; } std::string name, key; if(decode_zset_key(log.key(), &name, &key) == -1){ break; } log_trace("zset %s %s", hexmem(name.data(), name.size()).c_str(), hexmem(key.data(), key.size()).c_str()); if(ssdb->zset(name, key, req[1], log_type) == -1){ return -1; } } break; case BinlogCommand::ZDEL: { std::string name, key; if(decode_zset_key(log.key(), &name, &key) == -1){ break; } log_trace("zdel %s %s", hexmem(name.data(), name.size()).c_str(), hexmem(key.data(), key.size()).c_str()); if(ssdb->zdel(name, key, log_type) == -1){ return -1; } } break; case BinlogCommand::QSET: case BinlogCommand::QPUSH_BACK: case BinlogCommand::QPUSH_FRONT: { if(req.size() != 2){ break; } std::string name; uint64_t seq; if(decode_qitem_key(log.key(), &name, &seq) == -1){ break; } if(seq < QITEM_MIN_SEQ || seq > QITEM_MAX_SEQ){ break; } int ret; if(log.cmd() == BinlogCommand::QSET){ log_trace("qset %s %" PRIu64 "", hexmem(name.data(), name.size()).c_str(), seq); ret = ssdb->qset_by_seq(name, seq, req[1], log_type); }else if(log.cmd() == BinlogCommand::QPUSH_BACK){ log_trace("qpush_back %s", hexmem(name.data(), name.size()).c_str()); ret = ssdb->qpush_back(name, req[1], log_type); }else{ log_trace("qpush_front %s", hexmem(name.data(), name.size()).c_str()); ret = ssdb->qpush_front(name, req[1], log_type); } if(ret == -1){ return -1; } } break; case BinlogCommand::QPOP_BACK: case BinlogCommand::QPOP_FRONT: { int ret; const Bytes name = log.key(); std::string tmp; if(log.cmd() == BinlogCommand::QPOP_BACK){ log_trace("qpop_back %s", hexmem(name.data(), name.size()).c_str()); ret = ssdb->qpop_back(name, &tmp, log_type); }else{ log_trace("qpop_front %s", hexmem(name.data(), name.size()).c_str()); ret = ssdb->qpop_front(name, &tmp, log_type); } if(ret == -1){ return -1; } } break; default: log_error("unknown binlog, type=%d, cmd=%d", log.type(), log.cmd()); break; } this->last_seq = log.seq(); if(log.type() == BinlogType::COPY){ this->last_key = log.key().String(); } this->save_status(); return 0; }
int queue_message_fd_r(uint32_t msgid) { int fdin, fdout = -1, fd = -1; FILE *ifp = NULL; FILE *ofp = NULL; profile_enter("queue_message_fd_r"); fdin = handler_message_fd_r(msgid); profile_leave(); log_trace(TRACE_QUEUE, "queue-backend: queue_message_fd_r(%08"PRIx32") -> %d", msgid, fdin); if (fdin == -1) return (-1); #ifdef HAVE_GCM_CRYPTO if (env->sc_queue_flags & QUEUE_ENCRYPTION) { if ((fdout = mktmpfile()) == -1) goto err; if ((fd = dup(fdout)) == -1) goto err; if ((ifp = fdopen(fdin, "r")) == NULL) goto err; fdin = fd; fd = -1; if ((ofp = fdopen(fdout, "w+")) == NULL) goto err; if (! crypto_decrypt_file(ifp, ofp)) goto err; fclose(ifp); ifp = NULL; fclose(ofp); ofp = NULL; lseek(fdin, SEEK_SET, 0); } #endif if (env->sc_queue_flags & QUEUE_COMPRESSION) { if ((fdout = mktmpfile()) == -1) goto err; if ((fd = dup(fdout)) == -1) goto err; if ((ifp = fdopen(fdin, "r")) == NULL) goto err; fdin = fd; fd = -1; if ((ofp = fdopen(fdout, "w+")) == NULL) goto err; if (! uncompress_file(ifp, ofp)) goto err; fclose(ifp); ifp = NULL; fclose(ofp); ofp = NULL; lseek(fdin, SEEK_SET, 0); } return (fdin); err: if (fd != -1) close(fd); if (fdin != -1) close(fdin); if (fdout != -1) close(fdout); if (ifp) fclose(ifp); if (ofp) fclose(ofp); return -1; }
// sync seq and/or binlog int BackendSync::Client::sync(BinlogQueue *logs){ Binlog log; while(1){ int ret = 0; uint64_t expect_seq = this->last_seq + 1; if(this->status == Client::COPY && this->last_seq == 0){ ret = logs->find_last(&log); }else{ ret = logs->find_next(expect_seq, &log); } if(ret == 0){ return 0; } if(this->status == Client::COPY && log.key() > this->last_key){ log_debug("fd: %d, last_key: '%s', drop: %s", link->fd(), hexmem(this->last_key.data(), this->last_key.size()).c_str(), log.dumps().c_str()); this->last_seq = log.seq(); // WARN: When there are writes behind last_key, we MUST create // a new iterator, because iterator will not know this key. // Because iterator ONLY iterates throught keys written before // iterator is created. if(this->iter){ delete this->iter; this->iter = NULL; } continue; } if(this->last_seq != 0 && log.seq() != expect_seq){ log_warn("%s:%d fd: %d, OUT_OF_SYNC! log.seq: %" PRIu64 ", expect_seq: %" PRIu64 "", link->remote_ip, link->remote_port, link->fd(), log.seq(), expect_seq ); this->out_of_sync(); return 1; } // update last_seq this->last_seq = log.seq(); char type = log.type(); if(type == BinlogType::MIRROR && this->is_mirror){ if(this->last_seq - this->last_noop_seq >= 1000){ this->noop(); return 1; }else{ continue; } } break; } int ret = 0; std::string val; switch(log.cmd()){ case BinlogCommand::KSET: case BinlogCommand::HSET: case BinlogCommand::ZSET: case BinlogCommand::QSET: case BinlogCommand::QPUSH_BACK: case BinlogCommand::QPUSH_FRONT: ret = backend->ssdb->raw_get(log.key(), &val); if(ret == -1){ log_error("fd: %d, raw_get error!", link->fd()); }else if(ret == 0){ //log_debug("%s", hexmem(log.key().data(), log.key().size()).c_str()); log_trace("fd: %d, skip not found: %s", link->fd(), log.dumps().c_str()); }else{ log_trace("fd: %d, %s", link->fd(), log.dumps().c_str()); link->send(log.repr(), val); } break; case BinlogCommand::KDEL: case BinlogCommand::HDEL: case BinlogCommand::ZDEL: case BinlogCommand::QPOP_BACK: case BinlogCommand::QPOP_FRONT: log_trace("fd: %d, %s", link->fd(), log.dumps().c_str()); link->send(log.repr()); break; } return 1; }
void *realloc(void *ptr, size_t size) { struct log_malloc_s *mem; sig_atomic_t memuse = 0; sig_atomic_t memruse = 0; sig_atomic_t memchange = 0; #ifdef HAVE_MALLOC_USABLE_SIZE size_t rsize = 0; sig_atomic_t memrchange = 0; #endif if(!DL_RESOLVE_CHECK(realloc)) return NULL; mem = (ptr != NULL) ? MEM_HEAD(ptr) : NULL; //FIXME: not handling foreign memory here (seems not needed) if(mem && (mem->size != ~mem->cb)) { assert(mem->size != ~mem->cb); return NULL; } if((mem = real_realloc(mem, size + MEM_OFF)) != NULL) { memchange = (ptr) ? size - mem->size : size; memuse = __sync_add_and_fetch(&g_ctx.mem_used, memchange); #ifdef HAVE_MALLOC_USABLE_SIZE rsize = malloc_usable_size(mem); memrchange = (ptr) ? rsize - mem->rsize : rsize; memruse = __sync_add_and_fetch(&g_ctx.mem_rused, memrchange); #endif } #ifndef DISABLE_CALL_COUNTS (void)__sync_fetch_and_add(&g_ctx.stat.realloc, 1); g_ctx.stat.unrel_sum++; #endif if(!g_ctx.memlog_disabled) { int s; char buf[LOG_BUFSIZE]; s = snprintf(buf, sizeof(buf), "+ realloc %d %p %p (%zu %zu) [%u:%u]\n", memchange, ptr, MEM_PTR(mem), (mem ? mem->size : 0), size, memuse, memruse); log_trace(buf, s, sizeof(buf), 1); } /* now we can update */ if(mem != NULL) { mem->size = size; mem->cb = ~mem->size; #ifdef HAVE_MALLOC_USABLE_SIZE mem->rsize = rsize; #endif } return MEM_PTR(mem); }