/* * This function tests that resize routine works properly. * NOTE: I NEED TO PASS THE SAME LIMITS TO ALL REALLOCATION CALLS TO DOUBLE AND VECTOR ARRAYS BECAUSE OF * I USE ONE COMMON LOOP TO CHECK THE RESULT. OTHERWISE I BREAK BOUNDARY OF ARRAY. * */ void mesh_testResize(void) { int imin, jmin, kmin, imax, jmax, kmax; int i, j, k, di, dj, dk; // Arrays to save data in control points to compare. int I[5], J[5], K[5]; vec3D_t saveVec[5][5][5]; double saveDouble[5][5][5]; // Sets initial size. imin = mesh_randomInt(5, 10) * mc_have_x; jmin = mesh_randomInt(5, 10) * mc_have_y; kmin = mesh_randomInt(5, 10) * mc_have_z; imax = (imin + mesh_randomInt(5, 10)) * mc_have_x; jmax = (jmin + mesh_randomInt(5, 10)) * mc_have_y; kmax = (kmin + mesh_randomInt(5, 10)) * mc_have_z; // Allocates meshes. mesh_allocate(&test1, imin, jmin, kmin, imax, jmax, kmax, "test_Double", mc_double); mesh_allocate(&test2, imin, jmin, kmin, imax, jmax, kmax, "test_Vec", mc_vec3D_t); if(mf_mesh_cmpSize(testDouble, testVec)) error("mesh_testResize: bad initialization"); // Initializes by random value. for(i = testVec->imin; i <= testVec->imax; i++) for(j = testVec->jmin; j <= testVec->jmax; j++) for(k = testVec->kmin; k <= testVec->kmax; k++) { mv_f(testDouble, i, j, k) = mesh_randomDouble(); mv_fx(testVec, i, j, k) = mesh_randomDouble(); mv_fy(testVec, i, j, k) = mesh_randomDouble(); mv_fz(testVec, i, j, k) = mesh_randomDouble(); } // Picks the control point. for(i = 0; i < 5; i++) { I[i] = mesh_randomInt(testVec->imin, testVec->imax); J[i] = mesh_randomInt(testVec->jmin, testVec->jmax); K[i] = mesh_randomInt(testVec->kmin, testVec->kmax); } msg_send ("mesh_testResize: grid is\n {%d, %d, %d, %d, %d}\n {%d, %d, %d, %d, %d}\n {%d, %d, %d, %d, %d}.", I[0], I[1], I[2], I[3], I[4], J[0], J[1], J[2], J[3], J[4], K[0], K[1], K[2], K[3], K[4]); // Saves the values. for(i = 0; i < 5; i++) for(j = 0; j < 5; j++) for(k = 0; k < 5; k++) { saveDouble[i][j][k] = mv_f(testDouble, I[i], J[j], K[k]); saveVec[i][j][k] = mv_v(testVec, I[i], J[j], K[k]); } // Expands the meshes. di = mesh_randomInt(0, 4) * mc_have_x; dj = mesh_randomInt(0, 4) * mc_have_y; dk = mesh_randomInt(0, 4) * mc_have_z; // Expands the array. mesh_reallocate(&test1, imin - di, jmin - dj, kmin - dk, imax + di * 2, jmax + dj / 2, kmax + dk); mesh_reallocate(&test2, imin - di, jmin - dj, kmin - dk, imax + di * 2, jmax + dj / 2, kmax + dk); // Verifies the values. for(i = 0; i < 5; i++) for(j = 0; j < 5; j++) for(k = 0; k < 5; k++) { if(saveDouble[i][j][k] != mv_f(testDouble, I[i], J[j], K[k])) error("mesh_testResize: bad mv_f."); if(saveVec[i][j][k].x != mv_fx(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fx."); if(saveVec[i][j][k].y != mv_fy(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fy."); if(saveVec[i][j][k].z != mv_fz(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fz."); } msg_send("mesh_testResize: expand test is passed."); // Initializes by random value new array. for(i = testVec->imin; i <= testVec->imax; i++) for(j = testVec->jmin; j <= testVec->jmax; j++) for(k = testVec->kmin; k <= testVec->kmax; k++) { mv_f(testDouble, i, j, k) = mesh_randomDouble(); mv_fx(testVec, i, j, k) = mesh_randomDouble(); mv_fy(testVec, i, j, k) = mesh_randomDouble(); mv_fz(testVec, i, j, k) = mesh_randomDouble(); } // Saves the values. for(i = 0; i < 5; i++) for(j = 0; j < 5; j++) for(k = 0; k < 5; k++) { saveDouble[i][j][k] = mv_f(testDouble, I[i], J[j], K[k]); saveVec[i][j][k] = mv_v(testVec, I[i], J[j], K[k]); } // Shrinks the meshes back. mesh_reallocate(&test1, imin, jmin, kmin, imax, jmax, kmax); mesh_reallocate(&test2, imin, jmin, kmin, imax, jmax, kmax); // Verifies the values. for(i = 0; i < 5; i++) for(j = 0; j < 5; j++) for(k = 0; k < 5; k++) { if(saveDouble[i][j][k] != mv_f(testDouble, I[i], J[j], K[k])) error("mesh_testResize: bad mv_f."); if(saveVec[i][j][k].x != mv_fx(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fx."); if(saveVec[i][j][k].y != mv_fy(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fy."); if(saveVec[i][j][k].z != mv_fz(testVec, I[i], J[j], K[k])) error("mesh_testResize: bad mv_fz."); } msg_send("mesh_testResize: shrink test is passed."); mesh_free(&test1); mesh_free(&test2); }
/* * Note: * * The state after exec() are as follows: * - Opened file descriptors remain open except FD_CLOEXEC flag is set. * - Opened directory streams are closed * - Signals set to the default action. * - Any asynchronous I/O operations are cancelled. */ int execve(char *path, char *argv[], char *envp[]) { object_t exec_obj; struct exec_msg msg; int err, i, argc, envc; size_t bufsz; char *dest, *src; if ((err = object_lookup(OBJNAME_EXEC, &exec_obj)) != 0) { errno = ENOSYS; return -1; } if (path == NULL) { errno = EFAULT; return -1; } /* if (strlen(path) >= PATH_MAX) return ENAMETOOLONG; */ /* Get arg/env buffer size */ bufsz = 0; argc = 0; if (argv) { while (argv[argc]) { bufsz += (strlen(argv[argc]) + 1); argc++; } } envc = 0; if (envp) { while (envp[envc]) { bufsz += (strlen(envp[envc]) + 1); envc++; } } if (bufsz >= ARG_MAX) { errno = E2BIG; return -1; } dest = msg.buf; for (i = 0; i < argc; i++) { src = argv[i]; while ((*dest++ = *src++) != 0); } for (i = 0; i < envc; i++) { src = envp[i]; while ((*dest++ = *src++) != 0); } /* Request to exec server */ msg.hdr.code = EX_EXEC; msg.argc = argc; msg.envc = envc; msg.bufsz = bufsz; strlcpy(msg.path, path, PATH_MAX); do { err = msg_send(exec_obj, &msg, sizeof(msg), 0); } while (err == EINTR); /* * If exec() request is done successfully, control never comes here. */ errno = 0; if (err) errno = EIO; else if (msg.hdr.status) errno = msg.hdr.status; return -1; }
/** * @return: * 0: success * -1: internal error * -2: insane call :) */ int ack_local_uac(struct cell *trans, str *hdrs, str *body) { struct retr_buf *local_ack, *old_lack; int ret; struct tmcb_params onsend_params; /* sanity checks */ #ifdef EXTRA_DEBUG if (! trans) { BUG("no transaction to ACK.\n"); abort(); } #endif #define RET_INVALID \ ret = -2; \ goto fin if (! is_local(trans)) { ERR("trying to ACK non local transaction (T@%p).\n", trans); RET_INVALID; } if (! is_invite(trans)) { ERR("trying to ACK non INVITE local transaction (T@%p).\n", trans); RET_INVALID; } if (! trans->uac[0].reply) { ERR("trying to ACK un-completed INVITE transaction (T@%p).\n", trans); RET_INVALID; } if (! (trans->flags & T_NO_AUTO_ACK)) { ERR("trying to ACK an auto-ACK transaction (T@%p).\n", trans); RET_INVALID; } if (trans->uac[0].local_ack) { ERR("trying to rebuild ACK retransmission buffer (T@%p).\n", trans); RET_INVALID; } /* looks sane: build the retransmission buffer */ if (! (local_ack = local_ack_rb(trans->uac[0].reply, trans, /*branch*/0, hdrs, body))) { ERR("failed to build ACK retransmission buffer"); RET_INVALID; } else { /* set the new buffer, but only if not already set (conc. invok.) */ if ((old_lack = (struct retr_buf *)atomic_cmpxchg_long( (void *)&trans->uac[0].local_ack, 0, (long)local_ack))) { /* buffer already set: deny current attempt */ ERR("concurrent ACKing for local INVITE detected (T@%p).\n",trans); free_local_ack(local_ack); RET_INVALID; } } if (msg_send(&local_ack->dst, local_ack->buffer, local_ack->buffer_len)<0){ /* hopefully will succeed on next 2xx retransmission */ ERR("failed to send local ACK (T@%p).\n", trans); ret = -1; goto fin; } else { INIT_TMCB_ONSEND_PARAMS(onsend_params, 0, 0, &trans->uac[0].request, &local_ack->dst, local_ack->buffer, local_ack->buffer_len, TMCB_LOCAL_F, 0 /* branch */, TYPE_LOCAL_ACK); run_trans_callbacks_off_params(TMCB_REQUEST_SENT, trans, &onsend_params); } ret = 0; fin: /* TODO: ugly! */ /* FIXME: the T had been obtain by t_lookup_ident()'ing for it, so, it is * ref-counted. The t_unref() can not be used, as it requests a valid SIP * message (all available might be the reply, but if AS goes wrong and * tries to ACK before the final reply is received, we still have to * lookup the T to find this out). */ UNREF( trans ); return ret; #undef RET_INVALID }
/* removes first via & sends msg to the second * - mode param controls if modules sip response callbacks are executed */ static int do_forward_reply(struct sip_msg* msg, int mode) { char* new_buf; struct dest_info dst; unsigned int new_len; int r; #ifdef USE_TCP char* s; int len; #endif init_dest_info(&dst); new_buf=0; /*check if first via host = us */ if (check_via){ if (check_self(&msg->via1->host, msg->via1->port?msg->via1->port:SIP_PORT, msg->via1->proto)!=1){ LOG(L_NOTICE, "ERROR: forward_reply: host in first via!=me :" " %.*s:%d\n", msg->via1->host.len, msg->via1->host.s, msg->via1->port); /* send error msg back? */ goto error; } } /* check modules response_f functions */ if(likely(mode==0)) { for (r=0; r<mod_response_cbk_no; r++) if (mod_response_cbks[r](msg)==0) goto skip; } /* we have to forward the reply stateless, so we need second via -bogdan*/ if (parse_headers( msg, HDR_VIA2_F, 0 )==-1 || (msg->via2==0) || (msg->via2->error!=PARSE_OK)) { /* no second via => error */ LOG(L_DBG, "reply cannot be forwarded - no 2nd via\n"); goto error; } new_buf = build_res_buf_from_sip_res( msg, &new_len); if (!new_buf){ LOG(L_ERR, "ERROR: forward_reply: building failed\n"); goto error; } dst.proto=msg->via2->proto; SND_FLAGS_OR(&dst.send_flags, &msg->fwd_send_flags, &msg->rpl_send_flags); if (update_sock_struct_from_via( &dst.to, msg, msg->via2 )==-1) goto error; #ifdef USE_COMP dst.comp=msg->via2->comp_no; #endif #if defined USE_TCP || defined USE_SCTP if ( #ifdef USE_TCP dst.proto==PROTO_TCP || dst.proto==PROTO_WS #ifdef USE_TLS || dst.proto==PROTO_TLS || dst.proto==PROTO_WSS #endif #ifdef USE_SCTP || #endif /* USE_SCTP */ #endif /* USE_TCP */ #ifdef USE_SCTP dst.proto==PROTO_SCTP #endif /* USE_SCTP */ ){ /* find id in i param if it exists */ if (msg->via1->i && msg->via1->i->value.s){ s=msg->via1->i->value.s; len=msg->via1->i->value.len; DBG("forward_reply: i=%.*s\n",len, ZSW(s)); if (reverse_hex2int(s, len, (unsigned int*)&dst.id)<0){ LOG(L_ERR, "ERROR: forward_reply: bad via i param \"%.*s\"\n", len, ZSW(s)); dst.id=0; } } } #endif apply_force_send_socket(&dst, msg); if (msg_send(&dst, new_buf, new_len)<0) { STATS_RPL_FWD_DROP(); goto error; } /* call onsend_route */ if(dst.send_sock == NULL) { dst.send_sock=get_send_socket(msg, &dst.to, dst.proto); if (dst.send_sock==0){ LOG(L_ERR, "forward_reply: ERROR: cannot forward reply\n"); goto done; } } run_onsend(msg, &dst, new_buf, new_len); done: #ifdef STATS STATS_TX_RESPONSE( (msg->first_line.u.reply.statuscode/100) ); #endif DBG(" reply forwarded to %.*s:%d\n", msg->via2->host.len, msg->via2->host.s, (unsigned short) msg->via2->port); STATS_RPL_FWD_OK(); pkg_free(new_buf); skip: return 0; error: if (new_buf) pkg_free(new_buf); return -1; }
int forward_request( struct sip_msg* msg, struct proxy_l * p) { union sockaddr_union to; unsigned int len; char* buf; struct socket_info* send_sock; struct socket_info* last_sock; str *branch; buf=0; /* calculate branch for outbound request - if the branch buffer is already * set (maybe by an upper level as TM), used it; otherwise computes * the branch for stateless fwd. . According to the latest discussions * on the topic, you should reuse the latest statefull branch * --bogdan */ if ( msg->add_to_branch_len==0 ) { branch = get_sl_branch(msg); if (branch==0) { LM_ERR("unable to compute branch\n"); goto error; } msg->add_to_branch_len = branch->len; memcpy( msg->add_to_branch_s, branch->s, branch->len); } msg_callback_process(msg, REQ_PRE_FORWARD, (void *)p); hostent2su( &to, &p->host, p->addr_idx, (p->port)?p->port:SIP_PORT); last_sock = 0; #ifdef USE_TCP if (getb0flags() & tcp_no_new_conn_bflag) tcp_no_new_conn = 1; #endif do { send_sock=get_send_socket( msg, &to, p->proto); if (send_sock==0){ LM_ERR("cannot forward to af %d, proto %d no corresponding" "listening socket\n", to.s.sa_family, p->proto); ser_error=E_NO_SOCKET; continue; } if ( last_sock!=send_sock ) { if (buf) pkg_free(buf); buf = build_req_buf_from_sip_req(msg, &len, send_sock, p->proto, 0); if (!buf){ LM_ERR("building req buf failed\n"); #ifdef USE_TCP tcp_no_new_conn = 0; #endif goto error; } last_sock = send_sock; } if (check_blacklists( p->proto, &to, buf, len)) { LM_DBG("blocked by blacklists\n"); ser_error=E_IP_BLOCKED; continue; } /* send it! */ LM_DBG("sending:\n%.*s.\n", (int)len, buf); LM_DBG("orig. len=%d, new_len=%d, proto=%d\n", msg->len, len, p->proto ); if (msg_send(send_sock, p->proto, &to, 0, buf, len)<0){ ser_error=E_SEND; continue; } run_fwd_callbacks( msg, buf, len, send_sock, p->proto, &to); ser_error = 0; break; }while( get_next_su( p, &to, (ser_error==E_IP_BLOCKED)?0:1)==0 ); #ifdef USE_TCP tcp_no_new_conn = 0; #endif if (ser_error) { update_stat( drp_reqs, 1); goto error; } /* sent requests stats */ update_stat( fwd_reqs, 1); pkg_free(buf); /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/ return 0; error: if (buf) pkg_free(buf); return -1; }
//static void param_kernel(void) { /* we send the params to hfkernel */ struct hfapp_msg msg; /* general parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_GENERALPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.generalpar)); msg.data.generalpar.beaconpause = htons(params.general.beaconpause); msg_send(&msg); /* FSK parameters */ set_fsk_freq(params.fsk.freq[1], params.fsk.freq[0]); /* CW parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_CWPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.cwpar)); msg.data.cwpar.wpm = htons(params.cw.wpm); msg.data.cwpar.tone = htons(params.cw.tone); msg.data.cwpar.farnsworth = params.cw.farnsworth; msg.data.cwpar.dtr = params.cw.dtr; msg_send(&msg); /* RTTY parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_RTTYPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.rpar)); //msg.data.rpar.baud = htons(params.rtty.baud); msg.data.rpar.baud = (params.rtty.baud); msg.data.rpar.rxinvert = params.rtty.rxinvert; msg.data.rpar.txinvert = params.rtty.txinvert; msg_send(&msg); /* Amtor parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_AMTORPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.apar)); strncpy(msg.data.apar.destcall, params.amtor.destcall, sizeof(msg.data.apar.destcall)); strncpy(msg.data.apar.selfeccall, params.amtor.selfeccall, sizeof(msg.data.apar.selfeccall)); strncpy(msg.data.apar.mycall, params.amtor.mycall, sizeof(msg.data.apar.mycall)); msg.data.apar.txdelay = htons(params.amtor.txdelay); msg.data.apar.retry = htons(params.amtor.retry); msg.data.apar.rxinvert = params.amtor.rxinvert ; msg.data.apar.txinvert = params.amtor.txinvert; msg_send(&msg); /* GTOR parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_GTORPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.gpar)); strncpy(msg.data.gpar.destcall, params.gtor.destcall, sizeof(msg.data.gpar.destcall)); strncpy(msg.data.gpar.mycall, params.gtor.mycall, sizeof(msg.data.gpar.mycall)); msg.data.gpar.txdelay = htons(params.gtor.txdelay); msg.data.gpar.retry = htons(params.gtor.retry); msg_send(&msg); /* Pactor parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_PACTORPAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.ppar)); strncpy(msg.data.ppar.destcall, params.pactor.destcall, sizeof(msg.data.ppar.destcall)); strncpy(msg.data.ppar.mycall, params.pactor.mycall, sizeof(msg.data.ppar.mycall)); msg.data.ppar.txdelay = htons(params.pactor.txdelay); msg.data.ppar.retry = htons(params.pactor.retry); msg.data.ppar.longpath = params.pactor.longpath; msg.data.ppar.crcpreset[0] = htons(params.pactor.crcpreset[0]); msg.data.ppar.crcpreset[1] = htons(params.pactor.crcpreset[1]); msg.data.ppar.crcpreset[2] = htons(params.pactor.crcpreset[2]); msg.data.ppar.crcpreset[3] = htons(params.pactor.crcpreset[3]); msg_send(&msg); /* MT63 parameters */ msg.hdr.type = htonl(HFAPP_MSG_SET_MT63PAR); msg.hdr.err = htonl(ERR_NOERR); msg.hdr.len = htonl(sizeof(msg.data.mt63par)); msg.data.mt63par.bandwidth = htons(params.mt63.bandwidth); msg.data.mt63par.integration = htons(params.mt63.integration); strncpy(msg.data.mt63par.cwcall, params.mt63.cwcall, sizeof(msg.data.mt63par.cwcall)); msg.data.mt63par.doubleinterleave = params.mt63.doubleinterleave; msg_send(&msg); }
static int enable(struct cmd_struct *cmd, struct arg_struct *arg) { int cnt; int err; char *bearer; struct tipc_nl_msg msg; struct cmd_option *opt; struct nlattr *attrs; __u32 domain = 0; __u32 priority = 0; /* One mandatory argument (bearer) */ if (arg->argc < arg->loc + 1) return -EINVAL; bearer = arg->argv[arg->loc]; (arg->loc)++; cnt = opt_parse(cmd, arg); if (cnt < 0) return -EINVAL; msg.nl_flags = NLM_F_REQUEST; msg.nl_cmd = TIPC_NL_BEARER_ENABLE; err = msg_init(&msg); if (err) return err; attrs = nla_nest_start(msg.nl_msg, TIPC_NLA_BEARER); NLA_PUT_STRING(msg.nl_msg, TIPC_NLA_BEARER_NAME, bearer); opt = get_opt(cmd, "priority"); if (opt) { struct nlattr *prop; priority = atoi(opt->val); prop = nla_nest_start(msg.nl_msg, TIPC_NLA_BEARER_PROP); NLA_PUT_U32(msg.nl_msg, TIPC_NLA_PROP_PRIO, priority); nla_nest_end(msg.nl_msg, prop); } opt = get_opt(cmd, "domain"); if (opt) { domain = str2addr(opt->val); if (!domain) { msg_abort(&msg); return -1; } NLA_PUT_U32(msg.nl_msg, TIPC_NLA_BEARER_DOMAIN, domain); } nla_nest_end(msg.nl_msg, attrs); err = msg_send(&msg); if (err) return err; err = msg_recv(&msg, NULL); if (err) return err; log_info("Bearer %s enabled\n", bearer); return 0; nla_put_failure: msg_abort(&msg); return -ENOBUFS; }
int sl_send_reply(struct sip_msg *msg , int code, char* reason) { char *buf, *dset; unsigned int len; struct dest_info dst; struct bookmark dummy_bm; int backup_mhomed, ret, dset_len; if ( msg->first_line.u.request.method_value==METHOD_ACK) { LOG(L_WARN, "Warning: sl_send_reply: I won't send a reply for ACK!!\n"); goto error; } init_dest_info(&dst); if (reply_to_via) { if (update_sock_struct_from_via( &dst.to, msg, msg->via1 )==-1) { LOG(L_ERR, "ERROR: sl_send_reply: " "cannot lookup reply dst: %s\n", msg->via1->host.s ); goto error; } } else update_sock_struct_from_ip( &dst.to, msg ); /* if that is a redirection message, dump current message set to it */ if (code>=300 && code<400) { dset=print_dset(msg, &dset_len); if (dset) { add_lump_rpl(msg, dset, dset_len, LUMP_RPL_HDR); } } /* add a to-tag if there is a To header field without it */ if ( /* since RFC3261, we append to-tags anywhere we can, except * 100 replies */ /* msg->first_line.u.request.method_value==METHOD_INVITE && */ code>=180 && (msg->to || (parse_headers(msg,HDR_TO_F, 0)!=-1 && msg->to)) && (get_to(msg)->tag_value.s==0 || get_to(msg)->tag_value.len==0) ) { calc_crc_suffix( msg, tag_suffix ); buf = build_res_buf_from_sip_req(code,reason,&sl_tag,msg,&len,&dummy_bm); } else { buf = build_res_buf_from_sip_req(code,reason,0,msg,&len,&dummy_bm); } if (!buf) { DBG("DEBUG: sl_send_reply: response building failed\n"); goto error; } /* supress multhoming support when sending a reply back -- that makes sure that replies will come from where requests came in; good for NATs (there is no known use for mhomed for locally generated replies; note: forwarded cross-interface replies do benefit of mhomed! */ backup_mhomed=mhomed; mhomed=0; /* use for sending the received interface -bogdan*/ dst.proto=msg->rcv.proto; dst.send_sock=msg->rcv.bind_address; dst.id=msg->rcv.proto_reserved1; #ifdef USE_COMP dst.comp=msg->via1->comp_no; #endif ret = msg_send(&dst, buf, len); mhomed=backup_mhomed; pkg_free(buf); if (ret<0) { goto error; } *(sl_timeout) = get_ticks() + SL_RPL_WAIT_TIME; update_sl_stats(code); return 1; error: update_sl_failures(); return -1; }
/** * Creates quiet start photo-ionization produced plasma DF (for paper with Valery). */ double tag_photoelectrons(FILE * fp) { int uniformWeight; // Flag to choose sampling of the DF. double qDivM, chargeDensity, eta; nx = cfg_readInt(fp); // Reads parameters. ny = cfg_readInt(fp); nz = cfg_readInt(fp); N = cfg_readInt(fp); mirror = cfg_readInt(fp); nRotations = cfg_readInt(fp); eta = cfg_readDouble(fp); qDivM = cfg_readDouble(fp); V0 = cfg_readDouble(fp); Nx = cfg_readInt(fp); // Reads staggered mesh steps. Ny = cfg_readInt(fp); Nz = cfg_readInt(fp); uniformWeight = cfg_readInt(fp) == 1; V0 = (V0 >= 0) ? V0 : sqrt(-2.0 * V0 * mc_CGS_eV / mc_CGS_m) / units(mc_v0); // Converts velocity to our units. chargeDensity = (eta > 0) ? eta * units(mc_ne_critical) / qDivM : -eta; // Evaluates n_\alpha[cm^-3]. chargeDensity *= mc_CGS_e / units(mc_rho0); // Evaluates rho in dimensionless units. if(qDivM * chargeDensity <= 0) chargeDensity *= -1; // Updates omega_pe after updating rho. omega2_pe = 4 * mc_pi * chargeDensity * units(mc_rho0) * qDivM * mc_CGS_e / mc_CGS_m * units(mc_t0) * units(mc_t0); if(nx <= 0 || ny <= 0 || nz <= 0 || Nx <= 0 || Ny <= 0 || Nz <= 0) error("tag_photoDF: nx, ny, nz, Nx, Ny, Nz must be positive (>0)."); if(dmn_mesh_max[0] % Nx || dmn_mesh_max[1] % Ny || dmn_mesh_max[2] % Nz) error("tag_photoDF: staggered steps size doesn't fit domain size."); if(nRotations < 0) error("tag_photoDF: nRotations (= %d) must be >= 0.", nRotations); mirror = (mirror != 0); // Clamps mirror flag to \in {0, 1}. double rDebay = sqrt(V0 * V0 / (5.0 * omega2_pe)); // Estimates debay scale from disp. eq.. msg_send("tag_photoDF:"); msg_send(" - photo-DF plasma component is added,"); msg_send(" - V0 = %.3e (energy = %.3e eV),", V0, mc_CGS_m * pow(V0 * units(mc_v0), 2) / 2 / mc_CGS_eV); msg_send(" - (omega_pe/omega_0)^2 = %.3e, q/M = %.3e, n_0 = %.3e [cm^-3],", omega2_pe / (4 * mc_pi * mc_pi), qDivM, chargeDensity * units(mc_rho0) / mc_CGS_e); msg_send(" - resolution of debay scale (nodes on rD) is"); msg_send(" %e (x), %e (y), %e (z),", rDebay / h1, rDebay / h2, rDebay / h3); msg_send(" - particles placement:"); msg_send(" o uniform %s of markers,", (uniformWeight) ? "weight" : "spacing"); msg_send(" o mirror: %d, rotations: %d,", mirror, nRotations); msg_send(" o %d x %d x %d sub-cell mesh,", nx, ny, nz); msg_send(" o %d x %d x %d staggered mesh steps,", Nx, Ny, Nz); msg_send(" o %d particles per cell,", nx * ny * nz * N * (1 + mirror) * (1 + nRotations)); msg_send(" o %d particles per pattern,", nx * ny * nz * Nx * Ny * Nz * N * (1 + mirror) * (1 + nRotations)); double N_part = nx * ny * nz * N * (dmn_mesh_max[0] - dmn_mesh_min[0] + 1 - mc_have_x) * (dmn_mesh_max[1] - dmn_mesh_min[1] + 1 - mc_have_y) * (dmn_mesh_max[2] - dmn_mesh_min[2] + 1 - mc_have_z) * (1.0 + mirror) * (1.0 + nRotations); msg_send(" o %.3e particles total,", N_part); if(memEstimateOnly) { set = 1; // To permit seed parameters checks. return (N_part + nx * ny * nz * Nx * Ny * Nz * N * (1.0 + mirror) * (1.0 + nRotations)) * sizeof(marker_t); } plasma_newObject(); // Starts new chapter. double Ntotal = 0, Nlocal; // Allocates particles and gets number. Nlocal = tag_photoInit(chargeDensity / (nx * ny * nz * N * (1.0 + mirror) * (1.0 + nRotations)), uniformWeight, qDivM); msg_send(" o %.3e particles added / cpu %d.", Nlocal, cpu_here); MPI_Allreduce(&Nlocal, &Ntotal, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); // Checks total number of particles created. if(Ntotal != N_part) error("tag_photoDF: lost %.1f particles.", N_part - Ntotal); set = 1; // Size (pattern size included as storage). return (Nlocal + nx * ny * nz * Nx * Ny * Nz * N * (1.0 + mirror) * (1.0 + nRotations)) * sizeof(marker_t); }
int do_repeated_task(int sockfd) { int vm = -1; int vmno = -1; int reroute = 0; int resendcnt = 0; int src_port; char ch = '\0'; char in[MAXLINE +1] = {0,}; char inmsg[PAYLOAD_SIZE] = {0,}; peerinfo_t *pinfo = NULL; char payload[PAYLOAD_SIZE] = {0,}; char vm_ip[MAX_IP_LEN]; char my_hostname[MAXLINE]; char buffer[200]; char src_ip[MAX_IP_LEN]; struct sigaction sa; /* Install timer_handler as the signal handler for SIGVTALRM. */ memset (&sa, 0, sizeof (sa)); sa.sa_handler = &sig_alrm; sigaction (SIGALRM, &sa, NULL); while (42) { reroute = 0; resendcnt = 0; //fflush(stdin); why? fprintf (stdout, "Choose the server from vm1..vm10 (1-10 or e to exit): "); if (fgets(in, MAXLINE, stdin) != NULL){ printf("You entered %s\n", in); } else { printf("fgets error\n"); continue; } if (strncmp (in, "e", 1) == 0) { fprintf (stdout, "\nExiting... Bye.\n"); return 0; } vmno = atoi(in); resend: get_ip_of_vm(vmno, vm_ip, sizeof(vm_ip)); gethostname(my_hostname, sizeof(my_hostname)); fprintf (stdout, "TRACE: client at node %s sending request to server " "at vm%d(%s)\n", my_hostname, vmno, vm_ip); if (msg_send(sockfd, vm_ip, SERVER_PORT, "AB", reroute) < 0) { fprintf (stderr, "Failed to send message: %s\n", strerror(errno)); return -1; } mysetitimer(CLIENT_TIMEOUT); if (sigsetjmp(waitbuf, 1) != 0) { if (resendcnt >= MAX_RESEND) { fprintf (stderr, "Max resend count reached, %d times. No more " "trying.\n", resendcnt); mysetitimer(0); continue; } resendcnt ++; fprintf (stdout, "TRACE: client at node vm %d timeout on response from " "server at vm %d\n", MYID, vmno); reroute = 1; goto resend; } if (msg_recv(sockfd, buffer, src_ip, &src_port) < 0) { fprintf (stderr, "Failed to receive message: %s\n", strerror(errno)); return -1; } printf("TRACE: I recvd %s\n", buffer); mysetitimer(0); } }
int main(int argc, char *argv[]) { struct { struct kdbus_cmd_make head; /* bloom size item */ struct { uint64_t size; uint64_t type; struct kdbus_bloom_parameter bloom; } bs; /* name item */ uint64_t n_size; uint64_t n_type; char name[64]; } bus_make; int fdc, ret; char *bus; struct conn *activator, *conn_a; struct pollfd fds[2]; bool activator_done = false; printf("-- opening /dev/" KBUILD_MODNAME "/control\n"); fdc = open("/dev/" KBUILD_MODNAME "/control", O_RDWR|O_CLOEXEC); if (fdc < 0) { fprintf(stderr, "--- error %d (%m)\n", fdc); return EXIT_FAILURE; } memset(&bus_make, 0, sizeof(bus_make)); bus_make.bs.size = sizeof(bus_make.bs); bus_make.bs.type = KDBUS_ITEM_BLOOM_PARAMETER; bus_make.bs.bloom.size = 64; bus_make.bs.bloom.n_hash = 1; snprintf(bus_make.name, sizeof(bus_make.name), "%u-testbus", getuid()); bus_make.n_type = KDBUS_ITEM_MAKE_NAME; bus_make.n_size = KDBUS_ITEM_HEADER_SIZE + strlen(bus_make.name) + 1; bus_make.head.size = sizeof(struct kdbus_cmd_make) + sizeof(bus_make.bs) + bus_make.n_size; printf("-- creating bus '%s'\n", bus_make.name); ret = ioctl(fdc, KDBUS_CMD_BUS_MAKE, &bus_make); if (ret) { fprintf(stderr, "--- error %d (%m)\n", ret); return EXIT_FAILURE; } if (asprintf(&bus, "/dev/" KBUILD_MODNAME "/%s/bus", bus_make.name) < 0) return EXIT_FAILURE; activator = make_activator(bus, "foo.test.activator"); conn_a = connect_to_bus(bus, 0); if (!activator || !conn_a) return EXIT_FAILURE; upload_policy(conn_a->fd, "foo.test.activator"); add_match_empty(conn_a->fd); name_list(conn_a, KDBUS_NAME_LIST_NAMES | KDBUS_NAME_LIST_UNIQUE | KDBUS_NAME_LIST_ACTIVATORS | KDBUS_NAME_LIST_QUEUED); msg_send(conn_a, "foo.test.activator", 0xdeafbeef, 0, 0, 0, KDBUS_DST_ID_NAME); fds[0].fd = activator->fd; fds[1].fd = conn_a->fd; printf("-- entering poll loop ...\n"); for (;;) { int i, nfds = sizeof(fds) / sizeof(fds[0]); for (i = 0; i < nfds; i++) { fds[i].events = POLLIN | POLLPRI; fds[i].revents = 0; } ret = poll(fds, nfds, 3000); if (ret <= 0) break; name_list(conn_a, KDBUS_NAME_LIST_NAMES); if ((fds[0].revents & POLLIN) && !activator_done) { printf("Starter was called back!\n"); ret = name_acquire(conn_a, "foo.test.activator", KDBUS_NAME_REPLACE_EXISTING); if (ret != 0) break; activator_done = true; } if (fds[1].revents & POLLIN) { msg_recv(conn_a); break; } } printf("-- closing bus connections\n"); close(activator->fd); close(conn_a->fd); free(activator); free(conn_a); printf("-- closing bus master\n"); close(fdc); free(bus); return EXIT_SUCCESS; }
void *ipv6_process(void *arg) { (void) arg; msg_t m_recv_lowpan, m_send_lowpan; msg_t m_recv, m_send; uint8_t i; uint16_t packet_length; msg_init_queue(ip_msg_queue, IP_PKT_RECV_BUF_SIZE); while (1) { msg_receive(&m_recv_lowpan); ipv6_buf = (ipv6_hdr_t *)m_recv_lowpan.content.ptr; /* identifiy packet */ nextheader = &ipv6_buf->nextheader; for (i = 0; i < SIXLOWIP_MAX_REGISTERED; i++) { if (sixlowip_reg[i]) { msg_t m_send; m_send.type = IPV6_PACKET_RECEIVED; m_send.content.ptr = (char *) ipv6_buf; msg_send(&m_send, sixlowip_reg[i]); } } int addr_match = is_our_address(&ipv6_buf->destaddr); /* no address configured for this node so far, exit early */ if (addr_match < 0) { msg_reply(&m_recv_lowpan, &m_send_lowpan); continue; } /* destination is our address */ else if (addr_match) { switch (*nextheader) { case (IPV6_PROTO_NUM_ICMPV6): { icmp_buf = get_icmpv6_buf(ipv6_ext_hdr_len); /* checksum test*/ if (ipv6_csum(ipv6_buf, (uint8_t *) icmp_buf, NTOHS(ipv6_buf->length), IPV6_PROTO_NUM_ICMPV6) != 0xffff) { DEBUG("ERROR: wrong checksum\n"); } icmpv6_demultiplex(icmp_buf); break; } case (IPV6_PROTO_NUM_TCP): { if (tcp_packet_handler_pid != KERNEL_PID_UNDEF) { m_send.content.ptr = (char *) ipv6_buf; msg_send_receive(&m_send, &m_recv, tcp_packet_handler_pid); } else { DEBUG("INFO: No TCP handler registered.\n"); } break; } case (IPV6_PROTO_NUM_UDP): { if (udp_packet_handler_pid != KERNEL_PID_UNDEF) { m_send.content.ptr = (char *) ipv6_buf; msg_send_receive(&m_send, &m_recv, udp_packet_handler_pid); } else { DEBUG("INFO: No UDP handler registered.\n"); } break; } case (IPV6_PROTO_NUM_NONE): { DEBUG("INFO: Packet with no Header following the IPv6 Header received.\n"); break; } default: DEBUG("INFO: Unknown next header\n"); break; } } /* destination is foreign address */ else { DEBUG("That's not for me, destination is %s\n", ipv6_addr_to_str(addr_str, IPV6_MAX_ADDR_STR_LEN, &ipv6_buf->destaddr)); packet_length = IPV6_HDR_LEN + NTOHS(ipv6_buf->length); ndp_neighbor_cache_t *nce; ipv6_addr_t *dest; if (ip_get_next_hop == NULL) { dest = &ipv6_buf->destaddr; } else { dest = ip_get_next_hop(&ipv6_buf->destaddr); } if ((dest == NULL) || ((--ipv6_buf->hoplimit) == 0)) { DEBUG("!!! Packet not for me, routing handler is set, but I "\ " have no idea where to send or the hop limit is exceeded.\n"); msg_reply(&m_recv_lowpan, &m_send_lowpan); continue; } nce = ndp_get_ll_address(dest); /* copy received packet to send buffer */ memcpy(ipv6_get_buf_send(), ipv6_get_buf(), packet_length); /* send packet to node ID derived from dest IP */ if (nce != NULL) { sixlowpan_lowpan_sendto(nce->if_id, &nce->lladdr, nce->lladdr_len, (uint8_t *)ipv6_get_buf_send(), packet_length); } else { /* XXX: this is wrong, but until ND does work correctly, * this is the only way (aka the old way)*/ uint16_t raddr = dest->uint16[7]; sixlowpan_lowpan_sendto(0, &raddr, 2, (uint8_t *)ipv6_get_buf_send(), packet_length); } } msg_reply(&m_recv_lowpan, &m_send_lowpan); } }
int icmpv6_demultiplex(const icmpv6_hdr_t *hdr) { switch (hdr->type) { case (ICMPV6_TYPE_ECHO_REQUEST): { DEBUG("INFO: packet type: icmp echo request\n"); /* processing echo request */ recv_echo_req(); break; } case (ICMPV6_TYPE_ECHO_REPLY): { DEBUG("INFO: packet type: icmp echo reply\n"); /* processing echo reply */ recv_echo_repl(); break; } case (ICMPV6_TYPE_ROUTER_SOL): { DEBUG("INFO: packet type: icmp router solicitation\n"); /* processing router solicitation */ recv_rtr_sol(); /* init solicited router advertisment*/ break; } case (ICMPV6_TYPE_ROUTER_ADV): { DEBUG("INFO: packet type: icmp router advertisment\n"); /* processing router advertisment */ recv_rtr_adv(); /* init neighbor solicitation */ break; } case (ICMPV6_TYPE_NEIGHBOR_SOL): { DEBUG("INFO: packet type: icmp neighbor solicitation\n"); recv_nbr_sol(); break; } case (ICMPV6_TYPE_NEIGHBOR_ADV): { DEBUG("INFO: packet type: icmp neighbor advertisment\n"); recv_nbr_adv(); break; } case (ICMPV6_TYPE_RPL_CONTROL): { DEBUG("INFO: packet type: RPL message\n"); if (_rpl_process_pid != KERNEL_PID_UNDEF) { msg_t m_send; m_send.content.ptr = (char *) &hdr->code; msg_send(&m_send, _rpl_process_pid); } else { DEBUG("INFO: no RPL handler registered\n"); } break; } default: return -1; } return 0; }
void main(int argc, char **argv) { int fd, sockfd, temp, n, recv_port, forced_disc; struct timeval t; struct sockaddr_un cliaddr; char serv_node[10], cli_node[10], file_path[40], sendline[1024], recvline[1024], send_ip[20], recv_ip[20]; struct hostent *host; fd_set rset; FD_ZERO(&rset); strcpy(file_path,"/tmp/upasi_XXXXXX"); fd = mkstemp(file_path); if(fd < 0) { printf("Could not create a new file \n"); exit(-1); } sockfd = Socket(AF_LOCAL, SOCK_DGRAM, 0); unlink(file_path); bzero(&cliaddr,sizeof(cliaddr)); cliaddr.sun_family = AF_LOCAL; strcpy(cliaddr.sun_path, file_path); Bind(sockfd, (struct sockaddr *)&cliaddr, SUN_LEN(&cliaddr)); printf("Before getting the cli_node \n"); get_client_node(cli_node); printf("Client node is %s\n", cli_node); while(1) { forced_disc = 0; strcpy(serv_node,""); printf("Choose a VM from vm1 to vm10 as a server node:\n"); scanf("%s", serv_node); if(strcmp(serv_node,"exit") == 0) { break; } if((host = gethostbyname(serv_node)) == NULL) { printf("Invalid input\n"); continue; } if(strncmp(serv_node,"vm",2) != 0) { printf("Invalid input\n"); continue; } printf("The vm selected is %s\n", serv_node); strcpy(send_ip,""); Inet_ntop(AF_INET, (void*)host->h_addr, send_ip, 20); printf("IP of the selected host is %s\n", send_ip); strcpy(sendline,"time"); send_message: printf("Client at node %s sending request to server at %s\n", cli_node, serv_node); printf("Preparing to send message \n"); msg_send(sockfd, send_ip, SERV_PORT_NO, sendline, 0); FD_SET(sockfd, &rset); t.tv_sec = 8; t.tv_usec = 0; Select(sockfd+1, &rset, NULL, NULL, &t); if(FD_ISSET(sockfd, &rset)) { msg_recv(sockfd, recvline, recv_ip, &recv_port); printf("Client at node %s: received from %s %s\n", cli_node,serv_node, recvline); } else { if(forced_disc == 0) { forced_disc = 1; printf("Client at node %s: timeout on response from %s\n", cli_node, serv_node); goto send_message; } else { printf("Forced discovery unsuccessful \n"); continue; } } } unlink(cliaddr.sun_path); exit(0); }
void minipro_protect_on(minipro_handle_t *handle) { memset(msg, 0, sizeof(msg)); msg_init(msg, MP_PROTECT_ON, handle->device, handle->icsp); msg_send(handle, msg, 10); }
static void _semtech_loramac_event_cb(netdev_t *dev, netdev_event_t event) { netdev_lora_rx_info_t packet_info; msg_t msg; msg.content.ptr = dev; switch (event) { case NETDEV_EVENT_ISR: msg.type = MSG_TYPE_ISR; if (msg_send(&msg, semtech_loramac_pid) <= 0) { DEBUG("[semtech-loramac] possibly lost interrupt.\n"); } break; case NETDEV_EVENT_TX_COMPLETE: sx127x_set_sleep((sx127x_t *)dev); semtech_loramac_radio_events.TxDone(); DEBUG("[semtech-loramac] Transmission completed\n"); break; case NETDEV_EVENT_TX_TIMEOUT: msg.type = MSG_TYPE_TX_TIMEOUT; if (msg_send(&msg, semtech_loramac_pid) <= 0) { DEBUG("[semtech-loramac] TX timeout, possibly lost interrupt.\n"); } break; case NETDEV_EVENT_RX_COMPLETE: { size_t len; uint8_t radio_payload[SX127X_RX_BUFFER_SIZE]; len = dev->driver->recv(dev, NULL, 0, 0); dev->driver->recv(dev, radio_payload, len, &packet_info); semtech_loramac_radio_events.RxDone(radio_payload, len, packet_info.rssi, packet_info.snr); break; } case NETDEV_EVENT_RX_TIMEOUT: msg.type = MSG_TYPE_RX_TIMEOUT; if (msg_send(&msg, semtech_loramac_pid) <= 0) { DEBUG("[semtech-loramac] RX timeout, possibly lost interrupt.\n"); } break; case NETDEV_EVENT_CRC_ERROR: DEBUG("[semtech-loramac] RX CRC error\n"); semtech_loramac_radio_events.RxError(); break; case NETDEV_EVENT_FHSS_CHANGE_CHANNEL: DEBUG("[semtech-loramac] FHSS channel change\n"); if(semtech_loramac_radio_events.FhssChangeChannel) { semtech_loramac_radio_events.FhssChangeChannel(( (sx127x_t *)dev)->_internal.last_channel); } break; case NETDEV_EVENT_CAD_DONE: DEBUG("[semtech-loramac] test: CAD done\n"); if(semtech_loramac_radio_events.CadDone) { semtech_loramac_radio_events.CadDone(( (sx127x_t *)dev)->_internal.is_last_cad_success); } break; default: DEBUG("[semtech-loramac] unexpected netdev event received: %d\n", event); } }
int stlink2_swim_write_range(programmer_t *pgm, const stm8_device_t *device, unsigned char *buffer, unsigned int start, unsigned int length, const memtype_t memtype) { stlink2_init_session(pgm); stlink2_write_byte(pgm, 0x00, device->regs.CLK_CKDIVR); if(memtype == FLASH || memtype == EEPROM || memtype == OPT) { stlink2_write_and_read_byte(pgm, 0x00, device->regs.FLASH_IAPSR); } // Unlock MASS if(memtype == FLASH) { stlink2_write_byte(pgm, 0x56, device->regs.FLASH_PUKR); stlink2_write_byte(pgm, 0xae, device->regs.FLASH_PUKR); } if(memtype == EEPROM || memtype == OPT) { stlink2_write_byte(pgm, 0xae, device->regs.FLASH_DUKR); stlink2_write_byte(pgm, 0x56, device->regs.FLASH_DUKR); } if(memtype == FLASH || memtype == EEPROM || memtype == OPT) { stlink2_write_and_read_byte(pgm, 0x56, device->regs.FLASH_IAPSR); // mov 0x56, FLASH_IAPSR } int i; int BLOCK_SIZE = device->flash_block_size; for(i = 0; i < length; i+=BLOCK_SIZE) { if(memtype == FLASH || memtype == EEPROM) { // block programming mode stlink2_write_byte(pgm, 0x01, device->regs.FLASH_CR2); // mov 0x01fe, FLASH_CR2; 0x817e - enable write OPT bytes if(device->regs.FLASH_NCR2 != 0) { // Device have FLASH_NCR2 register stlink2_write_byte(pgm, 0xFE, device->regs.FLASH_NCR2); } } else if (memtype == OPT){ // option programming mode stlink2_write_byte(pgm, 0x80, device->regs.FLASH_CR2); if(device->regs.FLASH_NCR2 != 0) { stlink2_write_byte(pgm, 0x7F, device->regs.FLASH_NCR2); } } if(memtype == OPT){ int j; for(j = 0; j < length; j++){ stlink2_write_byte(pgm, buffer[j], start+j); TRY(8, HI(stlink2_get_status(pgm)) == 1); } } else { // page-based writing // The first 8 packet bytes are getting transmitted // with the same USB bulk transfer as the command itself msg_init(cmd_buf, 0xf40a); format_int(&(cmd_buf[2]), BLOCK_SIZE, 2, MP_BIG_ENDIAN); format_int(&(cmd_buf[6]), start + i, 2, MP_BIG_ENDIAN); memcpy(&(cmd_buf[8]), &(buffer[i]), 8); msg_send(pgm, cmd_buf, sizeof(cmd_buf)); // Transmitting the rest msg_send(pgm, &(buffer[i + 8]), BLOCK_SIZE - 8); // Waiting for the transfer to process TRY(128, HI(stlink2_get_status(pgm)) == BLOCK_SIZE); } if(memtype == FLASH || memtype == EEPROM || memtype == OPT) { stlink2_wait_until_transfer_completes(pgm, device); } } if(memtype == FLASH || memtype == EEPROM || memtype == OPT) { stlink2_write_and_read_byte(pgm, 0x56, device->regs.FLASH_IAPSR); // mov 0x56, FLASH_IAPSR } stlink2_write_byte(pgm, 0x00, 0x7f80); stlink2_write_byte(pgm, 0xb6, 0x7f80); stlink2_finish_session(pgm); return(length); }
void *_semtech_loramac_event_loop(void *arg) { msg_init_queue(_semtech_loramac_msg_queue, SEMTECH_LORAMAC_MSG_QUEUE); semtech_loramac_t *mac = (semtech_loramac_t *)arg; while (1) { msg_t msg; msg_receive(&msg); if (msg.type == MSG_TYPE_ISR) { netdev_t *dev = msg.content.ptr; dev->driver->isr(dev); } else { switch (msg.type) { case MSG_TYPE_RX_TIMEOUT: DEBUG("[semtech-loramac] RX timer timeout\n"); semtech_loramac_radio_events.RxTimeout(); break; case MSG_TYPE_TX_TIMEOUT: DEBUG("[semtech-loramac] TX timer timeout\n"); semtech_loramac_radio_events.TxTimeout(); break; case MSG_TYPE_MAC_TIMEOUT: { DEBUG("[semtech-loramac] MAC timer timeout\n"); void (*callback)(void) = msg.content.ptr; callback(); break; } case MSG_TYPE_LORAMAC_CMD: { msg_t msg_resp; DEBUG("[semtech-loramac] loramac cmd msg\n"); semtech_loramac_call_t *call = msg.content.ptr; call->func(mac, call->arg); msg_reply(&msg, &msg_resp); break; } case MSG_TYPE_LORAMAC_JOIN: { DEBUG("[semtech-loramac] loramac join notification msg\n"); msg_t msg_ret; msg_ret.content.value = msg.content.value; msg_send(&msg_ret, mac->caller_pid); break; } case MSG_TYPE_LORAMAC_LINK_CHECK: { MlmeConfirm_t *confirm = (MlmeConfirm_t *)msg.content.ptr; mac->link_chk.demod_margin = confirm->DemodMargin; mac->link_chk.nb_gateways = confirm->NbGateways; mac->link_chk.available = true; DEBUG("[semtech-loramac] link check info received:\n" " - Demodulation marging: %d\n" " - Number of gateways: %d\n", mac->link_chk.demod_margin, mac->link_chk.nb_gateways); break; } case MSG_TYPE_LORAMAC_TX_STATUS: { DEBUG("[semtech-loramac] received TX status\n"); if (msg.content.value == SEMTECH_LORAMAC_TX_SCHEDULE) { DEBUG("[semtech-loramac] schedule immediate TX\n"); uint8_t prev_port = mac->port; mac->port = 0; _semtech_loramac_send(mac, NULL, 0); mac->port = prev_port; } else { DEBUG("[semtech-loramac] forward TX status to caller thread\n"); msg_t msg_ret; msg_ret.type = msg.type; msg_ret.content.value = msg.content.value; msg_send(&msg_ret, mac->caller_pid); } break; } case MSG_TYPE_LORAMAC_RX: { msg_t msg_ret; msg_ret.type = MSG_TYPE_LORAMAC_RX; McpsIndication_t *indication = (McpsIndication_t *)msg.content.ptr; memcpy(mac->rx_data.payload, indication->Buffer, indication->BufferSize); mac->rx_data.payload_len = indication->BufferSize; mac->rx_data.port = indication->Port; DEBUG("[semtech-loramac] loramac RX data:\n" " - Payload: %s\n" " - Size: %d\n" " - Port: %d\n", (char *)mac->rx_data.payload, mac->rx_data.payload_len, mac->rx_data.port); msg_send(&msg_ret, mac->caller_pid); break; } default: DEBUG("[semtech-loramac] Unexpected msg type '%04x'\n", msg.type); } } } }
/** * Takes all particles and sends them to the owners. Local portal is slightly extended * to grab particles we can safely push ourself and remove boundary uncertainty. */ void placer_exchange(void) { MF_ENSURE(0, "Particles sorter is not reimplemented."); msg_send("placer_exchange: particles are forced to their domains."); }
/* test between process */ static Bool main_loop(TestParams *params) { Bool ret = FALSE; #ifndef PARENT_ONLY pid_t pid; if((pid = fork()) < 0) { ERRSTR("fork err"); goto exit; } else if(pid == 0) { /* child */ MsgHandle hMsg0 = msg_create(CHILD_MSG, PARENT_MSG, 0); if(!hMsg0) { ERR("create child msg failed"); goto exit; } sleep(1); /* we just send msg */ Int32 cnt0; MsgData msgData0; Int32 err0, dataLen0; DBG("msg test client start..."); for(cnt0 = 0; cnt0 < params->loopCnt; cnt0++) { memset(&msgData0.buf, 0, sizeof(msgData0.buf)); msgData0.header.cmd = cnt0; msgData0.header.index = cnt0; msgData0.header.type = MSG_TYPE_REQU; msgData0.header.dataLen = sprintf(msgData0.buf, "child msg [%d]", cnt0) + 1; //msgData0.header.dataLen= ROUND_UP(msgData0.header.dataLen,4); dataLen0 = msgData0.header.dataLen + sizeof(msgData0.header); err0 = msg_send(hMsg0, NULL, &msgData0.header, 0); if(err0) ERR("<%d> child send msg err", cnt0); else DBG("<%d> child send msg ok...", cnt0); err0 = msg_recv(hMsg0, &msgData0.header, sizeof(msgData0), 0); if(err0 < 0) { ERR("child wait reply err"); } else DBG("<%d> child recv reply: %s", cnt0, msgData0.buf); usleep(100000); } DBG("child exit"); } else #endif { /* parent */ MsgHandle hMsg1 = msg_create(PARENT_MSG, CHILD_MSG, 0); if(!hMsg1) { ERR("create parent msg failed"); goto exit; } sleep(1); /* we just send msg */ Int32 cnt1; MsgData msgData1; Int32 err1; DBG("msg test server start..."); for(cnt1 = 0; cnt1 < params->loopCnt; cnt1++) { memset(&msgData1.buf, 0, sizeof(msgData1.buf)); err1 = msg_recv(hMsg1, &msgData1.header, sizeof(msgData1), 0); if(err1 < 0) { ERR("<%d> parent recv msg err", cnt1); continue; } else DBG("<%d> parent recv msg: %s...", cnt1, msgData1.buf); usleep(100000); /* reply msg */ msgData1.header.type = MSG_TYPE_RESP; err1 = msg_send(hMsg1, NULL, &msgData1.header, 0); if(err1 < 0) ERR("<%d> send reply msg err", cnt1); else DBG("<%d> parent reply msg ok"); } DBG("parent exit"); } ret = TRUE; exit: return ret; }
/* forwards a request to dst * parameters: * msg - sip msg * dst - destination name, if non-null it will be resolved and * send_info updated with the ip/port. Even if dst is non * null send_info must contain the protocol and if a non * default port or non srv. lookup is desired, the port must * be !=0 * port - used only if dst!=0 (else the port in send_info->to is used) * send_info - value/result partially filled dest_info structure: * - send_info->proto and comp are used * - send_info->to will be filled (dns) * - send_info->send_flags is filled from the message * - if the send_socket member is null, a send_socket will be * chosen automatically * WARNING: don't forget to zero-fill all the unused members (a non-zero * random id along with proto==PROTO_TCP can have bad consequences, same for * a bogus send_socket value) */ int forward_request(struct sip_msg* msg, str* dst, unsigned short port, struct dest_info* send_info) { unsigned int len; char* buf; char md5[MD5_LEN]; struct socket_info* orig_send_sock; /* initial send_sock */ int ret; struct ip_addr ip; /* debugging only */ char proto; struct onsend_info onsnd_info = {0}; #ifdef USE_DNS_FAILOVER struct socket_info* prev_send_sock; int err; struct dns_srv_handle dns_srv_h; prev_send_sock=0; err=0; #endif buf=0; orig_send_sock=send_info->send_sock; proto=send_info->proto; ret=0; if(dst){ #ifdef USE_DNS_FAILOVER if (cfg_get(core, core_cfg, use_dns_failover)){ dns_srv_handle_init(&dns_srv_h); err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port, &proto, dns_flags); if (err!=0){ LOG(L_ERR, "ERROR: forward_request: resolving \"%.*s\"" " failed: %s [%d]\n", dst->len, ZSW(dst->s), dns_strerror(err), err); ret=E_BAD_ADDRESS; goto error; } }else #endif if (sip_hostport2su(&send_info->to, dst, port, &proto)<0){ LOG(L_ERR, "ERROR: forward_request: bad host name %.*s," " dropping packet\n", dst->len, ZSW(dst->s)); ret=E_BAD_ADDRESS; goto error; } }/* dst */ send_info->send_flags=msg->fwd_send_flags; /* calculate branch for outbound request; calculate is from transaction key, i.e., as an md5 of From/To/CallID/ CSeq exactly the same way as TM does; good for reboot -- than messages belonging to transaction lost due to reboot will still be forwarded with the same branch parameter and will be match-able downstream */ if (!char_msg_val( msg, md5 )) { /* parses transaction key */ LOG(L_ERR, "ERROR: forward_request: char_msg_val failed\n"); ret=E_UNSPEC; goto error; } msg->hash_index=hash( msg->callid->body, get_cseq(msg)->number); if (!branch_builder( msg->hash_index, 0, md5, 0 /* 0-th branch */, msg->add_to_branch_s, &msg->add_to_branch_len )) { LOG(L_ERR, "ERROR: forward_request: branch_builder failed\n"); ret=E_UNSPEC; goto error; } /* try to send the message until success or all the ips are exhausted * (if dns lookup is performed && the dns cache used ) */ #ifdef USE_DNS_FAILOVER do{ #endif if (orig_send_sock==0) /* no forced send_sock => find it **/ send_info->send_sock=get_send_socket(msg, &send_info->to, proto); if (send_info->send_sock==0){ LOG(L_ERR, "forward_req: ERROR: cannot forward to af %d, proto %d " "no corresponding listening socket\n", send_info->to.s.sa_family, proto); ret=ser_error=E_NO_SOCKET; #ifdef USE_DNS_FAILOVER /* continue, maybe we find a socket for some other ip */ continue; #else goto error; #endif } #ifdef USE_DNS_FAILOVER if (prev_send_sock!=send_info->send_sock){ /* rebuild the message only if the send_sock changed */ prev_send_sock=send_info->send_sock; #endif if (buf) pkg_free(buf); send_info->proto=proto; buf = build_req_buf_from_sip_req(msg, &len, send_info, 0); if (!buf){ LOG(L_ERR, "ERROR: forward_request: building failed\n"); ret=E_OUT_OF_MEM; /* most probable */ goto error; } #ifdef USE_DNS_FAILOVER } #endif /* send it! */ DBG("Sending:\n%.*s.\n", (int)len, buf); DBG("orig. len=%d, new_len=%d, proto=%d\n", msg->len, len, send_info->proto ); if (run_onsend(msg, send_info, buf, len)==0){ su2ip_addr(&ip, &send_info->to); LOG(L_INFO, "forward_request: request to %s:%d(%d) dropped" " (onsend_route)\n", ip_addr2a(&ip), su_getport(&send_info->to), send_info->proto); ser_error=E_OK; /* no error */ ret=E_ADM_PROHIBITED; #ifdef USE_DNS_FAILOVER continue; /* try another ip */ #else goto error; /* error ? */ #endif } #ifdef USE_DST_BLACKLIST if (cfg_get(core, core_cfg, use_dst_blacklist)){ if (dst_is_blacklisted(send_info, msg)){ su2ip_addr(&ip, &send_info->to); LOG(L_DBG, "DEBUG: blacklisted destination:%s:%d (%d)\n", ip_addr2a(&ip), su_getport(&send_info->to), send_info->proto); ret=ser_error=E_SEND; #ifdef USE_DNS_FAILOVER continue; /* try another ip */ #else goto error; #endif } } #endif if(unlikely(_forward_set_send_info==1)) { onsnd_info.to=&send_info->to; onsnd_info.send_sock=send_info->send_sock; onsnd_info.buf=buf; onsnd_info.len=len; onsnd_info.msg=msg; p_onsend=&onsnd_info; } if (msg_send(send_info, buf, len)<0){ p_onsend=0; ret=ser_error=E_SEND; #ifdef USE_DST_BLACKLIST (void)dst_blacklist_add(BLST_ERR_SEND, send_info, msg); #endif #ifdef USE_DNS_FAILOVER continue; /* try another ip */ #else goto error; #endif }else{ p_onsend=0; ret=ser_error=E_OK; /* sent requests stats */ STATS_TX_REQUEST( msg->first_line.u.request.method_value ); /* exit succcesfully */ goto end; } #ifdef USE_DNS_FAILOVER }while(dst && cfg_get(core, core_cfg, use_dns_failover) && dns_srv_handle_next(&dns_srv_h, err) && ((err=dns_sip_resolve2su(&dns_srv_h, &send_info->to, dst, port, &proto, dns_flags))==0)); if ((err!=0) && (err!=-E_DNS_EOR)){ LOG(L_ERR, "ERROR: resolving %.*s host name in uri" " failed: %s [%d] (dropping packet)\n", dst->len, ZSW(dst->s), dns_strerror(err), err); ret=ser_error=E_BAD_ADDRESS; goto error; } #endif error: STATS_TX_DROPS; end: #ifdef USE_DNS_FAILOVER if (dst && cfg_get(core, core_cfg, use_dns_failover)){ dns_srv_handle_put(&dns_srv_h); } #endif if (buf) pkg_free(buf); /* received_buf & line_buf will be freed in receive_msg by free_lump_list*/ #if defined STATS_REQ_FWD_OK || defined STATS_REQ_FWD_DROP if(ret==0) STATS_REQ_FWD_OK(); else STATS_REQ_FWD_DROP(); #endif /* STATS_REQ_FWD_* */ return ret; }
static void *thr_msg(void *arg) { assert(arg); TaskEnv *env = (TaskEnv *)arg; MsgHandle hMsg; MsgData msgData; hMsg = msg_create(env->name, env->dest, 0); if(!hMsg) { ERR("create msg handle failed..."); goto exit; } DBG("create msg ok, our name: %s, dst name: %s.", env->name, env->dest); sleep(1); int cnt = 0, dataLen = sizeof(msgData.header); int err; memset(&msgData, 0, sizeof(msgData)); msgData.header.cmd = cnt; msgData.header.index = cnt; msgData.header.type = MSG_TYPE_REQU; msgData.header.dataLen = sprintf(msgData.buf, "%s start", env->name); dataLen = msgData.header.dataLen + sizeof(msgData.header); //msgData.header.dataLen += 16; if(env->id) { DBG("send msg to %s", env->dest); err = msg_send(hMsg, env->dest, &msgData.header, 0); if(err < 0) DBG("send msg returns %d", err); } DBG("%s, start recv msg", env->name); struct timeval tmStart,tmEnd; float timeUse; err = msg_set_recv_timeout(hMsg, 1); err |= msg_set_send_timeout(hMsg, 2); assert(err == E_NO); while(1) { /* Do echo loop */ gettimeofday(&tmStart,NULL); err = msg_recv(hMsg, &msgData.header, sizeof(MsgData), 0); gettimeofday(&tmEnd,NULL); if(err > 0) { DBG("<%u> recv msg from %s, len: %d", (unsigned int)pthread_self(), msg_get_recv_src(hMsg), err); DBG(" cmd: %d, index: %d", msgData.header.cmd, msgData.header.index); if(msgData.header.dataLen > 0) DBG(" append data: %s", msgData.buf); timeUse = 1000000*(tmEnd.tv_sec-tmStart.tv_sec)+tmEnd.tv_usec-tmStart.tv_usec; DBG(" recv cost: %.0f us", timeUse); } /* Send back data */ sprintf(msgData.buf, "<%d> %s send msg", cnt, env->name); msgData.header.dataLen = sizeof(msgData.buf); msgData.header.type = MSG_TYPE_RESP; msgData.header.index = cnt; dataLen = msgData.header.dataLen + sizeof(msgData.header); gettimeofday(&tmStart,NULL); err = msg_send(hMsg, NULL, &msgData.header, 0); gettimeofday(&tmEnd,NULL); if(err) ERR("Send msg failed"); timeUse = 1000000*(tmEnd.tv_sec-tmStart.tv_sec)+tmEnd.tv_usec-tmStart.tv_usec; DBG("<%u> send %d bytes msg to %s cost: %.0f us", (unsigned int)pthread_self(), dataLen, msg_get_recv_src(hMsg), timeUse); cnt++; if( env->params->loopCnt > 0 && cnt > env->params->loopCnt) break; } exit: if(env) free(env); if(hMsg) msg_delete(hMsg); pthread_exit(0); }
void* PCmain(void* varg) { thread_t from; unsigned int tag; char PCbuff[64]; unsigned int msgSize = 64; int err; PCthreadArgs* targs = (PCthreadArgs*)varg; assert( targs != NULL ); // define all tunable constants used by the performance Consultant // tunable constants must be defined here in the sequential section // of the code, or values specified in pcl files won't be handled // properly. initPCconstants(); // thread startup thr_name("PerformanceConsultant"); pc = new performanceConsultant(targs->mainTid); msg_send (targs->mainTid, MSG_TAG_PC_READY, (char *) NULL, 0); from = targs->mainTid; tag = MSG_TAG_ALL_CHILDREN_READY; msg_recv (&from, &tag, PCbuff, &msgSize); assert( from == targs->mainTid ); // register performance stream with data manager union dataCallback dataHandlers; struct controlCallback controlHandlers; memset(&controlHandlers, '\0', sizeof(controlHandlers)); controlHandlers.fFunc = PCfold; controlHandlers.pFunc = PCphase; // At this time, don't need to to receive notice of retired resources //controlHandlers.retireFunc = PCresourceRetiredCallback; // will wait to implement this controlHandlers.avFunc = PCinitialActualValue; // The PC has to register a callback routine for predictedDataCost callbacks // even though there is a kludge in the PC to receive the msg before the // callback routine is called (PCpredData will never execute). This is // to maintain consistency in how the DM handles all callback functions. controlHandlers.cFunc = PCpredData; // The PC has to register a callback routine for enableDataRequest callbacks // even though there is a kludge in the PC to receive the msg before the // callback routine is called (PCenableDataCallback will never execute). controlHandlers.eFunc = PCenableDataCallback; // don't ask for a signal to flush our data controlHandlers.flFunc= 0; dataHandlers.sample = PCnewDataCallback; // the performance stream is used to identify this thread to the // data manager performanceConsultant::pstream = dataMgr->createPerformanceStream (Sample, dataHandlers, controlHandlers); // Note: remaining initialization is application- and/or phase-specific and // is done after the user requests a search. #ifdef MYPCDEBUG timeStamp t1 = getCurrentTime(); timeStamp t2; timeLength TIME_TO_CHECK = timeLength::sec() * 2; #endif while (1) { #ifdef MYPCDEBUG t2 = getCurrentTime(); if ((t2-t1) > TIME_TO_CHECK) { unsigned loopLimit, loopStart; for (unsigned j=1;j<=1;j++) { if (j==1) { loopStart = (unsigned)T_performanceConsultant::verify + 1; loopLimit = (unsigned)T_performanceConsultant::last; } else { loopStart = (unsigned)T_dataManager::verify + 1; loopLimit = (unsigned)T_dataManager::last; } for (unsigned i=loopStart;i<loopLimit;i++) { tag = i; //printf("********** waiting for tag=%d\n",tag); from = THR_TID_UNSPEC; if (msg_poll(&from, &tag, false) != THR_ERR) { readTag(tag); } } } t1=TESTgetTime(); } else { from = THR_TID_UNSPEC; tag = MSG_TAG_THREAD; err = msg_poll(&from, &tag, true); assert(err != THR_ERR); readTag(tag); } #else from = THR_TID_UNSPEC; tag = MSG_TAG_THREAD; err = msg_poll(&from, &tag, true); assert(err != THR_ERR); readTag(tag); #endif } return NULL; }
int main(int argc, char *argv[]) { struct { struct kdbus_cmd_bus_make head; /* name item */ uint64_t n_size; uint64_t n_type; char name[64]; } __attribute__ ((__aligned__(8))) bus_make; int fdc, ret, cookie; char *bus; struct conn *conn_a, *conn_b; struct pollfd fds[2]; int count; int r; printf("-- opening /dev/kdbus/control\n"); fdc = open("/dev/kdbus/control", O_RDWR|O_CLOEXEC); if (fdc < 0) { fprintf(stderr, "--- error %d (%m)\n", fdc); return EXIT_FAILURE; } memset(&bus_make, 0, sizeof(bus_make)); bus_make.head.bloom_size = 64; snprintf(bus_make.name, sizeof(bus_make.name), "%u-testbus", getuid()); bus_make.n_type = KDBUS_ITEM_MAKE_NAME; bus_make.n_size = KDBUS_ITEM_HEADER_SIZE + strlen(bus_make.name) + 1; bus_make.head.size = sizeof(struct kdbus_cmd_bus_make) + bus_make.n_size; printf("-- creating bus '%s'\n", bus_make.name); ret = ioctl(fdc, KDBUS_CMD_BUS_MAKE, &bus_make); if (ret) { fprintf(stderr, "--- error %d (%m)\n", ret); return EXIT_FAILURE; } if (asprintf(&bus, "/dev/kdbus/%s/bus", bus_make.name) < 0) return EXIT_FAILURE; conn_a = connect_to_bus(bus); conn_b = connect_to_bus(bus); if (!conn_a || !conn_b) return EXIT_FAILURE; r = upload_policy(conn_a->fd, "foo.bar.test"); if (r < 0) return EXIT_FAILURE; r = upload_policy(conn_a->fd, "foo.bar.baz"); if (r < 0) return EXIT_FAILURE; r = upload_policy(conn_a->fd, "foo.bar.double"); if (r < 0) return EXIT_FAILURE; r = name_acquire(conn_a, "foo.bar.test", KDBUS_NAME_ALLOW_REPLACEMENT); if (r < 0) return EXIT_FAILURE; r = name_acquire(conn_a, "foo.bar.baz", 0); if (r < 0) return EXIT_FAILURE; r = name_acquire(conn_b, "foo.bar.baz", KDBUS_NAME_QUEUE); if (r < 0) return EXIT_FAILURE; r = name_acquire(conn_a, "foo.bar.double", 0); if (r < 0) return EXIT_FAILURE; r = name_acquire(conn_a, "foo.bar.double", 0); if (r != -EALREADY) return EXIT_FAILURE; r = name_release(conn_a, "foo.bar.double"); if (r < 0) return EXIT_FAILURE; r = name_release(conn_a, "foo.bar.double"); if (r != -ESRCH) return EXIT_FAILURE; name_list(conn_b, KDBUS_NAME_LIST_UNIQUE | KDBUS_NAME_LIST_NAMES); add_match_empty(conn_a->fd); add_match_empty(conn_b->fd); cookie = 0; msg_send(conn_b, NULL, 0xc0000000 | cookie, KDBUS_DST_ID_BROADCAST); fds[0].fd = conn_a->fd; fds[1].fd = conn_b->fd; printf("-- entering poll loop ...\n"); for (count = 0;; count++) { int i, nfds = sizeof(fds) / sizeof(fds[0]); for (i = 0; i < nfds; i++) { fds[i].events = POLLIN | POLLPRI | POLLHUP; fds[i].revents = 0; } ret = poll(fds, nfds, 3000); if (ret <= 0) break; if (fds[0].revents & POLLIN) { if (count > 2) name_release(conn_a, "foo.bar.baz"); msg_recv(conn_a); msg_send(conn_a, NULL, 0xc0000000 | cookie++, conn_b->id); } if (fds[1].revents & POLLIN) { msg_recv(conn_b); msg_send(conn_b, NULL, 0xc0000000 | cookie++, conn_a->id); } name_list(conn_b, KDBUS_NAME_LIST_UNIQUE | KDBUS_NAME_LIST_NAMES); if (count > 10) break; } printf("-- closing bus connections\n"); close(conn_a->fd); close(conn_b->fd); free(conn_a); free(conn_b); printf("-- closing bus master\n"); close(fdc); free(bus); return EXIT_SUCCESS; }
/*! \brief removes first via & sends msg to the second */ int forward_reply(struct sip_msg* msg) { char* new_buf; union sockaddr_union* to; unsigned int new_len; struct sr_module *mod; int proto; int id; /* used only by tcp*/ struct socket_info *send_sock; #ifdef USE_TCP char* s; int len; #endif to=0; id=0; new_buf=0; /*check if first via host = us */ if (check_via){ if (check_self(&msg->via1->host, msg->via1->port?msg->via1->port:SIP_PORT, msg->via1->proto)!=1){ LM_ERR("host in first via!=me : %.*s:%d\n", msg->via1->host.len, msg->via1->host.s, msg->via1->port); /* send error msg back? */ goto error; } } /* quick hack, slower for multiple modules*/ for (mod=modules;mod;mod=mod->next){ if ((mod->exports) && (mod->exports->response_f)){ LM_DBG("found module %s, passing reply to it\n", mod->exports->name); if (mod->exports->response_f(msg)==0) goto skip; } } /* if stateless fwd was disabled, we cannot have stateless replies here*/ if (sl_fwd_disabled) goto skip; /* we have to forward the reply stateless, so we need second via -bogdan*/ if (parse_headers( msg, HDR_VIA2_F, 0 )==-1 || (msg->via2==0) || (msg->via2->error!=PARSE_OK)) { /* no second via => error */ LM_ERR("no 2nd via found in reply from %s:%d <%.*s>\n", ip_addr2a(&msg->rcv.src_ip),msg->rcv.src_port, msg->len,msg->buf ); goto error; } to=(union sockaddr_union*)pkg_malloc(sizeof(union sockaddr_union)); if (to==0){ LM_ERR("out of pkg memory\n"); goto error; } proto=msg->via2->proto; if (update_sock_struct_from_via( to, msg, msg->via2 )==-1) goto error; #ifdef USE_TCP if (proto==PROTO_TCP #ifdef USE_TLS || proto==PROTO_TLS #endif ){ /* find id in i param if it exists */ if (msg->via1->i&&msg->via1->i->value.s){ s=msg->via1->i->value.s; len=msg->via1->i->value.len; id=reverse_hex2int(s, len); } } #endif send_sock = get_send_socket(msg, to, proto); new_buf = build_res_buf_from_sip_res( msg, &new_len, send_sock); if (!new_buf){ LM_ERR("failed to build rpl from req failed\n"); goto error; } if (msg_send(send_sock, proto, to, id, new_buf, new_len)<0) { update_stat( drp_rpls, 1); goto error0; } update_stat( fwd_rpls, 1); /* * If no port is specified in the second via, then this * message output a wrong port number - zero. Despite that * the correct port is choosen in update_sock_struct_from_via, * as its visible with su_getport(to); . */ LM_DBG("reply forwarded to %.*s:%d\n", msg->via2->host.len, msg->via2->host.s, (unsigned short) msg->via2->port); pkg_free(new_buf); pkg_free(to); skip: return 0; error: update_stat( err_rpls, 1); error0: if (new_buf) pkg_free(new_buf); if (to) pkg_free(to); return -1; }
void minipro_begin_transaction(minipro_handle_t *handle) { memset(msg, 0, sizeof(msg)); msg_init(msg, MP_REQUEST_STATUS1_MSG1, handle->device, handle->icsp); msg_send(handle, msg, 48); }
int ccnl_riot_client_get(kernel_pid_t relay_pid, char *name, char *reply_buf) { char *prefix[CCNL_MAX_NAME_COMP]; char *cp = strtok(name, "/"); int i = 0; while (i < (CCNL_MAX_NAME_COMP - 1) && cp) { prefix[i++] = cp; cp = strtok(NULL, "/"); } //prefix[i] = 0; //segment to request prefix[i + 1] = 0; int content_len = 0; for (int segment = 0; ; segment++) { char segment_string[16]; //max=999\0 memset(segment_string, 0, 16); snprintf(segment_string, 16, "%d", segment); prefix[i] = segment_string; unsigned char *interest_pkg = malloc(PAYLOAD_SIZE); if (!interest_pkg) { puts("ccnl_riot_client_get: malloc failed"); return 0; } unsigned int interest_nonce = genrand_uint32(); int interest_len = mkInterest(prefix, &interest_nonce, interest_pkg); DEBUGMSG(1, "relay_pid=%" PRIkernel_pid " interest_len=%d\n", relay_pid, interest_len); riot_ccnl_msg_t rmsg; rmsg.payload = interest_pkg; rmsg.size = interest_len; msg_t m, rep; m.content.ptr = (char *) &rmsg; m.type = CCNL_RIOT_MSG; msg_send(&m, relay_pid, 1); /* ######################################################################### */ msg_receive(&rep); free(interest_pkg); if (rep.type == CCNL_RIOT_NACK) { /* network stack was not able to fetch this chunk */ return 0; } /* we got a chunk of data from the network stack */ riot_ccnl_msg_t *rmsg_reply = (riot_ccnl_msg_t *) rep.content.ptr; unsigned char *data = rmsg_reply->payload; int datalen = (int) rmsg_reply->size; DEBUGMSG(1, "%d bytes left; msg from=%" PRIkernel_pid "\n", datalen, rep.sender_pid); int scope = 3, aok = 3, minsfx = 0, maxsfx = CCNL_MAX_NAME_COMP, contlen = 0; struct ccnl_buf_s *buf = 0, *nonce = 0, *ppkd = 0; struct ccnl_prefix_s *p = 0; unsigned char *content = 0; buf = ccnl_extract_prefix_nonce_ppkd(&data, &datalen, &scope, &aok, &minsfx, &maxsfx, &p, &nonce, &ppkd, &content, &contlen); if (!buf) { DEBUGMSG(6, " parsing error or no prefix\n"); return 0; } DEBUGMSG(1, "content_len=%d contlen=%d\n", content_len, contlen); memcpy(reply_buf + content_len, content, contlen); content_len += contlen; free_prefix(p); free_3ptr_list(buf, nonce, ppkd); ccnl_free(rmsg_reply); DEBUGMSG(1, "contentlen=%d CCNL_RIOT_CHUNK_SIZE=%d\n", contlen, CCNL_RIOT_CHUNK_SIZE); if (contlen < CCNL_RIOT_CHUNK_SIZE || CCNL_RIOT_CHUNK_SIZE < contlen) { /* last chunk */ break; } } return content_len; }
void minipro_end_transaction(minipro_handle_t *handle) { msg_init(msg, 0x04, handle->device, handle->icsp); msg[3] = 0x00; msg_send(handle, msg, 4); }
/** * replicates a locally created dialog to all the destinations * specified with the 'replicate_dialogs' modparam */ void replicate_dialog_created(struct dlg_cell *dlg) { struct replication_dest *d; static str module_name = str_init("dialog"); int callee_leg; str *vars, *profiles; str send_buffer; if (bin_init(&module_name, REPLICATION_DLG_CREATED, BIN_VERSION) != 0) goto error; callee_leg = callee_idx(dlg); bin_push_str(&dlg->callid); bin_push_str(&dlg->legs[DLG_CALLER_LEG].tag); bin_push_str(&dlg->legs[callee_leg].tag); bin_push_str(&dlg->from_uri); bin_push_str(&dlg->to_uri); bin_push_int(dlg->h_id); bin_push_int(dlg->start_ts); bin_push_int(dlg->state); bin_push_str(&dlg->legs[DLG_CALLER_LEG].bind_addr->sock_str); if (dlg->legs[callee_leg].bind_addr) bin_push_str(&dlg->legs[callee_leg].bind_addr->sock_str); else bin_push_str(NULL); bin_push_str(&dlg->legs[DLG_CALLER_LEG].r_cseq); bin_push_str(&dlg->legs[callee_leg].r_cseq); bin_push_str(&dlg->legs[DLG_CALLER_LEG].route_set); bin_push_str(&dlg->legs[callee_leg].route_set); bin_push_str(&dlg->legs[DLG_CALLER_LEG].contact); bin_push_str(&dlg->legs[callee_leg].contact); bin_push_str(&dlg->legs[callee_leg].from_uri); bin_push_str(&dlg->legs[callee_leg].to_uri); /* XXX: on shutdown only? */ vars = write_dialog_vars(dlg->vals); dlg_lock_dlg(dlg); profiles = write_dialog_profiles(dlg->profile_links); dlg_unlock_dlg(dlg); bin_push_str(vars); bin_push_str(profiles); bin_push_int(dlg->user_flags); bin_push_int(dlg->flags & ~(DLG_FLAG_NEW|DLG_FLAG_CHANGED|DLG_FLAG_VP_CHANGED)); bin_push_int((unsigned int)time(0) + dlg->tl.timeout - get_ticks()); bin_push_int(dlg->legs[DLG_CALLER_LEG].last_gen_cseq); bin_push_int(dlg->legs[callee_leg].last_gen_cseq); bin_get_buffer(&send_buffer); for (d = replication_dests; d; d = d->next) msg_send(0,PROTO_BIN,&d->to,0,send_buffer.s,send_buffer.len,0); if_update_stat(dlg_enable_stats,create_sent,1); return; error: LM_ERR("Failed to replicate created dialog\n"); }
int gnrc_netif_ipv6_addr_add_internal(gnrc_netif_t *netif, const ipv6_addr_t *addr, unsigned pfx_len, uint8_t flags) { unsigned idx = UINT_MAX; assert((netif != NULL) && (addr != NULL)); assert(!(ipv6_addr_is_multicast(addr) || ipv6_addr_is_unspecified(addr) || ipv6_addr_is_loopback(addr))); assert((pfx_len > 0) && (pfx_len <= 128)); gnrc_netif_acquire(netif); if ((flags & GNRC_NETIF_IPV6_ADDRS_FLAGS_STATE_MASK) == GNRC_NETIF_IPV6_ADDRS_FLAGS_STATE_TENTATIVE) { /* set to first retransmission */ flags &= ~GNRC_NETIF_IPV6_ADDRS_FLAGS_STATE_TENTATIVE; flags |= 0x1; } for (unsigned i = 0; i < GNRC_NETIF_IPV6_ADDRS_NUMOF; i++) { if (ipv6_addr_equal(&netif->ipv6.addrs[i], addr)) { gnrc_netif_release(netif); return i; } if ((idx == UINT_MAX) && (netif->ipv6.addrs_flags[i] == 0)) { idx = i; } } if (idx == UINT_MAX) { gnrc_netif_release(netif); return -ENOMEM; } #if GNRC_IPV6_NIB_CONF_ARSM ipv6_addr_t sol_nodes; int res; /* TODO: SHOULD delay join between 0 and MAX_RTR_SOLICITATION_DELAY * for SLAAC */ ipv6_addr_set_solicited_nodes(&sol_nodes, addr); res = gnrc_netif_ipv6_group_join_internal(netif, &sol_nodes); if (res < 0) { DEBUG("nib: Can't join solicited-nodes of %s on interface %u\n", ipv6_addr_to_str(addr_str, addr, sizeof(addr_str)), netif->pid); return res; } #endif /* GNRC_IPV6_NIB_CONF_ARSM */ netif->ipv6.addrs_flags[idx] = flags; memcpy(&netif->ipv6.addrs[idx], addr, sizeof(netif->ipv6.addrs[idx])); #ifdef MODULE_GNRC_IPV6_NIB if (_get_state(netif, idx) == GNRC_NETIF_IPV6_ADDRS_FLAGS_STATE_VALID) { void *state = NULL; gnrc_ipv6_nib_pl_t ple; bool in_pl = false; while (gnrc_ipv6_nib_pl_iter(netif->pid, &state, &ple)) { if (ipv6_addr_match_prefix(&ple.pfx, addr) >= pfx_len) { in_pl = true; } } if (!in_pl) { gnrc_ipv6_nib_pl_set(netif->pid, addr, pfx_len, UINT32_MAX, UINT32_MAX); } } #if GNRC_IPV6_NIB_CONF_SLAAC else if (!gnrc_netif_is_6ln(netif)) { /* cast to remove const qualifier (will still be used NIB internally as * const) */ msg_t msg = { .type = GNRC_IPV6_NIB_DAD, .content = { .ptr = &netif->ipv6.addrs[idx] } }; msg_send(&msg, gnrc_ipv6_pid); }