zmq::req_t::req_t (class ctx_t *parent_, uint32_t tid_, int sid_) : dealer_t (parent_, tid_, sid_), receiving_reply (false), message_begins (true), reply_pipe (NULL), request_id_frames_enabled (false), request_id (generate_random ()), strict (true) { options.type = ZMQ_REQ; }
zmq::stream_t::stream_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_), prefetched (false), routing_id_sent (false), current_out (NULL), more_out (false), next_integral_routing_id (generate_random ()) { options.type = ZMQ_STREAM; options.raw_socket = true; prefetched_routing_id.init (); prefetched_msg.init (); }
int write_chalresp_state(FILE *f, CR_STATE *state) { char challenge_hex[CR_CHALLENGE_SIZE * 2 + 1], response_hex[CR_RESPONSE_SIZE * 2 + 1]; char salt_hex[CR_SALT_SIZE * 2 + 1], hashed_hex[CR_RESPONSE_SIZE * 2 + 1]; unsigned char salt[CR_SALT_SIZE], hash[CR_RESPONSE_SIZE]; YK_PRF_METHOD prf_method = {20, yk_hmac_sha1}; unsigned int iterations = CR_DEFAULT_ITERATIONS; int fd; memset(challenge_hex, 0, sizeof(challenge_hex)); memset(response_hex, 0, sizeof(response_hex)); memset(salt_hex, 0, sizeof(salt_hex)); memset(hashed_hex, 0, sizeof(hashed_hex)); yubikey_hex_encode(challenge_hex, (char *)state->challenge, state->challenge_len); yubikey_hex_encode(response_hex, (char *)state->response, state->response_len); if(state->iterations > 0) { iterations = state->iterations; } generate_random(salt, CR_SALT_SIZE); yk_pbkdf2(response_hex, salt, CR_SALT_SIZE, iterations, hash, CR_RESPONSE_SIZE, &prf_method); yubikey_hex_encode(hashed_hex, (char *)hash, CR_RESPONSE_SIZE); yubikey_hex_encode(salt_hex, (char *)salt, CR_SALT_SIZE); rewind(f); fd = fileno(f); if (fd == -1) goto out; if (ftruncate(fd, 0)) goto out; fprintf(f, "v2:%s:%s:%s:%u:%d\n", challenge_hex, hashed_hex, salt_hex, iterations, state->slot); if (fflush(f) < 0) goto out; if (fsync(fd) < 0) goto out; return 1; out: return 0; }
void parallelcoord() { TNtuple *nt = NULL; Double_t s1x, s1y, s1z; Double_t s2x, s2y, s2z; Double_t s3x, s3y, s3z; r = new TRandom();; new TCanvas("c1", "c1",0,0,800,700); gStyle->SetPalette(1); nt = new TNtuple("nt","Demo ntuple","x:y:z:u:v:w"); for (Int_t i=0; i<20000; i++) { r->Sphere(s1x, s1y, s1z, 0.1); r->Sphere(s2x, s2y, s2z, 0.2); r->Sphere(s3x, s3y, s3z, 0.05); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s1x, s1y, s1z, s2x, s2y, s2z); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s2x-1, s2y-1, s2z, s1x+.5, s1y+.5, s1z+.5); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); generate_random(i); nt->Fill(s1x+1, s1y+1, s1z+1, s3x-2, s3y-2, s3z-2); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6); } nt->Draw("x:y:z:u:v:w","","para",5000); TParallelCoord* para = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para->SetDotsSpacing(5); TParallelCoordVar* firstaxis = (TParallelCoordVar*)para->GetVarList()->FindObject("x"); firstaxis->AddRange(new TParallelCoordRange(firstaxis,0.846018,1.158469)); para->AddSelection("violet"); para->GetCurrentSelection()->SetLineColor(kViolet); firstaxis->AddRange(new TParallelCoordRange(firstaxis,-0.169447,0.169042)); para->AddSelection("Orange"); para->GetCurrentSelection()->SetLineColor(kOrange+9); firstaxis->AddRange(new TParallelCoordRange(firstaxis,-1.263024,-0.755292)); }
int zmq::tcp_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. const int interval = current_reconnect_ivl + generate_random () % options.reconnect_ivl; // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. if (options.reconnect_ivl_max > 0 && options.reconnect_ivl_max > options.reconnect_ivl) // Calculate the next interval current_reconnect_ivl = std::min (current_reconnect_ivl * 2, options.reconnect_ivl_max); return interval; }
///driver function to generate, insert and search rb hash tree void random_runner() { clock_t start, end; double insert_array[10], search_array[10]; for ( int i = 0; i < 10; i++ ) { generate_random(); start = ((double)clock()*1000)/CLOCKS_PER_SEC; insert_random(); end = ((double)clock()*1000)/CLOCKS_PER_SEC; insert_array[i] = end - start; start = ((double)clock()*1000)/CLOCKS_PER_SEC; search_random(); end = ((double)clock()*1000)/CLOCKS_PER_SEC; search_array[i] = end - start; make_root_null(); } cout << avg ( insert_array ) << " " << avg ( search_array ) << endl; }
xs::xrespondent_t::xrespondent_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_), prefetched (0), more_in (false), current_out (NULL), more_out (false), next_peer_id (generate_random ()) { options.type = XS_XRESPONDENT; // If the connection disappears it makes no sense to read any more surveys // from it. The responses will be unroutable anyway. options.delay_on_disconnect = false; prefetched_msg.init (); }
void random_runner() { clock_t start, end; long insert_array[10], search_array[10]; cout << "Experiment Running....." << endl; for ( int i = 0; i < 10; i++ ) { generate_random(); start = clock(); insert_random(); end = clock(); insert_array[i] = end - start; start = clock(); search_random(); end = clock(); search_array[i] = end - start; make_root_null(); } cout << "Insert Avg. Time : " << avg ( insert_array ) << " " << "Search Avg. Time : " << avg ( search_array ) << endl; }
zmq::xrep_t::xrep_t (class ctx_t *parent_, uint32_t tid_) : socket_base_t (parent_, tid_), prefetched (false), more_in (false), current_out (NULL), more_out (false) { options.type = ZMQ_XREP; // If peer disconnect there's noone to send reply to anyway. We can drop // all the outstanding requests from that peer. options.delay_on_disconnect = false; prefetched_msg.init (); // Start the peer ID sequence from a random point. generate_random (&next_peer_id, sizeof (next_peer_id)); }
int zmq::ipc_connecter_t::get_new_reconnect_ivl () { // The new interval is the current interval + random value. int this_interval = current_reconnect_ivl + (generate_random () % options.reconnect_ivl); // Only change the current reconnect interval if the maximum reconnect // interval was set and if it's larger than the reconnect interval. if (options.reconnect_ivl_max > 0 && options.reconnect_ivl_max > options.reconnect_ivl) { // Calculate the next interval current_reconnect_ivl = current_reconnect_ivl * 2; if(current_reconnect_ivl >= options.reconnect_ivl_max) { current_reconnect_ivl = options.reconnect_ivl_max; } } return this_interval; }
zmq::router_t::router_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_), prefetched (false), identity_sent (false), more_in (false), current_out (NULL), more_out (false), next_peer_id (generate_random ()), mandatory (false), raw_sock (false), probe_router (false) { options.type = ZMQ_ROUTER; options.recv_identity = true; options.raw_sock = false; prefetched_id.init (); prefetched_msg.init (); }
int main(int argc, char *argv[]) { options opts = { { NULL }, NULL, 0 }; argp_parse(&argp, argc, argv, 0, 0, &opts); int length = 0, sleep_i = 40; TO_INT(opts.args[0], length, "LENGTH"); TO_INT(opts.sleep_i, sleep_i, "TIME"); char *len_str, *pad_str; len_str = (length)? opts.args[0]: ""; pad_str = (length)? " ": ""; fprintf(stderr, "generating %s%srandom bytes @ %d+c us/bit\n", len_str, pad_str, sleep_i); generate_random(length, sleep_i, stdout); return EXIT_SUCCESS; }
xs::xrep_t::xrep_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_), prefetched (0), more_in (false), current_out (NULL), more_out (false), next_peer_id (generate_random ()) { options.type = XS_XREP; // TODO: Uncomment the following line when XREP will become true XREP // rather than generic router socket. // If peer disconnect there's noone to send reply to anyway. We can drop // all the outstanding requests from that peer. // options.delay_on_disconnect = false; options.send_identity = true; options.recv_identity = true; prefetched_msg.init (); }
unsigned int get_random(void) { int v; unsigned int r; const char *path = "/dev/urandom"; if ((v = open(path, O_RDONLY)) == -1) { fprintf(stderr, "Error opening to %s: %s", path, strerror(errno)); return -1; } if (read(v, &r, sizeof(unsigned int)) < sizeof(unsigned int)) { close(v); fprintf(stderr, "Error reading %d bytes from %s: %s", sizeof(unsigned int), path, strerror(errno)); return -1; } close(v); return r%10000; return generate_random(); }
zmq::router_t::router_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_), prefetched (false), identity_sent (false), current_in (NULL), terminate_current_in (false), more_in (false), current_out (NULL), more_out (false), next_rid (generate_random ()), mandatory (false), // raw_socket functionality in ROUTER is deprecated raw_socket (false), probe_router (false), handover (false) { options.type = ZMQ_ROUTER; options.recv_identity = true; options.raw_socket = false; prefetched_id.init (); prefetched_msg.init (); }
void FileBase::setxattr(const char* name, const char* value, size_t size, int flags) { if (!name || !value) throw OSException(EFAULT); std::unique_ptr<byte[]> buffer(new byte[size]); byte* ciphertext = buffer.get(); byte meta[XATTR_MAC_LENGTH + XATTR_IV_LENGTH]; byte* iv = meta; byte* mac = iv + XATTR_IV_LENGTH; generate_random(iv, XATTR_IV_LENGTH); auto name_len = strlen(name); std::unique_ptr<byte[]> header(new byte[name_len + ID_LENGTH]); memcpy(header.get(), get_id().data(), ID_LENGTH); memcpy(header.get() + ID_LENGTH, name, name_len); aes_gcm_encrypt(value, size, header.get(), name_len + ID_LENGTH, get_key().data(), get_key().size(), iv, XATTR_IV_LENGTH, mac, XATTR_MAC_LENGTH, ciphertext); auto rc = fsetxattr_wrapper(file_descriptor(), name, ciphertext, size, flags); if (rc < 0) throw OSException(errno); rc = fsetxattr_wrapper(m_meta_fd, name, meta, sizeof(meta), flags); if (rc < 0) throw OSException(errno); }
void CMediaStream::SetUpSRTPKeys (void) { if (GetBoolValue(STREAM_VIDEO_USE_SRTP)) { srandom(GetTimestamp()); if (GetBoolValue(STREAM_VIDEO_SRTP_FIXED_KEYS)) { CHECK_AND_FREE(m_video_key); m_video_key = strdup(GetStringValue(STREAM_VIDEO_SRTP_KEY)); CHECK_AND_FREE(m_video_salt); m_video_salt = strdup(GetStringValue(STREAM_VIDEO_SRTP_SALT)); } else { if (m_video_key == NULL) m_video_key = generate_random(16); if(m_video_salt == NULL) m_video_salt = generate_random(14); } } if (GetBoolValue(STREAM_AUDIO_USE_SRTP)) { if (GetBoolValue(STREAM_AUDIO_SRTP_FIXED_KEYS)) { CHECK_AND_FREE(m_audio_key); m_audio_key = strdup(GetStringValue(STREAM_AUDIO_SRTP_KEY)); CHECK_AND_FREE(m_audio_salt); m_audio_salt = strdup(GetStringValue(STREAM_AUDIO_SRTP_SALT)); } else { if (m_audio_key == NULL) m_audio_key = generate_random(16); if(m_audio_salt == NULL) m_audio_salt = generate_random(14); } } if (GetBoolValue(STREAM_TEXT_USE_SRTP)) { if (GetBoolValue(STREAM_TEXT_SRTP_FIXED_KEYS)) { CHECK_AND_FREE(m_text_key); m_text_key = strdup(GetStringValue(STREAM_TEXT_SRTP_KEY)); CHECK_AND_FREE(m_text_salt); m_text_salt = strdup(GetStringValue(STREAM_TEXT_SRTP_SALT)); } else { if (m_text_key == NULL) m_text_key = generate_random(16); if(m_text_salt == NULL) m_text_salt = generate_random(14); } } }
static int do_add_hmac_chalresp(YK_KEY *yk, uint8_t slot, bool verbose, char *output_dir, unsigned int iterations, int *exit_code) { char buf[CR_RESPONSE_SIZE + 16]; CR_STATE state; int ret = 0; unsigned int response_len; char *fn; struct passwd *p; FILE *f = NULL; struct stat st; state.iterations = iterations; state.slot = slot; *exit_code = 1; p = getpwuid (getuid ()); if (! p) { fprintf (stderr, "Who am I???"); goto out; } /* * Create default output directory for the user */ if (!output_dir){ char fullpath[256]; snprintf(fullpath, 256,"%s/.yubico",p->pw_dir); //check if directory exists if (stat(fullpath,&st)!=0 ){ if(mkdir(fullpath, S_IRWXU)==-1){ fprintf(stderr, "Failed creating directory '%s' :%s\n", fullpath, strerror(errno)); } if(verbose){ printf("Directory %s created successfully.\n", fullpath); } } else{ if(!S_ISDIR(st.st_mode)){ fprintf(stderr, "Destination %s already exist and is not a directory.\n", fullpath); goto out; } } } if (! get_user_challenge_file(yk, output_dir, p, &fn)) { fprintf (stderr, "Failed getting chalresp state filename\n"); goto out; } if (stat(fn, &st) == 0) { fprintf(stderr, "File %s already exists, refusing to overwrite.\n", fn); goto out; } if (generate_random(state.challenge, CR_CHALLENGE_SIZE)) { fprintf (stderr, "FAILED getting %i bytes of random data\n", CR_CHALLENGE_SIZE); goto out; } state.challenge_len = CR_CHALLENGE_SIZE; if (! challenge_response(yk, state.slot, state.challenge, CR_CHALLENGE_SIZE, true, true, verbose, buf, sizeof(buf), &response_len)) goto out; /* Make sure we get different responses for different challenges There is a firmware bug in YubiKey 2.2 that makes it issue same response for all challenges unless HMAC_LT64 is set. */ { char buf2[CR_RESPONSE_SIZE + 16]; char challenge[CR_CHALLENGE_SIZE]; if (generate_random(challenge, CR_CHALLENGE_SIZE)) { fprintf (stderr, "FAILED getting %i bytes of random data\n", CR_CHALLENGE_SIZE); goto out; } if (! challenge_response(yk, state.slot, challenge, CR_CHALLENGE_SIZE, true, true, verbose, buf2, sizeof(buf2), &response_len)) goto out; if (memcmp(buf, buf2, response_len) == 0) { fprintf (stderr, "FAILED YubiKey is outputting the same response for different challenges." "Make sure you configure the key with the option HMAC_LT64.\n"); goto out; } } if (response_len > sizeof (state.response)) { fprintf (stderr, "Got too long response ??? (%u/%lu)", response_len, (unsigned long) sizeof(state.response)); goto out; } memcpy (state.response, buf, response_len); state.response_len = response_len; umask(077); f = fopen (fn, "w"); if (! f) { fprintf (stderr, "Failed opening '%s' for writing : %s\n", fn, strerror (errno)); goto out; } if (! write_chalresp_state (f, &state)) goto out; printf ("Stored initial challenge and expected response in '%s'.\n", fn); *exit_code = 0; ret = 1; out: if (f) fclose (f); return ret; }
static NTSTATUS smb1srv_tcon_local_allocate_id(struct db_context *db, uint32_t lowest_id, uint32_t highest_id, TALLOC_CTX *mem_ctx, struct db_record **_rec, uint32_t *_id) { struct smb1srv_tcon_local_allocate_state state = { .lowest_id = lowest_id, .highest_id = highest_id, .last_id = 0, .useable_id = lowest_id, .status = NT_STATUS_INTERNAL_ERROR, }; uint32_t i; uint32_t range; NTSTATUS status; int count = 0; *_rec = NULL; *_id = 0; if (lowest_id > highest_id) { return NT_STATUS_INSUFFICIENT_RESOURCES; } /* * first we try randomly */ range = (highest_id - lowest_id) + 1; for (i = 0; i < (range / 2); i++) { uint32_t id; uint8_t key_buf[SMBXSRV_TCON_LOCAL_TDB_KEY_SIZE]; TDB_DATA key; TDB_DATA val; struct db_record *rec = NULL; id = generate_random() % range; id += lowest_id; if (id < lowest_id) { id = lowest_id; } if (id > highest_id) { id = highest_id; } key = smbXsrv_tcon_local_id_to_key(id, key_buf); rec = dbwrap_fetch_locked(db, mem_ctx, key); if (rec == NULL) { return NT_STATUS_INSUFFICIENT_RESOURCES; } val = dbwrap_record_get_value(rec); if (val.dsize != 0) { TALLOC_FREE(rec); continue; } *_rec = rec; *_id = id; return NT_STATUS_OK; } /* * if the range is almost full, * we traverse the whole table * (this relies on sorted behavior of dbwrap_rbt) */ status = dbwrap_traverse_read(db, smb1srv_tcon_local_allocate_traverse, &state, &count); if (NT_STATUS_IS_OK(status)) { if (NT_STATUS_IS_OK(state.status)) { return NT_STATUS_INTERNAL_ERROR; } if (!NT_STATUS_EQUAL(state.status, NT_STATUS_INTERNAL_ERROR)) { return state.status; } if (state.useable_id <= state.highest_id) { state.status = NT_STATUS_OK; } else { return NT_STATUS_INSUFFICIENT_RESOURCES; } } else if (!NT_STATUS_EQUAL(status, NT_STATUS_INTERNAL_DB_CORRUPTION)) { /* * Here we really expect NT_STATUS_INTERNAL_DB_CORRUPTION! * * If we get anything else it is an error, because it * means we did not manage to find a free slot in * the db. */ return NT_STATUS_INSUFFICIENT_RESOURCES; } if (NT_STATUS_IS_OK(state.status)) { uint32_t id; uint8_t key_buf[SMBXSRV_TCON_LOCAL_TDB_KEY_SIZE]; TDB_DATA key; TDB_DATA val; struct db_record *rec = NULL; id = state.useable_id; key = smbXsrv_tcon_local_id_to_key(id, key_buf); rec = dbwrap_fetch_locked(db, mem_ctx, key); if (rec == NULL) { return NT_STATUS_INSUFFICIENT_RESOURCES; } val = dbwrap_record_get_value(rec); if (val.dsize != 0) { TALLOC_FREE(rec); return NT_STATUS_INTERNAL_DB_CORRUPTION; } *_rec = rec; *_id = id; return NT_STATUS_OK; } return state.status; } struct smbXsrv_tcon_local_fetch_state { struct smbXsrv_tcon *tcon; NTSTATUS status; }; static void smbXsrv_tcon_local_fetch_parser(TDB_DATA key, TDB_DATA data, void *private_data) { struct smbXsrv_tcon_local_fetch_state *state = (struct smbXsrv_tcon_local_fetch_state *)private_data; void *ptr; if (data.dsize != sizeof(ptr)) { state->status = NT_STATUS_INTERNAL_DB_ERROR; return; } memcpy(&ptr, data.dptr, data.dsize); state->tcon = talloc_get_type_abort(ptr, struct smbXsrv_tcon); state->status = NT_STATUS_OK; } static NTSTATUS smbXsrv_tcon_local_lookup(struct smbXsrv_tcon_table *table, uint32_t tcon_local_id, NTTIME now, struct smbXsrv_tcon **_tcon) { struct smbXsrv_tcon_local_fetch_state state = { .tcon = NULL, .status = NT_STATUS_INTERNAL_ERROR, }; uint8_t key_buf[SMBXSRV_TCON_LOCAL_TDB_KEY_SIZE]; TDB_DATA key; NTSTATUS status; *_tcon = NULL; if (tcon_local_id == 0) { return NT_STATUS_NETWORK_NAME_DELETED; } if (table == NULL) { /* this might happen before the end of negprot */ return NT_STATUS_NETWORK_NAME_DELETED; } if (table->local.db_ctx == NULL) { return NT_STATUS_INTERNAL_ERROR; } key = smbXsrv_tcon_local_id_to_key(tcon_local_id, key_buf); status = dbwrap_parse_record(table->local.db_ctx, key, smbXsrv_tcon_local_fetch_parser, &state); if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_FOUND)) { return NT_STATUS_NETWORK_NAME_DELETED; } else if (!NT_STATUS_IS_OK(status)) { return status; } if (!NT_STATUS_IS_OK(state.status)) { return state.status; } if (NT_STATUS_EQUAL(state.tcon->status, NT_STATUS_NETWORK_NAME_DELETED)) { return NT_STATUS_NETWORK_NAME_DELETED; } state.tcon->idle_time = now; *_tcon = state.tcon; return state.tcon->status; } static int smbXsrv_tcon_global_destructor(struct smbXsrv_tcon_global0 *global) { return 0; } static void smbXsrv_tcon_global_verify_record(struct db_record *db_rec, bool *is_free, bool *was_free, TALLOC_CTX *mem_ctx, struct smbXsrv_tcon_global0 **_g); static NTSTATUS smbXsrv_tcon_global_allocate(struct db_context *db, TALLOC_CTX *mem_ctx, struct smbXsrv_tcon_global0 **_global) { uint32_t i; struct smbXsrv_tcon_global0 *global = NULL; uint32_t last_free = 0; const uint32_t min_tries = 3; *_global = NULL; global = talloc_zero(mem_ctx, struct smbXsrv_tcon_global0); if (global == NULL) { return NT_STATUS_NO_MEMORY; } talloc_set_destructor(global, smbXsrv_tcon_global_destructor); /* * Here we just randomly try the whole 32-bit space * * We use just 32-bit, because we want to reuse the * ID for SRVSVC. */ for (i = 0; i < UINT32_MAX; i++) { bool is_free = false; bool was_free = false; uint32_t id; uint8_t key_buf[SMBXSRV_TCON_GLOBAL_TDB_KEY_SIZE]; TDB_DATA key; if (i >= min_tries && last_free != 0) { id = last_free; } else { id = generate_random(); } if (id == 0) { id++; } if (id == UINT32_MAX) { id--; } key = smbXsrv_tcon_global_id_to_key(id, key_buf); global->db_rec = dbwrap_fetch_locked(db, mem_ctx, key); if (global->db_rec == NULL) { talloc_free(global); return NT_STATUS_INSUFFICIENT_RESOURCES; } smbXsrv_tcon_global_verify_record(global->db_rec, &is_free, &was_free, NULL, NULL); if (!is_free) { TALLOC_FREE(global->db_rec); continue; } if (!was_free && i < min_tries) { /* * The session_id is free now, * but was not free before. * * This happens if a smbd crashed * and did not cleanup the record. * * If this is one of our first tries, * then we try to find a real free one. */ if (last_free == 0) { last_free = id; } TALLOC_FREE(global->db_rec); continue; } global->tcon_global_id = id; *_global = global; return NT_STATUS_OK; } /* should not be reached */ talloc_free(global); return NT_STATUS_INTERNAL_ERROR; }
/************************************************************************* * Function name: Client::discover * Description: Function for discover in class Client using UDP * Parameter: const void * buffer_obj //pointer to discover objective * Return: ERRNO * Remark: * Lastly modified by Kangning Xu on 15-5-25 *************************************************************************/ ERRNO Client::discover() { // Client std::cout << "discovery start!!" << std::endl; ERRNO rtnval; int sock = socket(AF_INET6,SOCK_DGRAM,0); if(sock < 0) { dieWithUserMessager("socket failed"); } int broadcastPerm = 1; if(setsockopt(sock,SOL_SOCKET,SO_BROADCAST,&broadcastPerm,sizeof(broadcastPerm)) < 0) { dieWithUserMessager("set sockopt failed"); } session_id= generate_random()%(MAX_SESSION_ID+1); // send a discover request enum MSG_TYPE type; char buffer[MAXSTRINGLENGTH]; Objective_Option obj_opt(Discovery, 0, (uint8_t*)"",0,0); uint16_t * bits = obj_opt.to_bits(); memcpy(buffer, bits, Objective_Option::len_except_value); client_udp_init(sock, "ff02::1", serverAddr); //std::cout<<"ready to send:"<<std::endl; rtnval = send(buffer, strlen(buffer), DISCOVERY_MSG); if(rtnval != SUCCESS) { dieWithUserMessager("sendto failed"); //std::cout<<rtnval<<std::endl; return rtnval; } // waiting for response //rtnval = m.nrecvfrom(nsock,session_id,buffer,type); rtnval = recv(buffer,type); if(rtnval == SUCCESS) { cur_states = OFF; close(sock); close_udp(); } if(rtnval != SUCCESS) { dieWithUserMessager("recv failed"); } else { if(type == RESPONSE_MSG) { Option recved_opt = Option::parse_bits((uint16_t *)buffer); option_type type = recved_opt.get_type(); char * recved_addr; if(type == Locator) { recved_addr = (char*)recved_opt.get_value(); std::cout<<"Server ip6: "<< recved_addr << std::endl; inet_pton(AF_INET6, recved_addr, &negoAddr.sin6_addr); // struct in6_addr ip = negoAddr.sin6_addr; // printf("0x%x%x%x%x\n", htonl(ip.s6_addr32[0]),htonl(ip.s6_addr32[1]),htonl(ip.s6_addr32[2]),htonl(ip.s6_addr32[3])); // char s[64]={"\0"}; // inet_ntop(AF_INET6,(void*)&ip,s,64); // std::cout <<"sin6_addr "<< s << std::endl; } else return ERROR; } // Option recved_opt = Option::parse_bits((uint16_t *)buffer); // std::cout <<"type "<< recved_opt.get_type() <<std::endl // <<"len "<< recved_opt.get_len() << std::endl // <<"value "<< (char*)recved_opt.get_value() << std::endl; } // strcpy((char *)buffer_obj,(char*)recved_opt.get_value()); std::cout << "dicovery end!!" <<std::endl; //m.nclose("",0); return SUCCESS; }
int main(void) { puts("\nTesting the shared library to generate a random number\n"); generate_random(); return 0; }
int do_add_hmac_chalresp(YK_KEY *yk, uint8_t slot, bool verbose, char *output_dir, int *exit_code) { char buf[CR_RESPONSE_SIZE + 16]; CR_STATE state; unsigned int flags = 0; int ret = 0; unsigned int response_len; char *fn; struct passwd *p; FILE *f = NULL; state.slot = slot; flags |= YK_FLAG_MAYBLOCK; *exit_code = 1; p = getpwuid (getuid ()); if (! p) { fprintf (stderr, "Who am I???"); goto out; } if (! get_user_challenge_file(yk, output_dir, p->pw_name, &fn)) { fprintf (stderr, "Failed getting chalresp state filename\n"); goto out; } if (generate_random(state.challenge, CR_CHALLENGE_SIZE)) { fprintf (stderr, "FAILED getting %i bytes of random data\n", CR_CHALLENGE_SIZE); goto out; } state.challenge_len = CR_CHALLENGE_SIZE; if (! challenge_response(yk, state.slot, state.challenge, CR_CHALLENGE_SIZE, true, flags, verbose, buf, sizeof(buf), &response_len)) goto out; if (response_len > sizeof (state.response)) { fprintf (stderr, "Got too long response ??? (%i/%i)", response_len, sizeof(state.response)); goto out; } memcpy (state.response, buf, response_len); state.response_len = response_len; f = fopen (fn, "w"); if (! f) { fprintf (stderr, "Failed opening '%s' for writing : %s\n", fn, strerror (errno)); goto out; } if (! write_chalresp_state (f, &state)) goto out; printf ("Stored initial challenge and expected response in '%s'.\n", fn); *exit_code = 0; ret = 1; out: if (f) fclose (f); return ret; }
int main(int argc, char **argv) { unsigned char * buf; char * result, * result2; FILE *handle; srand(1); buf = (unsigned char *)malloc(SIZE); result = (char *)malloc(FUZZY_MAX_RESULT); result2 = (char *)malloc(FUZZY_MAX_RESULT); if (NULL == result || NULL == buf || NULL == result2) { fprintf (stderr,"%s: Out of memory\n", argv[0]); return EXIT_FAILURE; } generate_random(buf,SIZE); if (write_data(buf,SIZE,FILENAME)) return EXIT_FAILURE; printf ("Hashing buffer\n"); int status = fuzzy_hash_buf(buf,SIZE,result); if (status) printf ("Error during buf hash\n"); else printf ("%s\n", result); handle = fopen(FILENAME,"rb"); if (NULL == handle) { perror(FILENAME); return EXIT_FAILURE; } printf ("Hashing file\n"); status = fuzzy_hash_file(handle,result); if (status) printf ("Error during file hash\n"); else printf ("%s\n", result); fclose(handle); printf ("Modifying buffer and comparing to file\n"); int i; for (i = 0x100 ; i < 0x110 ; ++i) buf[i] = 37; status = fuzzy_hash_buf(buf,SIZE,result2); if (status) printf ("Error during buffer hash\n"); else printf ("%s\n", result2); i = fuzzy_compare(result,result2); if (-1 == i) printf ("An error occured during matching\n"); else { if (i != 0) printf ("MATCH: score = %d\n", i); else printf ("did not match\n"); } return EXIT_SUCCESS; }
zmq::server_t::server_t (class ctx_t *parent_, uint32_t tid_, int sid_) : socket_base_t (parent_, tid_, sid_, true), next_rid (generate_random ()) { options.type = ZMQ_SERVER; }
int do_add_hmac_chalresp(YK_KEY *yk, uint8_t slot, bool verbose, char *output_dir, int *exit_code) { char buf[CR_RESPONSE_SIZE + 16]; CR_STATE state; unsigned int flags = 0; int ret = 0; unsigned int response_len; char *fn; struct passwd *p; FILE *f = NULL; state.slot = slot; flags |= YK_FLAG_MAYBLOCK; *exit_code = 1; p = getpwuid (getuid ()); if (! p) { fprintf (stderr, "Who am I???"); goto out; } if (! get_user_challenge_file(yk, output_dir, p->pw_name, &fn)) { fprintf (stderr, "Failed getting chalresp state filename\n"); goto out; } if (generate_random(state.challenge, CR_CHALLENGE_SIZE)) { fprintf (stderr, "FAILED getting %i bytes of random data\n", CR_CHALLENGE_SIZE); goto out; } state.challenge_len = CR_CHALLENGE_SIZE; if (! challenge_response(yk, state.slot, state.challenge, CR_CHALLENGE_SIZE, true, flags, verbose, buf, sizeof(buf), &response_len)) goto out; /* Make sure we get different responses for different challenges There is a firmware bug in YubiKey 2.2 that makes it issue same response for all challenges unless HMAC_LT64 is set. */ { char buf2[CR_RESPONSE_SIZE + 16]; char challenge[CR_CHALLENGE_SIZE]; CR_STATE state2; if (generate_random(challenge, CR_CHALLENGE_SIZE)) { fprintf (stderr, "FAILED getting %i bytes of random data\n", CR_CHALLENGE_SIZE); goto out; } if (! challenge_response(yk, state.slot, challenge, CR_CHALLENGE_SIZE, true, flags, verbose, buf2, sizeof(buf2), &response_len)) goto out; if (memcmp(buf, buf2, response_len) == 0) { fprintf (stderr, "FAILED YubiKey is outputting the same response for different challenges." "Make sure you configure the key with the option HMAC_LT64.\n"); goto out; } } if (response_len > sizeof (state.response)) { fprintf (stderr, "Got too long response ??? (%u/%lu)", response_len, (unsigned long) sizeof(state.response)); goto out; } memcpy (state.response, buf, response_len); state.response_len = response_len; f = fopen (fn, "w"); if (! f) { fprintf (stderr, "Failed opening '%s' for writing : %s\n", fn, strerror (errno)); goto out; } if (! write_chalresp_state (f, &state)) goto out; printf ("Stored initial challenge and expected response in '%s'.\n", fn); *exit_code = 0; ret = 1; out: if (f) fclose (f); return ret; }
void parallelcoordtrans() { Double_t x,y,z,u,v,w,a,b,c; Double_t s1x, s1y, s1z; Double_t s2x, s2y, s2z; Double_t s3x, s3y, s3z; r = new TRandom();; TCanvas *c1 = new TCanvas("c1", "c1",0,0,900,1000); c1->Divide(1,2); if (gVirtualX && !gVirtualX->InheritsFrom("TGCocoa")) { std::cout<<"This macro works only on MacOS X with --enable-cocoa\n"; delete c1; delete r; return; } TNtuple *nt = new TNtuple("nt","Demo ntuple","x:y:z:u:v:w:a:b:c"); int n=0; for (Int_t i=0; i<1500; i++) { r->Sphere(s1x, s1y, s1z, 0.1); r->Sphere(s2x, s2y, s2z, 0.2); r->Sphere(s3x, s3y, s3z, 0.05); generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); n++; generate_random(i); nt->Fill(s1x, s1y, s1z, s2x, s2y, s2z, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, s3y, r9); n++; generate_random(i); nt->Fill(s2x-1, s2y-1, s2z, s1x+.5, s1y+.5, s1z+.5, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, r7, r8, r9); n++; generate_random(i); nt->Fill(s1x+1, s1y+1, s1z+1, s3x-2, s3y-2, s3z-2, r7, r8, r9); n++; generate_random(i); nt->Fill(r1, r2, r3, r4, r5, r6, s3x, r8, s3z ); n++; } TParallelCoordVar* pcv; c1->cd(1); // ||-Coord plot without transparency nt->Draw("x:y:z:u:v:w:a:b:c","","para"); TParallelCoord* para1 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para1->SetLineColor(25); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para1->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); // ||-Coord plot with transparency TColor *col26 = gROOT->GetColor(26); col26->SetAlpha(0.01); c1->cd(2); nt->Draw("x:y:z:u:v:w:a:b:c","","para"); TParallelCoord* para2 = (TParallelCoord*)gPad->GetListOfPrimitives()->FindObject("ParaCoord"); para2->SetLineColor(26); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("x"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("y"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("z"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("a"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("b"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("c"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("u"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("v"); pcv->SetHistogramHeight(0.); pcv = (TParallelCoordVar*)para2->GetVarList()->FindObject("w"); pcv->SetHistogramHeight(0.); }
void* neighborhood_search(void *numElementsInput) { //Method for performing neighborhood search functions int numElementsCurrent; //Number of matrix elements memcpy(&numElementsCurrent,(int *)numElementsInput,sizeof(int)); //Copy the number of elements int sideLength = sqrt(numElementsCurrent); //The size of the matrix rows and columns int sumNeighborhood, newInt = 0; //Sum of neighbor values int numNeighbors = 8; //Number of neighbors to check pthread_mutex_lock(&count_mutex);//Mutually exclude multiple threads from writing to the binary file at the same time int columnPos = generate_random(sideLength-1); //Randomly generate a column position int rowPos = generate_random(sideLength-1); //Randomly generate a row position //Seach the neighborhood and sum the current neighbors values fseek(smf, sizeof(int)*((columnPos-1)*sideLength+(rowPos-1)), SEEK_SET); //Neighbor one if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos)*sideLength+(rowPos-1)), SEEK_SET); //Neighbor two if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos+1)*sideLength+(rowPos-1)), SEEK_SET); //Neighbor three if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos-1)*sideLength+(rowPos)), SEEK_SET); //Neighbor four if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos+1)*sideLength+(rowPos)), SEEK_SET); //Neighbor five if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos-1)*sideLength+(rowPos+1)), SEEK_SET); //Neighbor six if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos)*sideLength+(rowPos+1)), SEEK_SET); //Neighbor seven if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*((columnPos+1)*sideLength+(rowPos+1)), SEEK_SET); //Neighbor eight if (ferror(smf)) { //Check if neighbor does not exist numNeighbors--; //Decremment numNeighbors }else{ //Neighbor does exist fread(&newInt, sizeof(int), 1, smf); //Read neighbor position sumNeighborhood += newInt; //Add the neighbors value } //End if, else fseek(smf, sizeof(int)*(columnPos*sideLength+rowPos), SEEK_SET); //Look for the specified random byte and position pointer if(sumNeighborhood > (numNeighbors/2)) { //Majority of neighbor values are 1 newInt = 1; //Set value to be written to 1 fwrite(&newInt, sizeof(int), 1, smf); //Change the specified byte printf("Value updated to 1 (Row: %i, Column: %i)\n", rowPos, columnPos); //Print changes to the screen } else if(sumNeighborhood < (numNeighbors/2)) { //Majority of neighbor values are 0 newInt = 0; //Set value to be written to 0 fwrite(&newInt, sizeof(int), 1, smf); //Change the specified byte printf("Value updated to 0 (Row: %i, Column: %i)\n", rowPos, columnPos); //Print changes to the screen } else { //Either they had no neighbors or a majority could not be determined printf("Value not updated (Row: %i, Column: %i)\n", rowPos, columnPos); //Print that no change occured to the screen } //End if, else pthread_mutex_unlock(&count_mutex); } //End neighborhood_search
static int do_challenge_response(pam_handle_t *pamh, struct cfg *cfg, const char *username) { char *userfile = NULL, *tmpfile = NULL; FILE *f = NULL; unsigned char buf[CR_RESPONSE_SIZE + 16], response_hex[CR_RESPONSE_SIZE * 2 + 1]; int ret; unsigned int flags = 0; unsigned int response_len = 0; unsigned int expect_bytes = 0; YK_KEY *yk = NULL; CR_STATE state; int len; char *errstr = NULL; ret = PAM_AUTH_ERR; flags |= YK_FLAG_MAYBLOCK; if (! init_yubikey(&yk)) { D(("Failed initializing YubiKey")); goto out; } if (! check_firmware_version(yk, false, true)) { D(("YubiKey does not support Challenge-Response (version 2.2 required)")); goto out; } if (! get_user_challenge_file (yk, cfg->chalresp_path, username, &userfile)) { D(("Failed getting user challenge file for user %s", username)); goto out; } DBG(("Loading challenge from file %s", userfile)); /* XXX should drop root privileges before opening file in user's home directory */ f = fopen(userfile, "r"); if (! load_chalresp_state(f, &state)) goto out; if (fclose(f) < 0) { f = NULL; goto out; } if (! challenge_response(yk, state.slot, state.challenge, state.challenge_len, true, flags, false, buf, sizeof(buf), &response_len)) { D(("Challenge-response FAILED")); goto out; } /* * Check YubiKey response against the expected response */ yubikey_hex_encode(response_hex, (char *)buf, response_len); if (memcmp(buf, state.response, response_len) == 0) { ret = PAM_SUCCESS; } else { D(("Unexpected C/R response : %s", response_hex)); goto out; } DBG(("Got the expected response, generating new challenge (%i bytes).", CR_CHALLENGE_SIZE)); errstr = "Error generating new challenge, please check syslog or contact your system administrator"; if (generate_random(state.challenge, sizeof(state.challenge))) { D(("Failed generating new challenge!")); goto out; } errstr = "Error communicating with Yubikey, please check syslog or contact your system administrator"; if (! challenge_response(yk, state.slot, state.challenge, CR_CHALLENGE_SIZE, true, flags, false, buf, sizeof(buf), &response_len)) { D(("Second challenge-response FAILED")); goto out; } /* the yk_* functions leave 'junk' in errno */ errno = 0; /* * Write the challenge and response we will expect the next time to the state file. */ if (response_len > sizeof(state.response)) { D(("Got too long response ??? (%i/%i)", response_len, sizeof(state.response))); goto out; } memcpy (state.response, buf, response_len); state.response_len = response_len; /* Write out the new file */ tmpfile = malloc(strlen(userfile) + 1 + 4); if (! tmpfile) goto out; strcpy(tmpfile, userfile); strcat(tmpfile, ".tmp"); f = fopen(tmpfile, "w"); if (! f) goto out; errstr = "Error updating Yubikey challenge, please check syslog or contact your system administrator"; if (! write_chalresp_state (f, &state)) goto out; if (fclose(f) < 0) { f = NULL; goto out; } f = NULL; if (rename(tmpfile, userfile) < 0) { goto out; } DBG(("Challenge-response success!")); errstr = NULL; out: if (yk_errno) { if (yk_errno == YK_EUSBERR) { syslog(LOG_ERR, "USB error: %s", yk_usb_strerror()); D(("USB error: %s", yk_usb_strerror())); } else { syslog(LOG_ERR, "Yubikey core error: %s", yk_strerror(yk_errno)); D(("Yubikey core error: %s", yk_strerror(yk_errno))); } } if (errstr) display_error(pamh, errstr); if (errno) { syslog(LOG_ERR, "Challenge response failed: %s", strerror(errno)); D(("Challenge response failed: %s", strerror(errno))); } if (yk) yk_close_key(yk); yk_release(); if (f) fclose(f); free(userfile); free(tmpfile); return ret; }
/* send a mailslot request */ NTSTATUS dgram_mailslot_send(struct nbt_dgram_socket *dgmsock, enum dgram_msg_type msg_type, const char *mailslot_name, struct nbt_name *dest_name, struct socket_address *dest, struct nbt_name *src_name, DATA_BLOB *request) { TALLOC_CTX *tmp_ctx = talloc_new(dgmsock); struct nbt_dgram_packet packet; struct dgram_message *msg; struct dgram_smb_packet *smb; struct smb_trans_body *trans; struct socket_address *src; NTSTATUS status; if (dest->port == 0) { return NT_STATUS_INVALID_PARAMETER; } ZERO_STRUCT(packet); packet.msg_type = msg_type; packet.flags = DGRAM_FLAG_FIRST | DGRAM_NODE_NBDD; packet.dgram_id = generate_random() % UINT16_MAX; src = socket_get_my_addr(dgmsock->sock, tmp_ctx); if (!src) { return NT_STATUS_NO_MEMORY; } packet.src_addr = src->addr; packet.src_port = src->port; msg = &packet.data.msg; /* this length calculation is very crude - it should be based on gensize calls */ msg->length = 138 + strlen(mailslot_name) + request->length; msg->offset = 0; msg->source_name = *src_name; msg->dest_name = *dest_name; msg->dgram_body_type = DGRAM_SMB; smb = &msg->body.smb; smb->smb_command = SMB_TRANSACTION; trans = &smb->body.trans; trans->total_data_count = request->length; trans->timeout = 1000; trans->data_count = request->length; trans->data_offset = 70 + strlen(mailslot_name); trans->opcode = 1; /* write mail slot */ trans->priority = 1; trans->_class = 2; trans->mailslot_name = mailslot_name; trans->data = *request; status = nbt_dgram_send(dgmsock, &packet, dest); talloc_free(tmp_ctx); return status; }
// Create, bind and connect PGM socket. int zmq::pgm_socket_t::init (bool udp_encapsulation_, const char *network_) { // Can not open transport before destroying old one. zmq_assert (sock == NULL); zmq_assert (options.rate > 0); // Zero counter used in msgrecv. nbytes_rec = 0; nbytes_processed = 0; pgm_msgv_processed = 0; uint16_t port_number; struct pgm_addrinfo_t *res = NULL; sa_family_t sa_family; pgm_error_t *pgm_error = NULL; if (init_address(network_, &res, &port_number) < 0) { goto err_abort; } zmq_assert (res != NULL); // Pick up detected IP family. sa_family = res->ai_send_addrs[0].gsr_group.ss_family; // Create IP/PGM or UDP/PGM socket. if (udp_encapsulation_) { if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_UDP, &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && ( pgm_error->code != PGM_ERROR_BADF && pgm_error->code != PGM_ERROR_FAULT && pgm_error->code != PGM_ERROR_NOPROTOOPT && pgm_error->code != PGM_ERROR_FAILED)) // User, host, or network configuration or transient error. goto err_abort; // Fatal OpenPGM internal error. zmq_assert (false); } // All options are of data type int const int encapsulation_port = port_number; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_UCAST_PORT, &encapsulation_port, sizeof (encapsulation_port))) goto err_abort; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_UDP_ENCAP_MCAST_PORT, &encapsulation_port, sizeof (encapsulation_port))) goto err_abort; } else { if (!pgm_socket (&sock, sa_family, SOCK_SEQPACKET, IPPROTO_PGM, &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); if (pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET && ( pgm_error->code != PGM_ERROR_BADF && pgm_error->code != PGM_ERROR_FAULT && pgm_error->code != PGM_ERROR_NOPROTOOPT && pgm_error->code != PGM_ERROR_FAILED)) // User, host, or network configuration or transient error. goto err_abort; // Fatal OpenPGM internal error. zmq_assert (false); } } { const int rcvbuf = (int) options.rcvbuf; if (rcvbuf) { if (!pgm_setsockopt (sock, SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof (rcvbuf))) goto err_abort; } const int sndbuf = (int) options.sndbuf; if (sndbuf) { if (!pgm_setsockopt (sock, SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof (sndbuf))) goto err_abort; } const int max_tpdu = (int) pgm_max_tpdu; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MTU, &max_tpdu, sizeof (max_tpdu))) goto err_abort; } if (receiver) { const int recv_only = 1, rxw_max_tpdu = (int) pgm_max_tpdu, rxw_sqns = compute_sqns (rxw_max_tpdu), peer_expiry = pgm_secs (300), spmr_expiry = pgm_msecs (25), nak_bo_ivl = pgm_msecs (50), nak_rpt_ivl = pgm_msecs (200), nak_rdata_ivl = pgm_msecs (200), nak_data_retries = 50, nak_ncf_retries = 50; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_RECV_ONLY, &recv_only, sizeof (recv_only)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_RXW_SQNS, &rxw_sqns, sizeof (rxw_sqns)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_PEER_EXPIRY, &peer_expiry, sizeof (peer_expiry)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_SPMR_EXPIRY, &spmr_expiry, sizeof (spmr_expiry)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_BO_IVL, &nak_bo_ivl, sizeof (nak_bo_ivl)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RPT_IVL, &nak_rpt_ivl, sizeof (nak_rpt_ivl)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_RDATA_IVL, &nak_rdata_ivl, sizeof (nak_rdata_ivl)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_DATA_RETRIES, &nak_data_retries, sizeof (nak_data_retries)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_NAK_NCF_RETRIES, &nak_ncf_retries, sizeof (nak_ncf_retries))) goto err_abort; } else { const int send_only = 1, max_rte = (int) ((options.rate * 1000) / 8), txw_max_tpdu = (int) pgm_max_tpdu, txw_sqns = compute_sqns (txw_max_tpdu), ambient_spm = pgm_secs (30), heartbeat_spm[] = { pgm_msecs (100), pgm_msecs (100), pgm_msecs (100), pgm_msecs (100), pgm_msecs (1300), pgm_secs (7), pgm_secs (16), pgm_secs (25), pgm_secs (30) }; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_ONLY, &send_only, sizeof (send_only)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_ODATA_MAX_RTE, &max_rte, sizeof (max_rte)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_TXW_SQNS, &txw_sqns, sizeof (txw_sqns)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_AMBIENT_SPM, &ambient_spm, sizeof (ambient_spm)) || !pgm_setsockopt (sock, IPPROTO_PGM, PGM_HEARTBEAT_SPM, &heartbeat_spm, sizeof (heartbeat_spm))) goto err_abort; } // PGM transport GSI. struct pgm_sockaddr_t addr; memset (&addr, 0, sizeof(addr)); addr.sa_port = port_number; addr.sa_addr.sport = DEFAULT_DATA_SOURCE_PORT; // Create random GSI. uint32_t buf [2]; buf [0] = generate_random (); buf [1] = generate_random (); if (!pgm_gsi_create_from_data (&addr.sa_addr.gsi, (uint8_t*) buf, 8)) goto err_abort; // Bind a transport to the specified network devices. struct pgm_interface_req_t if_req; memset (&if_req, 0, sizeof(if_req)); if_req.ir_interface = res->ai_recv_addrs[0].gsr_interface; if_req.ir_scope_id = 0; if (AF_INET6 == sa_family) { struct sockaddr_in6 sa6; memcpy (&sa6, &res->ai_recv_addrs[0].gsr_group, sizeof (sa6)); if_req.ir_scope_id = sa6.sin6_scope_id; } if (!pgm_bind3 (sock, &addr, sizeof (addr), &if_req, sizeof (if_req), &if_req, sizeof (if_req), &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); if ((pgm_error->domain == PGM_ERROR_DOMAIN_SOCKET || pgm_error->domain == PGM_ERROR_DOMAIN_IF) && ( pgm_error->code != PGM_ERROR_INVAL && pgm_error->code != PGM_ERROR_BADF && pgm_error->code != PGM_ERROR_FAULT)) // User, host, or network configuration or transient error. goto err_abort; // Fatal OpenPGM internal error. zmq_assert (false); } // Join IP multicast groups. for (unsigned i = 0; i < res->ai_recv_addrs_len; i++) { if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_JOIN_GROUP, &res->ai_recv_addrs [i], sizeof (struct group_req))) goto err_abort; } if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_SEND_GROUP, &res->ai_send_addrs [0], sizeof (struct group_req))) goto err_abort; pgm_freeaddrinfo (res); res = NULL; // Set IP level parameters. { // Multicast loopback disabled by default const int multicast_loop = 0; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_LOOP, &multicast_loop, sizeof (multicast_loop))) goto err_abort; const int multicast_hops = options.multicast_hops; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_MULTICAST_HOPS, &multicast_hops, sizeof (multicast_hops))) goto err_abort; // Expedited Forwarding PHB for network elements, no ECN. // Ignore return value due to varied runtime support. const int dscp = 0x2e << 2; if (AF_INET6 != sa_family) pgm_setsockopt (sock, IPPROTO_PGM, PGM_TOS, &dscp, sizeof (dscp)); const int nonblocking = 1; if (!pgm_setsockopt (sock, IPPROTO_PGM, PGM_NOBLOCK, &nonblocking, sizeof (nonblocking))) goto err_abort; } // Connect PGM transport to start state machine. if (!pgm_connect (sock, &pgm_error)) { // Invalid parameters don't set pgm_error_t. zmq_assert (pgm_error != NULL); goto err_abort; } // For receiver transport preallocate pgm_msgv array. if (receiver) { zmq_assert (in_batch_size > 0); size_t max_tsdu_size = get_max_tsdu_size (); pgm_msgv_len = (int) in_batch_size / max_tsdu_size; if ((int) in_batch_size % max_tsdu_size) pgm_msgv_len++; zmq_assert (pgm_msgv_len); pgm_msgv = (pgm_msgv_t*) malloc (sizeof (pgm_msgv_t) * pgm_msgv_len); alloc_assert (pgm_msgv); } return 0; err_abort: if (sock != NULL) { pgm_close (sock, FALSE); sock = NULL; } if (res != NULL) { pgm_freeaddrinfo (res); res = NULL; } if (pgm_error != NULL) { pgm_error_free (pgm_error); pgm_error = NULL; } errno = EINVAL; return -1; }