// modifies the GString in place static int send_hepv3 (GString *s, const str *id, int capt_id, const endpoint_t *src, const endpoint_t *dst, const struct timeval *tv) { struct hep_generic *hg=NULL; void* buffer; unsigned int buflen=0, iplen=0,tlen=0; hep_chunk_ip4_t src_ip4, dst_ip4; hep_chunk_ip6_t src_ip6, dst_ip6; hep_chunk_t payload_chunk; //hep_chunk_t authkey_chunk; hep_chunk_t correlation_chunk; //static int errors = 0; hg = malloc(sizeof(struct hep_generic)); memset(hg, 0, sizeof(struct hep_generic)); /* header set */ memcpy(hg->header.id, "\x48\x45\x50\x33", 4); /* IP proto */ hg->ip_family.chunk.vendor_id = htons(0x0000); hg->ip_family.chunk.type_id = htons(0x0001); hg->ip_family.data = src->address.family->af; hg->ip_family.chunk.length = htons(sizeof(hg->ip_family)); /* Proto ID */ hg->ip_proto.chunk.vendor_id = htons(0x0000); hg->ip_proto.chunk.type_id = htons(0x0002); hg->ip_proto.data = IPPROTO_UDP; hg->ip_proto.chunk.length = htons(sizeof(hg->ip_proto)); /* IPv4 */ if(hg->ip_family.data == AF_INET) { /* SRC IP */ src_ip4.chunk.vendor_id = htons(0x0000); src_ip4.chunk.type_id = htons(0x0003); src_ip4.data = src->address.u.ipv4; src_ip4.chunk.length = htons(sizeof(src_ip4)); /* DST IP */ dst_ip4.chunk.vendor_id = htons(0x0000); dst_ip4.chunk.type_id = htons(0x0004); dst_ip4.data = dst->address.u.ipv4; dst_ip4.chunk.length = htons(sizeof(dst_ip4)); iplen = sizeof(dst_ip4) + sizeof(src_ip4); } /* IPv6 */ else if(hg->ip_family.data == AF_INET6) { /* SRC IPv6 */ src_ip6.chunk.vendor_id = htons(0x0000); src_ip6.chunk.type_id = htons(0x0005); src_ip6.data = src->address.u.ipv6; src_ip6.chunk.length = htons(sizeof(src_ip6)); /* DST IPv6 */ dst_ip6.chunk.vendor_id = htons(0x0000); dst_ip6.chunk.type_id = htons(0x0006); dst_ip6.data = dst->address.u.ipv6; dst_ip6.chunk.length = htons(sizeof(dst_ip6)); iplen = sizeof(dst_ip6) + sizeof(src_ip6); } /* SRC PORT */ hg->src_port.chunk.vendor_id = htons(0x0000); hg->src_port.chunk.type_id = htons(0x0007); hg->src_port.data = htons(src->port); hg->src_port.chunk.length = htons(sizeof(hg->src_port)); /* DST PORT */ hg->dst_port.chunk.vendor_id = htons(0x0000); hg->dst_port.chunk.type_id = htons(0x0008); hg->dst_port.data = htons(dst->port); hg->dst_port.chunk.length = htons(sizeof(hg->dst_port)); /* TIMESTAMP SEC */ hg->time_sec.chunk.vendor_id = htons(0x0000); hg->time_sec.chunk.type_id = htons(0x0009); hg->time_sec.data = htonl(tv->tv_sec); hg->time_sec.chunk.length = htons(sizeof(hg->time_sec)); /* TIMESTAMP USEC */ hg->time_usec.chunk.vendor_id = htons(0x0000); hg->time_usec.chunk.type_id = htons(0x000a); hg->time_usec.data = htonl(tv->tv_usec); hg->time_usec.chunk.length = htons(sizeof(hg->time_usec)); /* Protocol TYPE */ hg->proto_t.chunk.vendor_id = htons(0x0000); hg->proto_t.chunk.type_id = htons(0x000b); hg->proto_t.data = PROTO_RTCP_JSON; hg->proto_t.chunk.length = htons(sizeof(hg->proto_t)); /* Capture ID */ hg->capt_id.chunk.vendor_id = htons(0x0000); hg->capt_id.chunk.type_id = htons(0x000c); hg->capt_id.data = capt_id; hg->capt_id.chunk.length = htons(sizeof(hg->capt_id)); /* Payload */ payload_chunk.vendor_id = htons(0x0000); payload_chunk.type_id = 0 ? htons(0x0010) : htons(0x000f); payload_chunk.length = htons(sizeof(payload_chunk) + s->len); tlen = sizeof(struct hep_generic) + s->len + iplen + sizeof(hep_chunk_t); #if 0 /* auth key */ if(profile_transport[idx].capt_password != NULL) { tlen += sizeof(hep_chunk_t); /* Auth key */ authkey_chunk.vendor_id = htons(0x0000); authkey_chunk.type_id = htons(0x000e); authkey_chunk.length = htons(sizeof(authkey_chunk) + strlen(profile_transport[idx].capt_password)); tlen += strlen(profile_transport[idx].capt_password); } #endif /* correlation key */ //if(rcinfo->correlation_id.s && rcinfo->correlation_id.len > 0) { tlen += sizeof(hep_chunk_t); /* Correlation key */ correlation_chunk.vendor_id = htons(0x0000); correlation_chunk.type_id = htons(0x0011); correlation_chunk.length = htons(sizeof(correlation_chunk) + id->len); tlen += id->len; //} /* total */ hg->header.length = htons(tlen); buffer = (void*)malloc(tlen); if (buffer==0){ ilog(LOG_ERR, "ERROR: out of memory"); free(hg); return -1; } memcpy((void*) buffer, hg, sizeof(struct hep_generic)); buflen = sizeof(struct hep_generic); /* IPv4 */ if(hg->ip_family.data == AF_INET) { /* SRC IP */ memcpy((void*) buffer+buflen, &src_ip4, sizeof(struct hep_chunk_ip4)); buflen += sizeof(struct hep_chunk_ip4); memcpy((void*) buffer+buflen, &dst_ip4, sizeof(struct hep_chunk_ip4)); buflen += sizeof(struct hep_chunk_ip4); } /* IPv6 */ else if(hg->ip_family.data == AF_INET6) { /* SRC IPv6 */ memcpy((void*) buffer+buflen, &src_ip4, sizeof(struct hep_chunk_ip6)); buflen += sizeof(struct hep_chunk_ip6); memcpy((void*) buffer+buflen, &dst_ip6, sizeof(struct hep_chunk_ip6)); buflen += sizeof(struct hep_chunk_ip6); } #if 0 /* AUTH KEY CHUNK */ if(profile_transport[idx].capt_password != NULL) { memcpy((void*) buffer+buflen, &authkey_chunk, sizeof(struct hep_chunk)); buflen += sizeof(struct hep_chunk); /* Now copying payload self */ memcpy((void*) buffer+buflen, profile_transport[idx].capt_password, strlen(profile_transport[idx].capt_password)); buflen+=strlen(profile_transport[idx].capt_password); } #endif /* Correlation KEY CHUNK */ //if(rcinfo->correlation_id.s && rcinfo->correlation_id.len > 0) { memcpy((void*) buffer+buflen, &correlation_chunk, sizeof(struct hep_chunk)); buflen += sizeof(struct hep_chunk); /* Now copying payload self */ memcpy((void*) buffer+buflen, id->s, id->len); buflen+= id->len; //} /* PAYLOAD CHUNK */ memcpy((void*) buffer+buflen, &payload_chunk, sizeof(struct hep_chunk)); buflen += sizeof(struct hep_chunk); /* Now copying payload self */ memcpy((void*) buffer+buflen, s->str, s->len); buflen+=s->len; #if 0 /* make sleep after 100 errors */ if(errors > 50) { LERR( "HEP server is down... retrying after sleep..."); if(!profile_transport[idx].usessl) { sleep(2); if(init_hepsocket_blocking(idx)) { profile_transport[idx].initfails++; } errors=0; } #ifdef USE_SSL else { sleep(2); if(initSSL(idx)) profile_transport[idx].initfails++; errors=0; } #endif /* USE SSL */ } /* send this packet out of our socket */ if(send_data(buffer, buflen, idx)) { errors++; stats.errors_total++; } #endif g_string_truncate(s, 0); g_string_append_len(s, buffer, buflen); /* FREE */ if(buffer) free(buffer); if(hg) free(hg); return 0; }
int main(int argc,char *argv[]){ codebook b; static_codebook c; double *quantlist; long *hits; int entries=-1,dim=-1,quantvals=-1,addmul=-1,sequencep=0; FILE *in=NULL; char *line,*name; long i,j; memset(&b,0,sizeof(b)); memset(&c,0,sizeof(c)); if(argv[1]==NULL){ fprintf(stderr,"Need a lattice description file on the command line.\n"); exit(1); } { char *ptr; char *filename=_ogg_calloc(strlen(argv[1])+4,1); strcpy(filename,argv[1]); in=fopen(filename,"r"); if(!in){ fprintf(stderr,"Could not open input file %s\n",filename); exit(1); } ptr=strrchr(filename,'.'); if(ptr){ *ptr='\0'; name=strdup(filename); }else{ name=strdup(filename); } } /* read the description */ line=get_line(in); if(sscanf(line,"%d %d %d %d",&quantvals,&dim,&addmul,&sequencep)!=4){ if(sscanf(line,"%d %d %d",&quantvals,&dim,&addmul)!=3){ fprintf(stderr,"Syntax error reading description file (line 1)\n"); exit(1); } } entries=pow(quantvals,dim); c.dim=dim; c.entries=entries; c.lengthlist=_ogg_malloc(entries*sizeof(long)); c.maptype=1; c.q_sequencep=sequencep; c.quantlist=_ogg_calloc(quantvals,sizeof(long)); quantlist=_ogg_malloc(sizeof(double)*c.dim*c.entries); hits=_ogg_malloc(c.entries*sizeof(long)); for(j=0;j<entries;j++)hits[j]=1; for(j=0;j<entries;j++)c.lengthlist[j]=1; reset_next_value(); line=setup_line(in); for(j=0;j<quantvals;j++){ char *temp; if(!line || sscanf(line,"%lf",quantlist+j)!=1){ fprintf(stderr,"Ran out of data on line 2 of description file\n"); exit(1); } temp=strchr(line,','); if(!temp)temp=strchr(line,' '); if(temp)temp++; line=temp; } /* gen a real quant list from the more easily human-grokked input */ { double min=quantlist[0]; double mindel=-1; int fac=1; for(j=1;j<quantvals;j++)if(quantlist[j]<min)min=quantlist[j]; for(j=0;j<quantvals;j++) for(i=j+1;i<quantvals;i++) if(mindel==-1 || fabs(quantlist[j]-quantlist[i])<mindel) mindel=fabs(quantlist[j]-quantlist[i]); j=0; while(j<quantvals){ for(j=0;j<quantvals;j++){ double test=fac*(quantlist[j]-min)/mindel; if( fabs(rint(test)-test)>.00001f) break; } if(fac>100)break; if(j<quantvals)fac++; } mindel/=fac; fprintf(stderr,"min=%g mindel=%g\n",min,mindel); c.q_min=_float32_pack(min); c.q_delta=_float32_pack(mindel); c.q_quant=0; min=_float32_unpack(c.q_min); mindel=_float32_unpack(c.q_delta); for(j=0;j<quantvals;j++){ c.quantlist[j]=rint((quantlist[j]-min)/mindel); if(ilog(c.quantlist[j])>c.q_quant)c.q_quant=ilog(c.quantlist[j]); } } /* build the [default] codeword lengths */ memset(c.lengthlist,0,sizeof(long)*entries); for(i=0;i<entries;i++)hits[i]=1; build_tree_from_lengths(entries,hits,c.lengthlist); /* save the book in C header form */ write_codebook(stdout,name,&c); fprintf(stderr,"\r " "\nDone.\n"); exit(0); }
int main(int argc, char *argv[]) { #ifndef _WIN32 if (geteuid() == 0) { fprintf(stderr, "Running IRC services is root is not recommended."); return 1; } setup_corefile(); #endif memset(&ServicesInfo, 0, sizeof(ServicesInfo)); memset(&ServicesState, 0, sizeof(ServicesState)); ServicesState.configfile = CPATH; ServicesState.logfile = LPATH; ServicesState.pidfile = PPATH; ServicesState.fully_connected = 0; parseargs(&argc, &argv, myopts); if(ServicesState.printversion) { printf("oftc-ircservices: version: %s\n", VERSION); exit(EXIT_SUCCESS); } if(chdir(DPATH)) { perror("chdir"); exit(EXIT_FAILURE); } #ifndef _WIN32 if(!ServicesState.foreground) make_daemon(); else print_startup(getpid()); #endif setup_signals(); memset(&me, 0, sizeof(me)); libio_init(!ServicesState.foreground); init_events(); iorecv_cb = register_callback("iorecv", iorecv_default); connected_cb = register_callback("server connected", server_connected); iosend_cb = register_callback("iosend", iosend_default); OpenSSL_add_all_digests(); init_interface(); check_pidfile(ServicesState.pidfile); init_log(ServicesState.logfile); #ifdef HAVE_RUBY init_ruby(); signal(SIGSEGV, SIG_DFL); #endif init_channel(); init_conf(); init_client(); init_parser(); init_channel_modes(); init_mqueue(); init_tor(); me.from = me.servptr = &me; SetServer(&me); SetMe(&me); dlinkAdd(&me, &me.node, &global_client_list); read_services_conf(TRUE); init_db(); init_uid(); #ifdef HAVE_PYTHON init_python(); #endif init_kill(); write_pidfile(ServicesState.pidfile); ilog(L_NOTICE, "Services Ready"); db_load_driver(); #ifdef USE_SHARED_MODULES if(chdir(MODPATH)) { ilog(L_ERROR, "Could not load core modules from %s: %s", MODPATH, strerror(errno)); exit(EXIT_FAILURE); } /* Go back to DPATH after checking to see if we can chdir to MODPATH */ chdir(DPATH); #else load_all_modules(1); #endif boot_modules(1); connect_server(); for(;;) { while (eventNextTime() <= CurrentTime) eventRun(); execute_callback(do_event_cb); if(events_loop() == -1) { ilog(L_CRIT, "libevent returned error %d", errno); services_die("Libevent returned some sort of error", NO); break; } comm_select(); send_queued_all(); if(dorehash) { ilog(L_INFO, "Got SIGHUP, reloading configuration"); read_services_conf(NO); dorehash = 0; } } return 0; }
/* * Check_pings_list() * * inputs - pointer to list to check * output - NONE * side effects - */ static void check_pings_list(dlink_list *list) { char scratch[32]; /* way too generous but... */ struct Client *client_p; /* current local client_p being examined */ int ping = 0; /* ping time value from client */ dlink_node *ptr, *next_ptr; for (ptr = list->head; ptr; ptr = next_ptr) { next_ptr = ptr->next; client_p = ptr->data; /* ** Note: No need to notify opers here. It's ** already done when "FLAGS_DEADSOCKET" is set. */ if (client_p->flags & FLAGS_DEADSOCKET) { /* Ignore it, its been exited already */ continue; } if (IsPerson(client_p)) { if(!IsExemptKline(client_p) && GlobalSetOptions.idletime && !IsOper(client_p) && !IsIdlelined(client_p) && ((CurrentTime - client_p->user->last) > GlobalSetOptions.idletime)) { struct ConfItem *aconf; aconf = make_conf(); aconf->status = CONF_KILL; DupString(aconf->host, client_p->host); DupString(aconf->passwd, "idle exceeder"); DupString(aconf->name, client_p->username); aconf->port = 0; aconf->hold = CurrentTime + 60; add_temp_kline(aconf); sendto_realops_flags(FLAGS_ALL, L_ALL, "Idle time limit exceeded for %s - temp k-lining", get_client_name(client_p, HIDE_IP)); (void)exit_client(client_p, client_p, &me, aconf->passwd); continue; } } if (!IsRegistered(client_p)) ping = CONNECTTIMEOUT; else ping = get_client_ping(client_p); if (ping < (CurrentTime - client_p->lasttime)) { /* * If the client/server hasnt talked to us in 2*ping seconds * and it has a ping time, then close its connection. */ if (((CurrentTime - client_p->lasttime) >= (2 * ping) && (client_p->flags & FLAGS_PINGSENT))) { if (IsServer(client_p) || IsConnecting(client_p) || IsHandshake(client_p)) { sendto_realops_flags(FLAGS_ALL, L_ADMIN, "No response from %s, closing link", get_client_name(client_p, HIDE_IP)); sendto_realops_flags(FLAGS_ALL, L_OPER, "No response from %s, closing link", get_client_name(client_p, MASK_IP)); ilog(L_NOTICE, "No response from %s, closing link", get_client_name(client_p, HIDE_IP)); } (void)ircsprintf(scratch, "Ping timeout: %d seconds", (int)(CurrentTime - client_p->lasttime)); (void)exit_client(client_p, client_p, &me, scratch); continue; } else if ((client_p->flags & FLAGS_PINGSENT) == 0) { /* * if we havent PINGed the connection and we havent * heard from it in a while, PING it to make sure * it is still alive. */ client_p->flags |= FLAGS_PINGSENT; /* not nice but does the job */ client_p->lasttime = CurrentTime - ping; sendto_one(client_p, "PING :%s", me.name); } } /* ping_timeout: */ } }
/* * m_challenge - generate RSA challenge for wouldbe oper * parv[0] = sender prefix * parv[1] = operator to challenge for, or +response * */ static void m_challenge(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) { char *challenge = NULL; struct ConfItem *conf = NULL; struct AccessItem *aconf = NULL; /* if theyre an oper, reprint oper motd and ignore */ if (IsOper(source_p)) { sendto_one(source_p, form_str(RPL_YOUREOPER), me.name, parv[0]); send_message_file(source_p, &ConfigFileEntry.opermotd); return; } if (*parv[1] == '+') { /* Ignore it if we aren't expecting this... -A1kmm */ if (source_p->localClient->response == NULL) return; if (irccmp(source_p->localClient->response, ++parv[1])) { sendto_one(source_p, form_str(ERR_PASSWDMISMATCH), me.name, source_p->name); failed_challenge_notice(source_p, source_p->localClient->auth_oper, "challenge failed"); return; } conf = find_exact_name_conf(OPER_TYPE, source_p->localClient->auth_oper, source_p->username, source_p->host); if (conf == NULL) conf = find_exact_name_conf(OPER_TYPE, source_p->localClient->auth_oper, source_p->username, source_p->sockhost); if (conf == NULL) { sendto_one (source_p, form_str(ERR_NOOPERHOST), me.name, parv[0]); log_oper_action(LOG_FAILED_OPER_TYPE, source_p, "%s\n", source_p->localClient->auth_oper); return; } if (attach_conf(source_p, conf) != 0) { sendto_one(source_p,":%s NOTICE %s :Can't attach conf!", me.name, source_p->name); failed_challenge_notice(source_p, conf->name, "can't attach conf!"); log_oper_action(LOG_FAILED_OPER_TYPE, source_p, "%s\n", source_p->localClient->auth_oper); return; } oper_up(source_p); ilog(L_TRACE, "OPER %s by %s!%s@%s", source_p->localClient->auth_oper, source_p->name, source_p->username, source_p->host); log_oper_action(LOG_OPER_TYPE, source_p, "%s\n", source_p->localClient->auth_oper); MyFree(source_p->localClient->response); MyFree(source_p->localClient->auth_oper); source_p->localClient->response = NULL; source_p->localClient->auth_oper = NULL; return; } MyFree(source_p->localClient->response); MyFree(source_p->localClient->auth_oper); source_p->localClient->response = NULL; source_p->localClient->auth_oper = NULL; if ((conf = find_conf_exact(OPER_TYPE, parv[1], source_p->username, source_p->host )) != NULL) aconf = map_to_conf(conf); else if ((conf = find_conf_exact(OPER_TYPE, parv[1], source_p->username, source_p->sockhost)) != NULL) aconf = map_to_conf(conf); if (aconf == NULL) { sendto_one (source_p, form_str(ERR_NOOPERHOST), me.name, parv[0]); conf = find_exact_name_conf(OPER_TYPE, parv[1], NULL, NULL); failed_challenge_notice(source_p, parv[1], (conf != NULL) ? "host mismatch" : "no oper {} block"); log_oper_action(LOG_FAILED_OPER_TYPE, source_p, "%s\n", parv[1]); return; } if (aconf->rsa_public_key == NULL) { sendto_one (source_p, ":%s NOTICE %s :I'm sorry, PK authentication " "is not enabled for your oper{} block.", me.name, parv[0]); return; } if (!generate_challenge(&challenge, &(source_p->localClient->response), aconf->rsa_public_key)) sendto_one(source_p, form_str(RPL_RSACHALLENGE), me.name, parv[0], challenge); DupString(source_p->localClient->auth_oper, conf->name); MyFree(challenge); }
/* ** m_okick ** parv[1] = channel ** parv[2] = client to kick ** parv[3] = kick comment */ static int mo_okick(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *who; struct Client *target_p; struct Channel *chptr; struct membership *msptr; int chasing = 0; char *comment; char *name; char *p = NULL; char *user; char text[10]; static char buf[BUFSIZE]; if(*parv[2] == '\0') { sendto_one(source_p, form_str(ERR_NEEDMOREPARAMS), me.name, source_p->name, "KICK"); return 0; } if(MyClient(source_p) && !IsFloodDone(source_p)) flood_endgrace(source_p); comment = (EmptyString(LOCAL_COPY(parv[3]))) ? LOCAL_COPY(parv[2]) : LOCAL_COPY(parv[3]); if(strlen(comment) > (size_t) TOPICLEN) comment[TOPICLEN] = '\0'; *buf = '\0'; if((p = strchr(parv[1], ','))) *p = '\0'; name = LOCAL_COPY(parv[1]); chptr = find_channel(name); if(!chptr) { sendto_one_numeric(source_p, ERR_NOSUCHCHANNEL, form_str(ERR_NOSUCHCHANNEL), name); return 0; } if((p = strchr(parv[2], ','))) *p = '\0'; user = LOCAL_COPY(parv[2]); // strtoken(&p2, parv[2], ","); if(!(who = find_chasing(source_p, user, &chasing))) { return 0; } if((target_p = find_client(user)) == NULL) { sendto_one(source_p, form_str(ERR_NOSUCHNICK), me.name, source_p->name, user); return 0; } if((msptr = find_channel_membership(chptr, target_p)) == NULL) { sendto_one(source_p, form_str(ERR_USERNOTINCHANNEL), me.name, source_p->name, parv[1], parv[2]); return 0; } sendto_realops_snomask(SNO_GENERAL, L_ALL, "OKICK called for %s %s by %s!%s@%s", chptr->chname, target_p->name, source_p->name, source_p->username, source_p->host); ilog(L_MAIN, "OKICK called for %s %s by %s", chptr->chname, target_p->name, get_oper_name(source_p)); sendto_channel_local(ALL_MEMBERS, chptr, ":%s KICK %s %s :%s", me.name, chptr->chname, who->name, comment); sendto_server(&me, chptr, CAP_TS6, NOCAPS, ":%s KICK %s %s :%s", me.id, chptr->chname, who->id, comment); remove_user_from_channel(msptr); rb_snprintf(text, sizeof(text), "K%s", who->id); /* we don't need to track NOREJOIN stuff unless it's our client being kicked */ if(MyClient(who) && chptr->mode.mode & MODE_NOREJOIN) channel_metadata_time_add(chptr, text, rb_current_time(), "KICKNOREJOIN"); return 0; }
void read_loop() { const int BUFFER_SIZE = 16; const int LEFTOVER = BUFFER_SIZE - sizeof(message_header); try { message m; while( !read_loop_complete.canceled() ) { char tmp[BUFFER_SIZE]; ilog( "read.." ); sock->read( tmp, BUFFER_SIZE ); ilog( "." ); memcpy( (char*)&m, tmp, sizeof(message_header) ); m.data.resize( m.size + 16 ); //give extra 16 bytes to allow for padding added in send call memcpy( (char*)m.data.data(), tmp + sizeof(message_header), LEFTOVER ); sock->read( m.data.data() + LEFTOVER, 16*((m.size -LEFTOVER + 15)/16) ); try { // message handling errors are warnings... con_del->on_connection_message( self, m ); } catch ( fc::canceled_exception& e ) { wlog(".");throw; } catch ( fc::eof_exception& e ) { wlog(".");throw; } catch ( fc::exception& e ) { wlog( "disconnected ${er}", ("er", e.to_detail_string() ) ); return; // TODO: log and potentiall disconnect... for now just warn. } catch( ... ) { wlog("...????" ); return; } } } catch ( const fc::canceled_exception& e ) { if( con_del ) { con_del->on_connection_disconnected( self ); } else { wlog( "disconnected ${e}", ("e", e.to_detail_string() ) ); } wlog( "exit read loop" ); return; } catch ( const fc::eof_exception& e ) { if( con_del ) { ilog( "."); fc::async( [=](){con_del->on_connection_disconnected( self );}, "on_connection_disconnected" ); ilog( "."); } else { wlog( "disconnected ${e}", ("e", e.to_detail_string() ) ); } } catch ( fc::exception& er ) { wlog( ".." ); if( con_del ) { elog( "disconnected ${er}", ("er", er.to_detail_string() ) ); //con_del->on_connection_disconnected( self ); fc::async( [=](){con_del->on_connection_disconnected( self );}, "exception on_connection_disconnected" ); } else { elog( "disconnected ${e}", ("e", er.to_detail_string() ) ); } FC_RETHROW_EXCEPTION( er, warn, "disconnected ${e}", ("e", er.to_detail_string() ) ); } catch ( ... ) { wlog( "unhandled??" ); // TODO: call con_del->???? FC_THROW_EXCEPTION( unhandled_exception, "disconnected: {e}", ("e", fc::except_str() ) ); } }
/* parse() * * given a raw buffer, parses it and generates parv, parc and sender */ void parse(struct Client *client_p, char *pbuffer, char *bufend) { struct Client *from = client_p; char *ch; char *s; char *end; int i = 1; char *numeric = 0; struct Message *mptr; s_assert(MyConnect(client_p)); if(IsAnyDead(client_p)) return; for(ch = pbuffer; *ch == ' '; ch++) /* skip spaces */ /* null statement */ ; if(from->name != NULL) para[0] = LOCAL_COPY(from->name); else para[0] = NULL; if(*ch == ':') { ch++; /* point sender to the sender param */ sender = ch; if((s = strchr(ch, ' '))) { *s = '\0'; s++; ch = s; } if(*sender && IsServer(client_p)) { from = find_client(sender); /* didnt find any matching client, issue a kill */ if(from == NULL) { ServerStats.is_unpf++; remove_unknown(client_p, sender, pbuffer); return; } para[0] = LOCAL_COPY(from->name); /* fake direction, hmm. */ if(from->from != client_p) { ServerStats.is_wrdi++; cancel_clients(client_p, from); return; } } while(*ch == ' ') ch++; } if(*ch == '\0') { ServerStats.is_empt++; return; } /* at this point there must be some sort of command parameter */ /* * Extract the command code from the packet. Point s to the end * of the command code and calculate the length using pointer * arithmetic. Note: only need length for numerics and *all* * numerics must have parameters and thus a space after the command * code. -avalon */ /* EOB is 3 chars long but is not a numeric */ if(*(ch + 3) == ' ' && /* ok, lets see if its a possible numeric.. */ IsDigit(*ch) && IsDigit(*(ch + 1)) && IsDigit(*(ch + 2))) { mptr = NULL; numeric = ch; ServerStats.is_num++; s = ch + 3; /* I know this is ' ' from above if */ *s++ = '\0'; /* blow away the ' ', and point s to next part */ } else { int ii = 0; if((s = strchr(ch, ' '))) *s++ = '\0'; mptr = hash_parse(ch); /* no command or its encap only, error */ if(!mptr || !mptr->cmd) { /* * Note: Give error message *only* to recognized * persons. It's a nightmare situation to have * two programs sending "Unknown command"'s or * equivalent to each other at full blast.... * If it has got to person state, it at least * seems to be well behaving. Perhaps this message * should never be generated, though... --msa * Hm, when is the buffer empty -- if a command * code has been found ?? -Armin */ if(pbuffer[0] != '\0') { if(IsClient(from)) sendto_one(from, form_str(ERR_UNKNOWNCOMMAND), me.name, from->name, ch); } ServerStats.is_unco++; return; } ii = bufend - ((s) ? s : ch); mptr->bytes += ii; } end = bufend - 1; /* XXX this should be done before parse() is called */ if(*end == '\n') *end-- = '\0'; if(*end == '\r') *end = '\0'; if(s != NULL) i = string_to_array(s, para); if(mptr == NULL) { do_numeric(numeric, client_p, from, i, para); return; } if(handle_command(mptr, client_p, from, i, /* XXX discards const!!! */ (const char **)para) < -1) { char *p; for(p = pbuffer; p <= end; p += 8) { /* HACK HACK */ /* Its expected this nasty code can be removed * or rewritten later if still needed. */ if((unsigned long)(p + 8) > (unsigned long)end) { for(; p <= end; p++) { ilog(L_MAIN, "%02x |%c", p[0], p[0]); } } else ilog(L_MAIN, "%02x %02x %02x %02x %02x %02x %02x %02x |%c%c%c%c%c%c%c%c", p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7], p[0], p[1], p[2], p[3], p[4], p[5], p[6], p[7]); } } }
/* * handle_command * * inputs - pointer to message block * - pointer to client * - pointer to client message is from * - count of number of args * - pointer to argv[] array * output - -1 if error from server * side effects - */ static int handle_command(struct Message *mptr, struct Client *client_p, struct Client *from, int i, const char **hpara) { struct MessageEntry ehandler; MessageHandler handler = 0; static time_t last_warning; if(IsAnyDead(client_p)) return -1; if(IsServer(client_p)) mptr->rcount++; mptr->count++; /* New patch to avoid server flooding from unregistered connects - Pie-Man 07/27/2000 */ if(!IsRegistered(client_p)) { /* if its from a possible server connection * ignore it.. more than likely its a header thats sneaked through */ if(IsAnyServer(client_p) && !(mptr->flags & MFLG_UNREG)) return (1); } ehandler = mptr->handlers[from->handler]; handler = ehandler.handler; /* check right amount of params is passed... --is */ if(i < ehandler.min_para || (ehandler.min_para && EmptyString(hpara[ehandler.min_para - 1]))) { if(!IsServer(client_p)) { sendto_one(client_p, form_str(ERR_NEEDMOREPARAMS), me.name, EmptyString(client_p->name) ? "*" : client_p->name, mptr->cmd); if(MyClient(client_p)) return (1); else return (-1); } sendto_realops_flags(UMODE_ALL, L_ALL, "Dropping server %s due to (invalid) command '%s'" " with only %d arguments (expecting %d).", client_p->name, mptr->cmd, i, ehandler.min_para); ilog(L_SERVER, "Insufficient parameters (%d) for command '%s' from %s.", i, mptr->cmd, client_p->name); exit_client(client_p, client_p, client_p, "Not enough arguments to server command."); return (-1); } (*handler) (client_p, from, i, hpara); if(!IsAnyDead(client_p) && IsCork(client_p) && !IsCapable(client_p, CAP_ZIP)) { if(last_warning + 300 <= rb_time()) { sendto_realops_flags(UMODE_DEBUG, L_ALL, "Bug: client %s was left corked after command %s", client_p->name, mptr->cmd); last_warning = rb_time(); } client_p->localClient->cork_count = 0; send_pop_queue(client_p); } return (1); }
void upnp_service::map_port( uint16_t local_port ) { std::string port = fc::variant(local_port).as_string(); my->map_port_complete = my->upnp_thread.async( [=]() { const char * multicastif = 0; const char * minissdpdpath = 0; struct UPNPDev * devlist = 0; char lanaddr[64]; /* miniupnpc 1.6 */ int error = 0; devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error); struct UPNPUrls urls; memset( &urls, 0, sizeof(urls) ); struct IGDdatas data; memset( &data, 0, sizeof(data) ); int r; r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr)); bool port_mapping_added = false; if (r == 1) { if (true) // TODO config this ? fDiscover) { char externalIPAddress[40]; r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress); if(r != UPNPCOMMAND_SUCCESS) printf("UPnP: GetExternalIPAddress() returned %d\n", r); else { if(externalIPAddress[0]) { printf("UPnP: ExternalIPAddress = %s\n", externalIPAddress); my->external_ip = fc::ip::address( std::string(externalIPAddress) ); // AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP); } else printf("UPnP: GetExternalIPAddress failed.\n"); } } std::string strDesc = "BitShares 0.0"; // TODO + FormatFullVersion(); // try { while(!my->done) // TODO provide way to exit cleanly { /* miniupnpc 1.6 */ r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype, port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0"); port_mapping_added = true; if(r!=UPNPCOMMAND_SUCCESS) printf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n", port.c_str(), port.c_str(), lanaddr, r, strupnperror(r)); else printf("UPnP Port Mapping successful.\n");; fc::usleep( fc::seconds(60*20) ); // Refresh every 20 minutes } } // catch (boost::thread_interrupted) { if( port_mapping_added ) { r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0); ilog("UPNP_DeletePortMapping() returned : ${r}", ("r",r)); freeUPNPDevlist(devlist); devlist = 0; FreeUPNPUrls(&urls); } // throw; } } else { printf("No valid UPnP IGDs found\n"); freeUPNPDevlist(devlist); devlist = 0; if (r != 0) { FreeUPNPUrls(&urls); } } }); }
static void control_udp_incoming(struct obj *obj, str *buf, struct sockaddr_in6 *sin, char *addr) { struct control_udp *u = (void *) obj; int ret; int ovec[100]; char **out; struct msghdr mh; struct iovec iov[10]; str cookie, *reply; ret = pcre_exec(u->parse_re, u->parse_ree, buf->s, buf->len, 0, 0, ovec, G_N_ELEMENTS(ovec)); if (ret <= 0) { ret = pcre_exec(u->fallback_re, NULL, buf->s, buf->len, 0, 0, ovec, G_N_ELEMENTS(ovec)); if (ret <= 0) { ilog(LOG_WARNING, "Unable to parse command line from udp:%s: %.*s", addr, STR_FMT(buf)); return; } ilog(LOG_WARNING, "Failed to properly parse UDP command line '%.*s' from %s, using fallback RE", STR_FMT(buf), addr); pcre_get_substring_list(buf->s, ovec, ret, (const char ***) &out); ZERO(mh); mh.msg_name = sin; mh.msg_namelen = sizeof(*sin); mh.msg_iov = iov; iov[0].iov_base = (void *) out[RE_UDP_COOKIE]; iov[0].iov_len = strlen(out[RE_UDP_COOKIE]); if (out[RE_UDP_UL_CMD] && (chrtoupper(out[RE_UDP_UL_CMD][0]) == 'U' || chrtoupper(out[RE_UDP_UL_CMD][0]) == 'L')) { iov[1].iov_base = (void *) out[4]; iov[1].iov_len = strlen(out[4]); iov[2].iov_base = (void *) out[3]; iov[2].iov_len = strlen(out[3]); iov[3].iov_base = "\n"; iov[3].iov_len = 1; mh.msg_iovlen = 4; } else { iov[1].iov_base = " E8\n"; iov[1].iov_len = 4; mh.msg_iovlen = 2; } sendmsg(u->udp_listener.fd, &mh, 0); pcre_free(out); return; } ilog(LOG_INFO, "Got valid command from udp:%s: %.*s", addr, STR_FMT(buf)); pcre_get_substring_list(buf->s, ovec, ret, (const char ***) &out); str_init(&cookie, (void *) out[RE_UDP_COOKIE]); reply = cookie_cache_lookup(&u->cookie_cache, &cookie); if (reply) { ilog(LOG_INFO, "Detected command from udp:%s as a duplicate", addr); sendto(u->udp_listener.fd, reply->s, reply->len, 0, (struct sockaddr *) sin, sizeof(*sin)); free(reply); goto out; } if (chrtoupper(out[RE_UDP_UL_CMD][0]) == 'U') reply = call_update_udp(out, u->callmaster); else if (chrtoupper(out[RE_UDP_UL_CMD][0]) == 'L') reply = call_lookup_udp(out, u->callmaster); else if (chrtoupper(out[RE_UDP_DQ_CMD][0]) == 'D') reply = call_delete_udp(out, u->callmaster); else if (chrtoupper(out[RE_UDP_DQ_CMD][0]) == 'Q') reply = call_query_udp(out, u->callmaster); else if (chrtoupper(out[RE_UDP_V_CMD][0]) == 'V') { ZERO(mh); mh.msg_name = sin; mh.msg_namelen = sizeof(*sin); mh.msg_iov = iov; mh.msg_iovlen = 2; iov[0].iov_base = (void *) out[RE_UDP_COOKIE]; iov[0].iov_len = strlen(out[RE_UDP_COOKIE]); iov[1].iov_base = " "; iov[1].iov_len = 1; if (chrtoupper(out[RE_UDP_V_FLAGS][0]) == 'F') { ret = 0; if (!strcmp(out[RE_UDP_V_PARMS], "20040107")) ret = 1; else if (!strcmp(out[RE_UDP_V_PARMS], "20050322")) ret = 1; else if (!strcmp(out[RE_UDP_V_PARMS], "20060704")) ret = 1; iov[2].iov_base = ret ? "1\n" : "0\n"; iov[2].iov_len = 2; mh.msg_iovlen++; } else { iov[2].iov_base = "20040107\n"; iov[2].iov_len = 9; mh.msg_iovlen++; } sendmsg(u->udp_listener.fd, &mh, 0); } if (reply) { sendto(u->udp_listener.fd, reply->s, reply->len, 0, (struct sockaddr *) sin, sizeof(*sin)); cookie_cache_insert(&u->cookie_cache, &cookie, reply); free(reply); } else cookie_cache_remove(&u->cookie_cache, &cookie); out: pcre_free(out); log_info_clear(); }
AVFrame *resample_frame(resample_t *resample, AVFrame *frame, const format_t *to_format) { const char *err; int errcode = 0; uint64_t to_channel_layout = av_get_default_channel_layout(to_format->channels); fix_frame_channel_layout(frame); if (frame->format != to_format->format) goto resample; if (frame->sample_rate != to_format->clockrate) goto resample; if (frame->channel_layout != to_channel_layout) goto resample; return av_frame_clone(frame); resample: if (G_UNLIKELY(!resample->swresample)) { resample->swresample = swr_alloc_set_opts(NULL, to_channel_layout, to_format->format, to_format->clockrate, frame->channel_layout, frame->format, frame->sample_rate, 0, NULL); err = "failed to alloc resample context"; if (!resample->swresample) goto err; err = "failed to init resample context"; if ((errcode = swr_init(resample->swresample)) < 0) goto err; } // get a large enough buffer for resampled audio - this should be enough so we don't // have to loop int dst_samples = av_rescale_rnd(swr_get_delay(resample->swresample, to_format->clockrate) + frame->nb_samples, to_format->clockrate, frame->sample_rate, AV_ROUND_UP); AVFrame *swr_frame = av_frame_alloc(); err = "failed to alloc resampling frame"; if (!swr_frame) goto err; av_frame_copy_props(swr_frame, frame); swr_frame->format = to_format->format; swr_frame->channel_layout = to_channel_layout; swr_frame->nb_samples = dst_samples; swr_frame->sample_rate = to_format->clockrate; err = "failed to get resample buffers"; if ((errcode = av_frame_get_buffer(swr_frame, 0)) < 0) goto err; int ret_samples = swr_convert(resample->swresample, swr_frame->extended_data, dst_samples, (const uint8_t **) frame->extended_data, frame->nb_samples); err = "failed to resample audio"; if ((errcode = ret_samples) < 0) goto err; swr_frame->nb_samples = ret_samples; swr_frame->pts = av_rescale(frame->pts, to_format->clockrate, frame->sample_rate); return swr_frame; err: if (errcode) ilog(LOG_ERR, "Error resampling: %s (%s)", err, av_error(errcode)); else ilog(LOG_ERR, "Error resampling: %s", err); resample_shutdown(resample); return NULL; }
/* ** mo_ojoin ** parv[1] = channel */ static int mo_ojoin(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Channel *chptr; int move_me = 0; /* admins only */ if(!IsOperAdmin(source_p)) { sendto_one(source_p, form_str(ERR_NOPRIVS), me.name, source_p->name, "admin"); return 0; } if(*parv[1] == '@' || *parv[1] == '%' || *parv[1] == '+' || *parv[1] == '&' || *parv[1] == '~') { parv[1]++; move_me = 1; } if((chptr = find_channel(parv[1])) == NULL) { sendto_one_numeric(source_p, ERR_NOSUCHCHANNEL, form_str(ERR_NOSUCHCHANNEL), parv[1]); return 0; } if(IsMember(source_p, chptr)) { sendto_one_notice(source_p, ":Please part %s before using OJOIN", parv[1]); return 0; } if(move_me == 1) parv[1]--; sendto_wallops_flags(UMODE_WALLOP, &me, "OJOIN called for %s by %s!%s@%s", parv[1], source_p->name, source_p->username, source_p->host); ilog(L_MAIN, "OJOIN called for %s by %s", parv[1], get_oper_name(source_p)); /* only sends stuff for #channels remotely */ sendto_server(NULL, chptr, NOCAPS, NOCAPS, ":%s WALLOPS :OJOIN called for %s by %s!%s@%s", me.name, parv[1], source_p->name, source_p->username, source_p->host); if(*parv[1] == '~' && ConfigChannel.use_owner) { add_user_to_channel(chptr, source_p, CHFL_OWNER); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s SJOIN %ld %s + :~%s", me.id, (long) chptr->channelts, chptr->chname, source_p->id); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +q %s", me.name, chptr->chname, source_p->name); } else if(*parv[1] == '&' && ConfigChannel.use_admin) { add_user_to_channel(chptr, source_p, CHFL_ADMIN); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s SJOIN %ld %s + :!%s", me.id, (long) chptr->channelts, chptr->chname, source_p->id); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +a %s", me.name, chptr->chname, source_p->name); } else if(*parv[1] == '@') { add_user_to_channel(chptr, source_p, CHFL_CHANOP); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s SJOIN %ld %s + :@%s", me.id, (long) chptr->channelts, chptr->chname, source_p->id); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +o %s", me.name, chptr->chname, source_p->name); } else if(*parv[1] == '%' && ConfigChannel.use_halfop) { add_user_to_channel(chptr, source_p, CHFL_HALFOP); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s SJOIN %ld %s + :%s%s", me.id, (long) chptr->channelts, chptr->chname, "%", source_p->id); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +h %s", me.name, chptr->chname, source_p->name); } else if(*parv[1] == '+') { add_user_to_channel(chptr, source_p, CHFL_VOICE); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s SJOIN %ld %s + :+%s", me.id, (long) chptr->channelts, chptr->chname, source_p->id); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +v %s", me.name, chptr->chname, source_p->name); } else { add_user_to_channel(chptr, source_p, CHFL_PEON); sendto_server(client_p, chptr, CAP_TS6, NOCAPS, ":%s JOIN %ld %s +", source_p->id, (long) chptr->channelts, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); } /* send the topic... */ if(chptr->topic != NULL) { sendto_one(source_p, form_str(RPL_TOPIC), me.name, source_p->name, chptr->chname, chptr->topic); sendto_one(source_p, form_str(RPL_TOPICWHOTIME), me.name, source_p->name, chptr->chname, chptr->topic_info, chptr->topic_time); } source_p->localClient->last_join_time = rb_current_time(); channel_member_names(chptr, source_p, 1); return 0; }
/* * ms_nick() * * server -> server nick change * parv[0] = sender prefix * parv[1] = nickname * parv[2] = TS when nick change * * server introducing new nick * parv[0] = sender prefix * parv[1] = nickname * parv[2] = hop count * parv[3] = TS * parv[4] = umode * parv[5] = username * parv[6] = hostname * parv[7] = server * parv[8] = ircname */ static void ms_nick(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) { struct Client *target_p; char nick[NICKLEN]; time_t newts = 0; if(parc < 2 || BadPtr(parv[1])) { sendto_one(source_p, form_str(ERR_NONICKNAMEGIVEN), me.name, parv[0]); return; } /* parc == 3 on nickchange, parc == 9 on new nick */ if((IsClient(source_p) && (parc != 3)) || (IsServer(source_p) && ((parc != 9) && (parc != 10)))) { char tbuf[BUFSIZE] = { 0 }; int j; for (j = 0; j < parc; j++) { strcat(tbuf, parv[j]); strcat(tbuf, " "); } sendto_realops_flags(UMODE_ALL, L_ALL, "Dropping server %s due to (invalid) command 'NICK' " "with only %d arguments. (Buf: '%s')", client_p->name, parc, tbuf); ilog(L_CRIT, "Insufficient parameters (%d) for command 'NICK' from %s. Buf: %s", parc, client_p->name, tbuf); exit_client(client_p, client_p, client_p, "Not enough arguments to server command."); return; } /* fix the length of the nick */ strlcpy(nick, parv[1], sizeof(nick)); if ((parc == 9) || (parc == 10)) { if (check_clean_nick(client_p, source_p, nick, parv[1], parv[7])) return; } else { if (check_clean_nick(client_p, source_p, nick, parv[1], (char *)source_p->user->server)) return; } if(parc == 9 || parc == 10) { if(check_clean_user(client_p, nick, parv[5], parv[7]) || check_clean_host(client_p, nick, parv[6], parv[7])) return; /* check the length of the clients gecos */ if(strlen(parv[(parc > 9)? 9 : 8]) > REALLEN) { sendto_realops_flags(UMODE_ALL, L_ALL, "Long realname from server %s for %s", parv[7], parv[1]); parv[(parc > 9)? 9 : 8][REALLEN] = '\0'; } if(IsServer(source_p)) newts = atol(parv[3]); } else { if(!IsServer(source_p)) newts = atol(parv[2]); } /* if the nick doesnt exist, allow it and process like normal */ if(!(target_p = find_client(nick))) { nick_from_server(client_p, source_p, parc, parv, newts, nick); return; } /* we're not living in the past anymore, an unknown client is local only. */ if(IsUnknown(target_p)) { exit_client(NULL, target_p, &me, "Overridden"); nick_from_server(client_p, source_p, parc, parv, newts, nick); return; } if(target_p == source_p) { if(strcmp(target_p->name, nick)) { /* client changing case of nick */ nick_from_server(client_p, source_p, parc, parv, newts, nick); return; } else /* client not changing nicks at all */ return; } perform_nick_collides(source_p, client_p, target_p, parc, parv, newts, nick); }
/* * mo_forcepart * parv[1] = forcepart victim * parv[2] = channels to part * parv[3] = reason */ static int mo_forcepart(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *target_p; const char *user, *channels, *reason; const char default_reason[] = "Leaving"; int chasing = 0; user = parv[1]; channels = parv[2]; if(!IsOperLocalForce(source_p)) { sendto_one(source_p, form_str(ERR_NOPRIVS), me.name, source_p->name, "local_force"); return 0; } /* if target_p == NULL then let the oper know */ if((target_p = find_chasing(source_p, user, &chasing)) == NULL) { sendto_one(source_p, form_str(ERR_NOSUCHNICK), me.name, source_p->name, user); return 0; } if(EmptyString(channels)) { sendto_one(source_p, form_str(ERR_NEEDMOREPARAMS), me.name, source_p->name, "FORCEPART"); return 0; } if(EmptyString(parv[3])) reason = default_reason; else { char *s; s = LOCAL_COPY(parv[3]); if(strlen(s) > (size_t) REASONLEN) s[REASONLEN] = '\0'; reason = s; } if(!IsClient(target_p)) return 0; if(!MyClient(target_p) && (!IsOperGlobalForce(source_p))) { sendto_one_notice(source_p, ":Nick %s is not on your server and you do not have the global_force flag", target_p->name); return 0; } sendto_realops_snomask(SNO_GENERAL, L_NETWIDE, "Received FORCEPART message for %s!%s@%s. From %s (Channels: %s)", target_p->name, target_p->username, target_p->host, source_p->name, channels); ilog(L_MAIN, "FORCEPART called for %s %s by %s!%s@%s (part reason %s)", user, channels, source_p->name, source_p->username, source_p->host, reason); if(!MyClient(target_p)) { struct Client *cptr = target_p->servptr; sendto_one(cptr, ":%s ENCAP %s FORCEPART %s :%s", get_id(source_p, cptr), cptr->name, get_id(target_p, cptr), channels); return 0; } forcepart_channels(client_p, source_p, target_p, channels, reason); return 0; }
/* ** mo_ojoin ** parv[0] = sender prefix ** parv[1] = channel */ static void mo_ojoin(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) { struct Channel *chptr; int move_me = 0; /* admins only */ if (!IsOperAdmin(source_p)) { sendto_one(source_p, ":%s NOTICE %s :You have no A flag", me.name, parv[0]); return; } if (*parv[1] == '@' || *parv[1] == '+') { parv[1]++; move_me = 1; } chptr = hash_find_channel(parv[1]); if(chptr == NULL) { sendto_one(source_p, form_str(ERR_NOSUCHCHANNEL), me.name, parv[0], parv[1]); return; } if(IsMember(source_p, chptr)) { sendto_one(source_p, ":%s NOTICE %s :Please part %s before using OJOIN", me.name, source_p->name, parv[1]); return; } if (move_me == 1) parv[1]--; sendto_wallops_flags(UMODE_WALLOP, &me, "OJOIN called for [%s] by %s!%s@%s", parv[1], source_p->name, source_p->username, source_p->host); ilog(L_NOTICE, "OJOIN called for [%s] by %s!%s@%s", parv[1], source_p->name, source_p->username, source_p->host); if(*chptr->chname != '&') sendto_server(NULL, NULL, NOCAPS, NOCAPS, ":%s WALLOPS :OJOIN called for [%s] by %s!%s@%s", me.name, parv[1], source_p->name, source_p->username, source_p->host); if (*parv[1] == '@') { add_user_to_channel(chptr, source_p, CHFL_CHANOP); if(*chptr->chname != '&') sendto_server(client_p, chptr, NOCAPS, NOCAPS, ":%s SJOIN %lu %s + :@%s", me.name, chptr->channelts, chptr->chname, source_p->name); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +o %s", me.name, chptr->chname, source_p->name); } else if (*parv[1] == '+') { add_user_to_channel(chptr, source_p, CHFL_VOICE); if(*chptr->chname != '&') sendto_server(client_p, chptr, NOCAPS, NOCAPS, ":%s SJOIN %lu %s + :+%s", me.name, chptr->channelts, chptr->chname, source_p->name); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +v %s", me.name, chptr->chname, source_p->name); } else { add_user_to_channel(chptr, source_p, CHFL_PEON); if(*chptr->chname != '&') sendto_server(client_p, chptr, NOCAPS, NOCAPS, ":%s SJOIN %lu %s + :%s", me.name, chptr->channelts, chptr->chname, source_p->name); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN %s", source_p->name, source_p->username, source_p->host, chptr->chname); } /* send the topic... */ if (chptr->topic != NULL) { sendto_one(source_p, form_str(RPL_TOPIC), me.name, source_p->name, chptr->chname, chptr->topic); sendto_one(source_p, form_str(RPL_TOPICWHOTIME), me.name, source_p->name, chptr->chname, chptr->topic_info, chptr->topic_time); } source_p->localClient->last_join_time = CurrentTime; channel_member_names(chptr, source_p, 1); }
/* * m_challenge - generate RSA challenge for wouldbe oper * parv[0] = sender prefix * parv[1] = operator to challenge for, or +response * */ static void m_challenge( struct Client *client_p, struct Client *source_p, int parc, char *parv[] ) { char * challenge; dlink_node *ptr; struct ConfItem *aconf, *oconf; if(!(source_p->user) || !source_p->localClient) return; /* if theyre an oper, reprint oper motd and ignore */ if(IsOper(source_p)) { sendto_one(source_p, form_str(RPL_YOUREOPER), me.name, parv[0]); SendMessageFile(source_p, &ConfigFileEntry.opermotd); return; } if (*parv[1] == '+') { /* Ignore it if we aren't expecting this... -A1kmm */ if (!source_p->user->response) return; if (irccmp(source_p->user->response, ++parv[1])) { sendto_one(source_p, form_str(ERR_PASSWDMISMATCH), me.name, source_p->name); log_foper(source_p, source_p->user->auth_oper); if(ConfigFileEntry.failed_oper_notice) sendto_realops_flags(UMODE_ALL, L_ALL, "Failed OPER attempt by %s (%s@%s)", source_p->name, source_p->username, source_p->host); return; } if ((aconf = find_conf_by_name(source_p->user->auth_oper, CONF_OPERATOR)) == NULL) { sendto_one(source_p, form_str(ERR_NOOPERHOST), me.name, parv[0]); log_foper(source_p, source_p->user->auth_oper); if(ConfigFileEntry.failed_oper_notice) sendto_realops_flags(UMODE_ALL, L_ALL, "Failed CHALLENGE attempt - host mismatch by %s (%s@%s)", source_p->name, source_p->username, source_p->host); return; } ptr = source_p->localClient->confs.head; oconf = ptr->data; detach_conf(source_p,oconf); if(attach_conf(source_p, aconf) != 0) { sendto_one(source_p,":%s NOTICE %s :Can't attach conf!", me.name,source_p->name); sendto_realops_flags(UMODE_ALL, L_ALL, "Failed CHALLENGE attempt by %s (%s@%s) can't attach conf!", source_p->name, source_p->username, source_p->host); log_foper(source_p, source_p->user->auth_oper); attach_conf(source_p, oconf); return; } oper_up(source_p, aconf); ilog(L_TRACE, "OPER %s by %s!%s@%s", source_p->user->auth_oper, source_p->name, source_p->username, source_p->host); log_oper(source_p, source_p->user->auth_oper); MyFree(source_p->user->response); MyFree(source_p->user->auth_oper); source_p->user->response = NULL; source_p->user->auth_oper = NULL; return; } MyFree(source_p->user->response); MyFree(source_p->user->auth_oper); source_p->user->response = NULL; source_p->user->auth_oper = NULL; if (!(aconf = find_conf_exact(parv[1], source_p->username, source_p->host, CONF_OPERATOR)) && !(aconf = find_conf_exact(parv[1], source_p->username, source_p->localClient->sockhost, CONF_OPERATOR))) { sendto_one(source_p, form_str(ERR_NOOPERHOST), me.name, parv[0]); log_foper(source_p, source_p->user->auth_oper); if(ConfigFileEntry.failed_oper_notice) sendto_realops_flags(UMODE_ALL, L_ALL, "Failed CHALLENGE attempt - host mismatch by %s (%s@%s)", source_p->name, source_p->username, source_p->host); return; } if(!aconf->rsa_public_key) { sendto_one(source_p, ":%s NOTICE %s :I'm sorry, PK authentication " "is not enabled for your oper{} block.", me.name, parv[0]); return; } if(!generate_challenge(&challenge, &(source_p->user->response), aconf->rsa_public_key)) { sendto_one(source_p, form_str(RPL_RSACHALLENGE), me.name, parv[0], challenge); } DupString(source_p->user->auth_oper, aconf->name); MyFree(challenge); return; }
static int inetport(struct Listener *listener) { rb_fde_t *F; int opt = 1; const char *errstr; /* * At first, open a new socket */ F = rb_socket(GET_SS_FAMILY(&listener->addr), SOCK_STREAM, 0, "Listener socket"); #ifdef RB_IPV6 if(listener->addr.ss_family == AF_INET6) { struct sockaddr_in6 *in6 = (struct sockaddr_in6 *)&listener->addr; if(!IN6_ARE_ADDR_EQUAL(&in6->sin6_addr, &in6addr_any)) { rb_inet_ntop(AF_INET6, &in6->sin6_addr, listener->vhost, sizeof(listener->vhost)); listener->name = listener->vhost; } } else #endif { struct sockaddr_in *in = (struct sockaddr_in *)&listener->addr; if(in->sin_addr.s_addr != INADDR_ANY) { rb_inet_ntop(AF_INET, &in->sin_addr, listener->vhost, sizeof(listener->vhost)); listener->name = listener->vhost; } } if(F == NULL) { sendto_realops_snomask(SNO_GENERAL, L_ALL, "Cannot open socket for listener on port %d", get_listener_port(listener)); ilog(L_MAIN, "Cannot open socket for listener %s", get_listener_name(listener)); return 0; } else if((maxconnections - 10) < rb_get_fd(F)) /* XXX this is kinda bogus*/ { ilog_error("no more connections left for listener"); sendto_realops_snomask(SNO_GENERAL, L_ALL, "No more connections left for listener on port %d", get_listener_port(listener)); ilog(L_MAIN, "No more connections left for listener %s", get_listener_name(listener)); rb_close(F); return 0; } /* * XXX - we don't want to do all this crap for a listener * set_sock_opts(listener); */ if(setsockopt(rb_get_fd(F), SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof(opt))) { errstr = strerror(rb_get_sockerr(F)); sendto_realops_snomask(SNO_GENERAL, L_ALL, "Cannot set SO_REUSEADDR for listener on port %d: %s", get_listener_port(listener), errstr); ilog(L_MAIN, "Cannot set SO_REUSEADDR for listener %s: %s", get_listener_name(listener), errstr); rb_close(F); return 0; } /* * Bind a port to listen for new connections if port is non-null, * else assume it is already open and try get something from it. */ if(bind(rb_get_fd(F), (struct sockaddr *) &listener->addr, GET_SS_LEN(&listener->addr))) { errstr = strerror(rb_get_sockerr(F)); sendto_realops_snomask(SNO_GENERAL, L_ALL, "Cannot bind for listener on port %d: %s", get_listener_port(listener), errstr); ilog(L_MAIN, "Cannot bind for listener %s: %s", get_listener_name(listener), errstr); rb_close(F); return 0; } if(rb_listen(F, RATBOX_SOMAXCONN, listener->defer_accept)) { errstr = strerror(rb_get_sockerr(F)); sendto_realops_snomask(SNO_GENERAL, L_ALL, "Cannot listen() for listener on port %d: %s", get_listener_port(listener), errstr); ilog(L_MAIN, "Cannot listen() for listener %s: %s", get_listener_name(listener), errstr); rb_close(F); return 0; } listener->F = F; rb_accept_tcp(listener->F, accept_precallback, accept_callback, listener); return 1; }
static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){ vorbis_look_floor1 *look=(vorbis_look_floor1 *)in; vorbis_info_floor1 *info=look->vi; codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup; int i,j,k; codebook *books=ci->fullbooks; /* unpack wrapped/predicted values from stream */ if(oggpack_read(&vb->opb,1)==1){ int *fit_value=(int *)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value)); fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1)); /* partition by partition */ /* partition by partition */ for(i=0,j=2;i<info->partitions;i++){ int classv=info->partitionclass[i]; int cdim=info->class_dim[classv]; int csubbits=info->class_subs[classv]; int csub=1<<csubbits; int cval=0; /* decode the partition's first stage cascade value */ if(csubbits){ cval=vorbis_book_decode(books+info->class_book[classv],&vb->opb); if(cval==-1)goto eop; } for(k=0;k<cdim;k++){ int book=info->class_subbook[classv][cval&(csub-1)]; cval>>=csubbits; if(book>=0){ if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1) goto eop; }else{ fit_value[j+k]=0; } } j+=cdim; } /* unwrap positive values and reconsitute via linear interpolation */ for(i=2;i<look->posts;i++){ int predicted=render_point(info->postlist[look->loneighbor[i-2]], info->postlist[look->hineighbor[i-2]], fit_value[look->loneighbor[i-2]], fit_value[look->hineighbor[i-2]], info->postlist[i]); int hiroom=look->quant_q-predicted; int loroom=predicted; int room=(hiroom<loroom?hiroom:loroom)<<1; int val=fit_value[i]; if(val){ if(val>=room){ if(hiroom>loroom){ val = val-loroom; }else{ val = -1-(val-hiroom); } }else{ if(val&1){ val= -((val+1)>>1); }else{ val>>=1; } } fit_value[i]=val+predicted; fit_value[look->loneighbor[i-2]]&=0x7fff; fit_value[look->hineighbor[i-2]]&=0x7fff; }else{
void account_history_plugin_impl::update_account_histories( const signed_block& b ) { graphene::chain::database& db = database(); const vector<optional< operation_history_object > >& hist = db.get_applied_operations(); for( const optional< operation_history_object >& o_op : hist ) { // add to the operation history index const auto& oho = db.create<operation_history_object>( [&]( operation_history_object& h ) { if( o_op.valid() ) h = *o_op; } ); if( !o_op.valid() ) { ilog( "removing failed operation with ID: ${id}", ("id", oho.id) ); db.remove( oho ); continue; } const operation_history_object& op = *o_op; // get the set of accounts this operation applies to flat_set<account_id_type> impacted; vector<authority> other; operation_get_required_authorities( op.op, impacted, impacted, other ); if( op.op.which() == operation::tag< account_create_operation >::value ) impacted.insert( oho.result.get<object_id_type>() ); else graphene::app::operation_get_impacted_accounts( op.op, impacted ); for( auto& a : other ) for( auto& item : a.account_auths ) impacted.insert( item.first ); // for each operation this account applies to that is in the config link it into the history if( _tracked_accounts.size() == 0 ) { for( auto& account_id : impacted ) { // we don't do index_account_keys here anymore, because // that indexing now happens in observers' post_evaluate() // add history const auto& stats_obj = account_id(db).statistics(db); const auto& ath = db.create<account_transaction_history_object>( [&]( account_transaction_history_object& obj ) { obj.operation_id = oho.id; obj.next = stats_obj.most_recent_op; }); db.modify( stats_obj, [&]( account_statistics_object& obj ) { obj.most_recent_op = ath.id; }); } } else { for( auto account_id : _tracked_accounts ) { if( impacted.find( account_id ) != impacted.end() ) { // add history const auto& stats_obj = account_id(db).statistics(db); const auto& ath = db.create<account_transaction_history_object>( [&]( account_transaction_history_object& obj ) { obj.operation_id = oho.id; obj.next = stats_obj.most_recent_op; }); db.modify( stats_obj, [&]( account_statistics_object& obj ) { obj.most_recent_op = ath.id; }); } } } } }
/* ** exit_client - This is old "m_bye". Name changed, because this is not a ** protocol function, but a general server utility function. ** ** This function exits a client of *any* type (user, server, etc) ** from this server. Also, this generates all necessary prototol ** messages that this exit may cause. ** ** 1) If the client is a local client, then this implicitly ** exits all other clients depending on this connection (e.g. ** remote clients having 'from'-field that points to this. ** ** 2) If the client is a remote client, then only this is exited. ** ** For convenience, this function returns a suitable value for ** m_function return value: ** ** CLIENT_EXITED if (client_p == source_p) ** 0 if (client_p != source_p) */ int exit_client( struct Client* client_p, /* The local client originating the * exit or NULL, if this exit is * generated by this server for * internal reasons. * This will not get any of the * generated messages. */ struct Client* source_p, /* Client exiting */ struct Client* from, /* Client firing off this Exit, * never NULL! */ const char* comment /* Reason for the exit */ ) { char comment1[HOSTLEN + HOSTLEN + 2]; dlink_node *m; fprintf(stderr, "Exiting client: %s\n", comment); if (MyConnect(source_p)) { /* DO NOT REMOVE. exit_client can be called twice after a failed * read/write. */ if(IsClosing(source_p)) return 0; SetClosing(source_p); if (source_p->flags & FLAGS_IPHASH) remove_one_ip(&source_p->localClient->ip); delete_adns_queries(source_p->localClient->dns_query); delete_identd_queries(source_p); client_flush_input(source_p); /* This source_p could have status of one of STAT_UNKNOWN, STAT_CONNECTING * STAT_HANDSHAKE or STAT_UNKNOWN * all of which are lumped together into unknown_list * * In all above cases IsRegistered() will not be true. */ if (!IsRegistered(source_p)) { m = dlinkFind(&unknown_list,source_p); if(m != NULL) { dlinkDelete(m, &unknown_list); free_dlink_node(m); } } if (IsOper(source_p)) { m = dlinkFind(&oper_list,source_p); if(m != NULL) { dlinkDelete(m, &oper_list); free_dlink_node(m); } } if (IsClient(source_p)) { Count.local--; if(IsPerson(source_p)) /* a little extra paranoia */ { m = dlinkFind(&lclient_list,source_p); if(m != NULL) { dlinkDelete(m,&lclient_list); free_dlink_node(m); } } } /* As soon as a client is known to be a server of some sort * it has to be put on the serv_list, or SJOIN's to this new server * from the connect burst will not be seen. */ if (IsServer(source_p) || IsConnecting(source_p) || IsHandshake(source_p)) { m = dlinkFind(&serv_list,source_p); if(m != NULL) { dlinkDelete(m,&serv_list); free_dlink_node(m); unset_chcap_usage_counts(source_p); } } if (IsServer(source_p)) { Count.myserver--; if(ServerInfo.hub) remove_lazylink_flags(source_p->localClient->serverMask); else uplink = NULL; } if (IsPerson(source_p)) sendto_realops_flags(FLAGS_CCONN, L_ALL, "Client exiting: %s (%s@%s) [%s] [%s]", source_p->name, source_p->username, source_p->host, comment, source_p->localClient->sockhost); log_user_exit(source_p); if (source_p->localClient->fd >= 0) { if (client_p != NULL && source_p != client_p) sendto_one(source_p, "ERROR :Closing Link: %s %s (%s)", source_p->host, source_p->name, comment); else sendto_one(source_p, "ERROR :Closing Link: %s (%s)", source_p->host, comment); } /* ** Currently only server connections can have ** depending remote clients here, but it does no ** harm to check for all local clients. In ** future some other clients than servers might ** have remotes too... ** ** Close the Client connection first and mark it ** so that no messages are attempted to send to it. ** (The following *must* make MyConnect(source_p) == FALSE!). ** It also makes source_p->from == NULL, thus it's unnecessary ** to test whether "source_p != target_p" in the following loops. */ close_connection(source_p); } if(IsServer(source_p)) { if(ConfigServerHide.hide_servers) { /* set netsplit message to "me.name *.split" to still show * that its a split, but hide the servers splitting */ ircsprintf(comment1,"%s *.split", me.name); } else { if((source_p->serv) && (source_p->serv->up)) strcpy(comment1, source_p->serv->up); else strcpy(comment1, "<Unknown>"); strcat(comment1," "); strcat(comment1, source_p->name); } remove_dependents(client_p, source_p, from, comment, comment1); if (source_p->servptr == &me) { sendto_realops_flags(FLAGS_ALL, L_ALL, "%s was connected for %d seconds. %d/%d sendK/recvK.", source_p->name, (int)(CurrentTime - source_p->firsttime), source_p->localClient->sendK, source_p->localClient->receiveK); ilog(L_NOTICE, "%s was connected for %d seconds. %d/%d sendK/recvK.", source_p->name, CurrentTime - source_p->firsttime, source_p->localClient->sendK, source_p->localClient->receiveK); } } exit_one_client(client_p, source_p, from, comment); return client_p == source_p ? CLIENT_EXITED : 0; }
/* ** mo_forcenick ** parv[1] = forcenick victim ** parv[2] = new nickname */ static int mo_forcenick(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *target_p, *exist_p; const char *user; const char *newnick; user = parv[1]; /* You must be this tall to ride the ride */ if(!IsOperLocalForce(source_p)) { sendto_one(source_p, form_str(ERR_NOPRIVS), me.name, source_p->name, "local_force"); return 0; } /* Truncate it so clean_nick doesn't spaz out */ if(!EmptyString(parv[2])) { char *s; s = LOCAL_COPY(parv[2]); if(strlen(s) > (size_t) NICKLEN) s[NICKLEN] = '\0'; newnick = s; } else { sendto_one_numeric(source_p, ERR_NONICKNAMEGIVEN, form_str(ERR_NONICKNAMEGIVEN), me.name, source_p->name); return 0; } /* Nick has to be clean or we'll have a protocol violation... */ if(!clean_nick(newnick)) { sendto_one(source_p, form_str(ERR_ERRONEUSNICKNAME), me.name, user, newnick); return 0; } /* Find the target... */ if((target_p = find_named_person(user)) == NULL) { sendto_one(source_p, form_str(ERR_NEEDMOREPARAMS), me.name, source_p->name, "FORCENICK"); return 0; } /* If it's a server, sod it, changing its name is stupid... */ if(IsServer(target_p) || IsMe(target_p)) { sendto_one_numeric(source_p, ERR_NOSUCHNICK, form_str(ERR_NOSUCHNICK), user); return 0; } /* Do we have permission to send it globally? */ if(!MyClient(target_p) && (!IsOperGlobalForce(source_p))) { sendto_one_notice(source_p, ":Nick %s is not on your server and you do not have the global_force flag", target_p->name); return 0; } /* Check to see if the new nick exists */ if((exist_p = find_named_person(newnick)) != NULL) { /* Could just be a case shift */ if(irccmp(target_p->name, newnick)) { sendto_one(source_p, form_str(ERR_NICKNAMEINUSE), me.name, user, newnick); return 0; } /* If it's the same nick, f**k it */ else if(!strcmp(target_p->name, newnick)) return 0; } sendto_realops_snomask(SNO_GENERAL, L_NETWIDE, "Received FORCENICK message for %s!%s@%s. From %s (Newnick: %s)", target_p->name, target_p->username, target_p->orighost, source_p->name, newnick); ilog(L_MAIN, "FORCENICK called for [%s] by %s!%s@%s", target_p->name, source_p->name, source_p->username, source_p->host); sendto_one_notice(target_p, ":You have been forcenicked from %s to %s by %s", target_p->name, newnick, source_p->name); if(!MyClient(target_p)) { struct Client *cptr = target_p->servptr; sendto_one(cptr, ":%s ENCAP %s FORCENICK %s :%s", get_id(source_p, cptr), cptr->name, get_id(target_p, cptr), newnick); return 0; } change_nick(target_p, newnick); return 0; }
void runTests10 (int argc, char* argv[]) { ExpressionListPtr pL = Util::genRotations(5); ilog("rotations"); pL->print(); }
/** the genesis block requires some special treatment and initialization */ void store_genesis( const trx_block& b, const signed_transactions& deterministic_trxs, const block_evaluation_state_ptr& state ) { try { std::vector<uint160> trxs_ids; std::map<int32_t,uint64_t> delegate_votes; for( uint32_t i = 1; i <= 100; ++i ) { delegate_votes[i] = 0; } for( uint32_t cur_trx = 0 ; cur_trx < b.trxs.size(); ++cur_trx ) { store( b.trxs[cur_trx], trx_num( b.block_num, cur_trx) ); trxs_ids.push_back( b.trxs[cur_trx].id() ); if( cur_trx == 0 ) { for( uint32_t o = 0; o < b.trxs[cur_trx].outputs.size(); ++o ) { if( b.trxs[cur_trx].outputs[o].claim_func == claim_name ) { auto claim = b.trxs[cur_trx].outputs[o].as<claim_name_output>(); update_name_record( claim.name, claim ); // if( claim.delegate_id != 0 ) update_delegate( name_record( claim ) ); } } } else // cur_trx != 0 { ilog( " processing transaction ${o}", ("o",cur_trx) ); name_record rec = _delegate_records.fetch( b.trxs[cur_trx].vote ); // first transaction registers names... the rest are initial balance for( uint32_t o = 0; o < b.trxs[cur_trx].outputs.size(); ++o ) { ilog( " processing output ${o} ${data}", ("o",o)("data",b.trxs[cur_trx].outputs[o]) ); FC_ASSERT( delegate_votes.find( b.trxs[cur_trx].vote ) != delegate_votes.end() ); delegate_votes[b.trxs[cur_trx].vote] += b.trxs[cur_trx].outputs[o].amount.get_rounded_amount(); ilog( "total_shares: ${total}", ("total",b.total_shares) ); rec.votes_for += to_bips( b.trxs[cur_trx].outputs[o].amount.get_rounded_amount(), b.total_shares ); ilog( "votes for: ${v}", ("v",rec.votes_for) ); ilog( "rec: ${rc}", ("rc",rec) ); } ilog( "updating delegate..." ); update_delegate( rec ); } } elog( "total votes:\n ${e}", ("e",fc::json::to_pretty_string( delegate_votes) ) ); uint64_t sum = 0; for( auto i : delegate_votes ) { sum += i.second; } elog( "grand total: ${g}", ("g",sum) ); head_block = b; head_block_id = b.id(); blocks.store( b.block_num, b ); block_trxs.store( b.block_num, trxs_ids ); blk_id2num.store( b.id(), b.block_num ); } FC_RETHROW_EXCEPTIONS( warn, "error storing genesis block " ) } // store_genesis
/* * m_forcejoin * parv[1] = user to force * parv[2] = channel to force them into */ static int mo_forcejoin(struct Client *client_p, struct Client *source_p, int parc, const char *parv[]) { struct Client *target_p; struct Channel *chptr; int type; char mode; char sjmode; char *newch; if(!IsOperAdmin(source_p)) { sendto_one(source_p, form_str(ERR_NOPRIVS), me.name, source_p->name, "admin"); return 0; } if((hunt_server(client_p, source_p, ":%s FORCEJOIN %s %s", 1, parc, parv)) != HUNTED_ISME) return 0; /* if target_p is not existant, print message * to source_p and bail - scuzzy */ if((target_p = find_client(parv[1])) == NULL) { sendto_one(source_p, form_str(ERR_NOSUCHNICK), me.name, source_p->name, parv[1]); return 0; } if(!IsPerson(target_p)) return 0; sendto_wallops_flags(UMODE_WALLOP, &me, "FORCEJOIN called for %s %s by %s!%s@%s", parv[1], parv[2], source_p->name, source_p->username, source_p->host); ilog(L_MAIN, "FORCEJOIN called for %s %s by %s!%s@%s", parv[1], parv[2], source_p->name, source_p->username, source_p->host); sendto_server(NULL, NULL, NOCAPS, NOCAPS, ":%s WALLOPS :FORCEJOIN called for %s %s by %s!%s@%s", me.name, parv[1], parv[2], source_p->name, source_p->username, source_p->host); /* select our modes from parv[2] if they exist... (chanop) */ if(*parv[2] == '@') { type = CHFL_CHANOP; mode = 'o'; sjmode = '@'; } else if(*parv[2] == '+') { type = CHFL_VOICE; mode = 'v'; sjmode = '+'; } else { type = CHFL_PEON; mode = sjmode = '\0'; } if(mode != '\0') parv[2]++; if((chptr = find_channel(parv[2])) != NULL) { if(IsMember(target_p, chptr)) { /* debugging is fun... */ sendto_one_notice(source_p, ":*** Notice -- %s is already in %s", target_p->name, chptr->chname); return 0; } add_user_to_channel(chptr, target_p, type); sendto_server(target_p, chptr, NOCAPS, NOCAPS, ":%s SJOIN %ld %s + :%c%s", me.name, (long) chptr->channelts, chptr->chname, type ? sjmode : ' ', target_p->name); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN :%s", target_p->name, target_p->username, target_p->host, chptr->chname); if(type) sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +%c %s", me.name, chptr->chname, mode, target_p->name); if(chptr->topic != NULL) { sendto_one(target_p, form_str(RPL_TOPIC), me.name, target_p->name, chptr->chname, chptr->topic); sendto_one(target_p, form_str(RPL_TOPICWHOTIME), me.name, source_p->name, chptr->chname, chptr->topic_info, chptr->topic_time); } channel_member_names(chptr, target_p, 1); } else { newch = LOCAL_COPY(parv[2]); if(!check_channel_name(newch)) { sendto_one(source_p, form_str(ERR_BADCHANNAME), me.name, source_p->name, (unsigned char *) newch); return 0; } /* channel name must begin with & or # */ if(!IsChannelName(newch)) { sendto_one(source_p, form_str(ERR_BADCHANNAME), me.name, source_p->name, (unsigned char *) newch); return 0; } /* newch can't be longer than CHANNELLEN */ if(strlen(newch) > CHANNELLEN) { sendto_one_notice(source_p, ":Channel name is too long"); return 0; } chptr = get_or_create_channel(target_p, newch, NULL); add_user_to_channel(chptr, target_p, CHFL_CHANOP); /* send out a join, make target_p join chptr */ sendto_server(target_p, chptr, NOCAPS, NOCAPS, ":%s SJOIN %ld %s +nt :@%s", me.name, (long) chptr->channelts, chptr->chname, target_p->name); sendto_channel_local(ALL_MEMBERS, chptr, ":%s!%s@%s JOIN :%s", target_p->name, target_p->username, target_p->host, chptr->chname); chptr->mode.mode |= MODE_TOPICLIMIT; chptr->mode.mode |= MODE_NOPRIVMSGS; sendto_channel_local(ALL_MEMBERS, chptr, ":%s MODE %s +nt", me.name, chptr->chname); target_p->localClient->last_join_time = rb_current_time(); channel_member_names(chptr, target_p, 1); /* we do this to let the oper know that a channel was created, this will be * seen from the server handling the command instead of the server that * the oper is on. */ sendto_one_notice(source_p, ":*** Notice -- Creating channel %s", chptr->chname); } return 0; }
void database::init_genesis(const genesis_allocation& initial_allocation) { try { _undo_db.disable(); fc::ecc::private_key genesis_private_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("genesis"))); const key_object& genesis_key = create<key_object>( [&genesis_private_key](key_object& k) { k.key_data = public_key_type(genesis_private_key.get_public_key()); }); const account_statistics_object& genesis_statistics = create<account_statistics_object>( [&](account_statistics_object& b){ }); create<account_balance_object>( [](account_balance_object& b) { b.balance = GRAPHENE_INITIAL_SUPPLY; }); const account_object& genesis_account = create<account_object>( [&](account_object& n) { n.name = "genesis"; n.owner.add_authority(genesis_key.get_id(), 1); n.owner.weight_threshold = 1; n.active = n.owner; n.memo_key = genesis_key.id; n.statistics = genesis_statistics.id; }); vector<delegate_id_type> init_delegates; vector<witness_id_type> init_witnesses; flat_set<witness_id_type> init_witness_set; auto delegates_and_witnesses = std::max(GRAPHENE_MIN_WITNESS_COUNT, GRAPHENE_MIN_DELEGATE_COUNT); for( int i = 0; i < delegates_and_witnesses; ++i ) { const account_statistics_object& stats_obj = create<account_statistics_object>( [&](account_statistics_object&){ }); const account_object& delegate_account = create<account_object>( [&](account_object& a) { a.active = a.owner = genesis_account.owner; a.name = string("init") + fc::to_string(i); a.statistics = stats_obj.id; }); const delegate_object& init_delegate = create<delegate_object>( [&](delegate_object& d) { d.delegate_account = delegate_account.id; d.vote_id = i * 2; }); init_delegates.push_back(init_delegate.id); const witness_object& init_witness = create<witness_object>( [&](witness_object& d) { d.witness_account = delegate_account.id; d.vote_id = i * 2 + 1; secret_hash_type::encoder enc; fc::raw::pack( enc, genesis_private_key ); fc::raw::pack( enc, d.last_secret ); d.next_secret = secret_hash_type::hash(enc.result()); }); init_witnesses.push_back(init_witness.id); init_witness_set.insert(init_witness.id); } create<block_summary_object>( [&](block_summary_object& p) { }); const witness_schedule_object& wso = create<witness_schedule_object>( [&]( witness_schedule_object& _wso ) { memset( _wso.rng_seed.begin(), 0, _wso.rng_seed.size() ); witness_scheduler_rng rng( _wso.rng_seed.begin(), GRAPHENE_NEAR_SCHEDULE_CTR_IV ); _wso.scheduler = witness_scheduler(); _wso.scheduler._min_token_count = init_witnesses.size() / 2; _wso.scheduler.update( init_witness_set ); for( int i=0; i<init_witnesses.size(); i++ ) _wso.scheduler.produce_schedule( rng ); _wso.last_scheduling_block = 0; } ) ; assert( wso.id == witness_schedule_id_type() ); const global_property_object& properties = create<global_property_object>( [&](global_property_object& p) { p.active_delegates = init_delegates; for( const witness_id_type& wit : init_witnesses ) p.active_witnesses.insert( wit ); p.next_available_vote_id = delegates_and_witnesses * 2; p.chain_id = fc::digest(initial_allocation); }); (void)properties; create<dynamic_global_property_object>( [&](dynamic_global_property_object& p) { p.time = fc::time_point_sec( GRAPHENE_GENESIS_TIMESTAMP ); }); const asset_dynamic_data_object& dyn_asset = create<asset_dynamic_data_object>( [&]( asset_dynamic_data_object& a ) { a.current_supply = GRAPHENE_INITIAL_SUPPLY; }); const asset_object& core_asset = create<asset_object>( [&]( asset_object& a ) { a.symbol = GRAPHENE_SYMBOL; a.options.max_supply = GRAPHENE_INITIAL_SUPPLY; a.precision = GRAPHENE_BLOCKCHAIN_PRECISION_DIGITS; a.options.flags = 0; a.options.issuer_permissions = 0; a.issuer = genesis_account.id; a.options.core_exchange_rate.base.amount = 1; a.options.core_exchange_rate.base.asset_id = 0; a.options.core_exchange_rate.quote.amount = 1; a.options.core_exchange_rate.quote.asset_id = 0; a.dynamic_asset_data_id = dyn_asset.id; }); assert( asset_id_type(core_asset.id) == asset().asset_id ); assert( get_balance(account_id_type(), asset_id_type()) == asset(dyn_asset.current_supply) ); (void)core_asset; if( !initial_allocation.empty() ) { share_type total_allocation = 0; for( const auto& handout : initial_allocation ) total_allocation += handout.second; auto mangle_to_name = [](const fc::static_variant<public_key_type, address>& key) { string addr = string(key.which() == std::decay<decltype(key)>::type::tag<address>::value? key.get<address>() : key.get<public_key_type>()); string result = "bts"; string key_string = string(addr).substr(sizeof(GRAPHENE_ADDRESS_PREFIX)-1); for( char c : key_string ) { if( isupper(c) ) result += string("-") + char(tolower(c)); else result += c; } return result; }; fc::time_point start_time = fc::time_point::now(); for( const auto& handout : initial_allocation ) { asset amount(handout.second); amount.amount = ((fc::uint128(amount.amount.value) * GRAPHENE_INITIAL_SUPPLY)/total_allocation.value).to_uint64(); if( amount.amount == 0 ) { wlog("Skipping zero allocation to ${k}", ("k", handout.first)); continue; } signed_transaction trx; trx.operations.emplace_back(key_create_operation({asset(), genesis_account.id, handout.first})); relative_key_id_type key_id(0); authority account_authority(1, key_id, 1); account_create_operation cop; cop.name = mangle_to_name(handout.first); cop.registrar = account_id_type(1); cop.active = account_authority; cop.owner = account_authority; cop.memo_key = key_id; trx.operations.push_back(cop); trx.validate(); auto ptrx = apply_transaction(trx, ~0); trx = signed_transaction(); account_id_type account_id(ptrx.operation_results.back().get<object_id_type>()); trx.operations.emplace_back(transfer_operation({ asset(), genesis_account.id, account_id, amount, memo_data()//vector<char>() })); trx.validate(); apply_transaction(trx, ~0); } asset leftovers = get_balance(account_id_type(), asset_id_type()); if( leftovers.amount > 0 ) { modify(*get_index_type<account_balance_index>().indices().get<by_balance>().find(boost::make_tuple(account_id_type(), asset_id_type())), [](account_balance_object& b) { b.adjust_balance(-b.get_balance()); }); modify(core_asset.dynamic_asset_data_id(*this), [&leftovers](asset_dynamic_data_object& d) { d.accumulated_fees += leftovers.amount; }); } fc::microseconds duration = fc::time_point::now() - start_time; ilog("Finished allocating to ${n} accounts in ${t} milliseconds.", ("n", initial_allocation.size())("t", duration.count() / 1000)); } _undo_db.enable(); } FC_LOG_AND_RETHROW() }
void database::clear_expired_orders() { detail::with_skip_flags( *this, get_node_properties().skip_flags | skip_authority_check, [&](){ transaction_evaluation_state cancel_context(this); //Cancel expired limit orders auto& limit_index = get_index_type<limit_order_index>().indices().get<by_expiration>(); while( !limit_index.empty() && limit_index.begin()->expiration <= head_block_time() ) { limit_order_cancel_operation canceler; const limit_order_object& order = *limit_index.begin(); canceler.fee_paying_account = order.seller; canceler.order = order.id; apply_operation(cancel_context, canceler); } }); //Process expired force settlement orders auto& settlement_index = get_index_type<force_settlement_index>().indices().get<by_expiration>(); if( !settlement_index.empty() ) { asset_id_type current_asset = settlement_index.begin()->settlement_asset_id(); asset max_settlement_volume; auto next_asset = [¤t_asset, &settlement_index] { auto bound = settlement_index.upper_bound(current_asset); if( bound == settlement_index.end() ) return false; current_asset = bound->settlement_asset_id(); return true; }; // At each iteration, we either consume the current order and remove it, or we move to the next asset for( auto itr = settlement_index.lower_bound(current_asset); itr != settlement_index.end(); itr = settlement_index.lower_bound(current_asset) ) { const force_settlement_object& order = *itr; auto order_id = order.id; current_asset = order.settlement_asset_id(); const asset_object& mia_object = get(current_asset); const asset_bitasset_data_object mia = mia_object.bitasset_data(*this); // Has this order not reached its settlement date? if( order.settlement_date > head_block_time() ) { if( next_asset() ) continue; break; } // Can we still settle in this asset? if( mia.current_feed.settlement_price.is_null() ) { ilog("Canceling a force settlement in ${asset} because settlement price is null", ("asset", mia_object.symbol)); cancel_order(order); continue; } if( max_settlement_volume.asset_id != current_asset ) max_settlement_volume = mia_object.amount(mia.max_force_settlement_volume(mia_object.dynamic_data(*this).current_supply)); if( mia.force_settled_volume >= max_settlement_volume.amount ) { /* ilog("Skipping force settlement in ${asset}; settled ${settled_volume} / ${max_volume}", ("asset", mia_object.symbol)("settlement_price_null",mia.current_feed.settlement_price.is_null()) ("settled_volume", mia.force_settled_volume)("max_volume", max_settlement_volume)); */ if( next_asset() ) continue; break; } auto& pays = order.balance; auto receives = (order.balance * mia.current_feed.settlement_price); receives.amount = (fc::uint128_t(receives.amount.value) * (GRAPHENE_100_PERCENT - mia.options.force_settlement_offset_percent) / GRAPHENE_100_PERCENT).to_uint64(); assert(receives <= order.balance * mia.current_feed.settlement_price); price settlement_price = pays / receives; auto& call_index = get_index_type<call_order_index>().indices().get<by_collateral>(); asset settled = mia_object.amount(mia.force_settled_volume); // Match against the least collateralized short until the settlement is finished or we reach max settlements while( settled < max_settlement_volume && find_object(order_id) ) { auto itr = call_index.lower_bound(boost::make_tuple(price::min(mia_object.bitasset_data(*this).options.short_backing_asset, mia_object.get_id()))); // There should always be a call order, since asset exists! assert(itr != call_index.end() && itr->debt_type() == mia_object.get_id()); asset max_settlement = max_settlement_volume - settled; settled += match(*itr, order, settlement_price, max_settlement); } modify(mia, [settled](asset_bitasset_data_object& b) { b.force_settled_volume = settled.amount; }); } } }
/* * m_challenge - generate RSA challenge for wouldbe oper * parv[0] = sender prefix * parv[1] = operator to challenge for, or +response * */ static void m_challenge(struct Client *client_p, struct Client *source_p, int parc, char *parv[]) { char *challenge = NULL; struct MaskItem *conf = NULL; if (*parv[1] == '+') { /* Ignore it if we aren't expecting this... -A1kmm */ if (source_p->localClient->response == NULL) return; if (irccmp(source_p->localClient->response, ++parv[1])) { sendto_one(source_p, form_str(ERR_PASSWDMISMATCH), me.name, source_p->name); failed_challenge_notice(source_p, source_p->localClient->auth_oper, "challenge failed"); return; } conf = find_exact_name_conf(CONF_OPER, source_p, source_p->localClient->auth_oper, NULL, NULL); if (conf == NULL) { /* XXX: logging */ sendto_one (source_p, form_str(ERR_NOOPERHOST), me.name, source_p->name); return; } if (attach_conf(source_p, conf) != 0) { sendto_one(source_p,":%s NOTICE %s :Can't attach conf!", me.name, source_p->name); failed_challenge_notice(source_p, conf->name, "can't attach conf!"); return; } ++conf->count; oper_up(source_p); ilog(LOG_TYPE_OPER, "OPER %s by %s!%s@%s", source_p->localClient->auth_oper, source_p->name, source_p->username, source_p->host); MyFree(source_p->localClient->response); MyFree(source_p->localClient->auth_oper); source_p->localClient->response = NULL; source_p->localClient->auth_oper = NULL; return; } MyFree(source_p->localClient->response); MyFree(source_p->localClient->auth_oper); source_p->localClient->response = NULL; source_p->localClient->auth_oper = NULL; conf = find_exact_name_conf(CONF_OPER, source_p, parv[1], NULL, NULL); if (!conf) { sendto_one (source_p, form_str(ERR_NOOPERHOST), me.name, source_p->name); conf = find_exact_name_conf(CONF_OPER, NULL, parv[1], NULL, NULL); failed_challenge_notice(source_p, parv[1], (conf != NULL) ? "host mismatch" : "no oper {} block"); return; } if (conf->rsa_public_key == NULL) { sendto_one (source_p, ":%s NOTICE %s :I'm sorry, PK authentication " "is not enabled for your oper{} block.", me.name, source_p->name); return; } if (!generate_challenge(&challenge, &(source_p->localClient->response), conf->rsa_public_key)) sendto_one(source_p, form_str(RPL_RSACHALLENGE), me.name, source_p->name, challenge); source_p->localClient->auth_oper = xstrdup(conf->name); MyFree(challenge); }
/* return values: * 1 = ICE completed, interfaces selected * 0 = packet processed * -1 = generic error, process packet as normal * -2 = role conflict */ int ice_request(struct packet_stream *ps, struct sockaddr_in6 *src, struct in6_addr *dst, struct stun_attrs *attrs) { struct call_media *media = ps->media; struct ice_agent *ag; struct interface_address *ifa; const char *err; struct ice_candidate *cand; struct ice_candidate_pair *pair; int ret; __DBG("received ICE request from %s on %s", smart_ntop_port_buf(src), smart_ntop_buf(dst)); ag = media->ice_agent; if (!ag) return -1; ifa = get_interface_from_address(ag->local_interface, dst); err = "ICE/STUN binding request received on unknown local interface address"; if (!ifa) goto err; /* determine candidate pair */ mutex_lock(&ag->lock); cand = __cand_lookup(ag, src, ps->component); if (!cand) pair = __learned_candidate(ag, ps, src, ifa, attrs->priority); else pair = __pair_lookup(ag, cand, ifa); err = "Failed to determine ICE candidate from STUN request"; if (!pair) goto err_unlock; mutex_unlock(&ag->lock); /* determine role conflict */ if (attrs->controlling && AGENT_ISSET(ag, CONTROLLING)) { if (tie_breaker >= attrs->tiebreaker) return -2; else __role_change(ag, 0); } else if (attrs->controlled && !AGENT_ISSET(ag, CONTROLLING)) { if (tie_breaker >= attrs->tiebreaker) __role_change(ag, 1); else return -2; } if (PAIR_ISSET(pair, SUCCEEDED)) ; else __trigger_check(pair); ret = 0; if (attrs->use && !PAIR_SET(pair, NOMINATED)) { ilog(LOG_DEBUG, "ICE pair "PAIR_FORMAT" has been nominated by peer", PAIR_FMT(pair)); mutex_lock(&ag->lock); g_tree_insert(ag->nominated_pairs, pair, pair); if (PAIR_ISSET(pair, SUCCEEDED)) { PAIR_SET(pair, VALID); g_tree_insert(ag->valid_pairs, pair, pair); } if (!AGENT_ISSET(ag, CONTROLLING)) ret = __check_valid(ag); mutex_unlock(&ag->lock); } return ret; err_unlock: mutex_unlock(&ag->lock); err: ilog(LOG_NOTICE, "%s (from %s on interface %s)", err, smart_ntop_port_buf(src), smart_ntop_buf(dst)); return 0; }
virtual void handle_transaction(const graphene::net::trx_message& transaction_message) override { try { ilog("Got transaction from network"); _chain_db->push_transaction( transaction_message.trx ); } FC_CAPTURE_AND_RETHROW( (transaction_message) ) }