static void * pinger_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; int i, rx = 0, n = targ->g->npackets; fds[0].fd = targ->fd; fds[0].events = (POLLIN); static uint32_t sent; struct timespec ts, now, last_print; uint32_t count = 0, min = 1000000, av = 0; if (targ->g->nthreads > 1) { D("can only ping with 1 thread"); return NULL; } clock_gettime(CLOCK_REALTIME_PRECISE, &last_print); while (n == 0 || (int)sent < n) { struct netmap_ring *ring = NETMAP_TXRING(nifp, 0); struct netmap_slot *slot; char *p; for (i = 0; i < 1; i++) { slot = &ring->slot[ring->cur]; slot->len = targ->g->pkt_size; p = NETMAP_BUF(ring, slot->buf_idx); if (ring->avail == 0) { D("-- ouch, cannot send"); } else { pkt_copy(&targ->pkt, p, targ->g->pkt_size); clock_gettime(CLOCK_REALTIME_PRECISE, &ts); bcopy(&sent, p+42, sizeof(sent)); bcopy(&ts, p+46, sizeof(ts)); sent++; ring->cur = NETMAP_RING_NEXT(ring, ring->cur); ring->avail--; } } /* should use a parameter to decide how often to send */ if (poll(fds, 1, 3000) <= 0) { D("poll error/timeout on queue %d", targ->me); continue; } /* see what we got back */ for (i = targ->qfirst; i < targ->qlast; i++) { ring = NETMAP_RXRING(nifp, i); while (ring->avail > 0) { uint32_t seq; slot = &ring->slot[ring->cur]; p = NETMAP_BUF(ring, slot->buf_idx); clock_gettime(CLOCK_REALTIME_PRECISE, &now); bcopy(p+42, &seq, sizeof(seq)); bcopy(p+46, &ts, sizeof(ts)); ts.tv_sec = now.tv_sec - ts.tv_sec; ts.tv_nsec = now.tv_nsec - ts.tv_nsec; if (ts.tv_nsec < 0) { ts.tv_nsec += 1000000000; ts.tv_sec--; } if (0) D("seq %d/%d delta %d.%09d", seq, sent, (int)ts.tv_sec, (int)ts.tv_nsec); if (ts.tv_nsec < (int)min) min = ts.tv_nsec; count ++; av += ts.tv_nsec; ring->avail--; ring->cur = NETMAP_RING_NEXT(ring, ring->cur); rx++; } } //D("tx %d rx %d", sent, rx); //usleep(100000); ts.tv_sec = now.tv_sec - last_print.tv_sec; ts.tv_nsec = now.tv_nsec - last_print.tv_nsec; if (ts.tv_nsec < 0) { ts.tv_nsec += 1000000000; ts.tv_sec--; } if (ts.tv_sec >= 1) { D("count %d min %d av %d", count, min, av/count); count = 0; av = 0; min = 100000000; last_print = now; } } return NULL; }
PAM_EXTERN int pam_sm_setcred(pam_handle_t *pamh, int flags , int argc, const char **argv) { const char *service=NULL, *tty=NULL; const char *user=NULL; int retval; unsigned setting; /* only interested in establishing credentials */ setting = flags; if (!(setting & PAM_ESTABLISH_CRED)) { D(("ignoring call - not for establishing credentials")); return PAM_SUCCESS; /* don't fail because of this */ } /* set service name */ if (pam_get_item(pamh, PAM_SERVICE, (const void **)&service) != PAM_SUCCESS || service == NULL) { _log_err("cannot find the current service name"); return PAM_ABORT; } /* set username */ if (pam_get_user(pamh, &user, NULL) != PAM_SUCCESS || user == NULL || *user == '\0') { _log_err("cannot determine the user's name"); return PAM_USER_UNKNOWN; } /* set tty name */ if (pam_get_item(pamh, PAM_TTY, (const void **)&tty) != PAM_SUCCESS || tty == NULL) { D(("PAM_TTY not set, probing stdin")); tty = ttyname(STDIN_FILENO); if (tty == NULL) { _log_err("couldn't get the tty name"); return PAM_ABORT; } if (pam_set_item(pamh, PAM_TTY, tty) != PAM_SUCCESS) { _log_err("couldn't set tty name"); return PAM_ABORT; } } if (strncmp("/dev/",tty,5) == 0) { /* strip leading /dev/ */ tty += 5; } /* good, now we have the service name, the user and the terminal name */ D(("service=%s", service)); D(("user=%s", user)); D(("tty=%s", tty)); #ifdef WANT_PWDB /* We initialize the pwdb library and check the account */ retval = pwdb_start(); /* initialize */ if (retval == PWDB_SUCCESS) { retval = check_account(service,tty,user); /* get groups */ (void) pwdb_end(); /* tidy up */ } else { D(("failed to initialize pwdb; %s", pwdb_strerror(retval))); _log_err("unable to initialize libpwdb"); retval = PAM_ABORT; } #else /* WANT_PWDB */ retval = check_account(service,tty,user); /* get groups */ #endif /* WANT_PWDB */ return retval; }
void showvmm(void) { int i, n; if (!vmm_fetched) return; for (i = 0; i < vmm_ncpus; ++i) { struct kinfo_cputime d; uint64_t cp_total = 0; n = X_START + CPU_LABEL_W; #define D(idx, field) \ (vmm_cur[idx].field - vmm_prev[idx].field) / (u_int)naptime DRAW_ROW(n, CPU_START + i, 6, "%*u", D(i, v_timer)); DRAW_ROW(n, CPU_START + i, 8, "%*u", D(i, v_ipi)); DRAW_ROW(n, CPU_START + i, 8, "%*u", D(i, v_intr)); #define CPUD(dif, idx, field) \ do { \ dif.cp_##field = vmm_cptime_cur[idx].cp_##field - \ vmm_cptime_prev[idx].cp_##field; \ cp_total += dif.cp_##field; \ } while (0) #define CPUV(dif, field) \ (dif.cp_##field * 100.0) / cp_total CPUD(d, i, user); CPUD(d, i, idle); CPUD(d, i, intr); CPUD(d, i, nice); CPUD(d, i, sys); if (cp_total == 0) cp_total = 1; DRAW_ROW(n, CPU_START + i, 6, "%*.1f", CPUV(d, user) + CPUV(d, nice)); /* DRAW_ROW(n, CPU_START + i, 6, "%*.1f", CPUV(d, nice));*/ DRAW_ROW(n, CPU_START + i, 6, "%*.1f", CPUV(d, sys)); DRAW_ROW(n, CPU_START + i, 6, "%*.1f", CPUV(d, intr)); DRAW_ROW(n, CPU_START + i, 6, "%*.1f", CPUV(d, idle)); /* * Display token collision count and the last-colliding * token name. */ if (D(i, v_lock_colls) > 9999999) DRAW_ROW(n, CPU_START + i, 8, "%*u", 9999999); else DRAW_ROW(n, CPU_START + i, 8, "%*u", D(i, v_lock_colls)); if (D(i, v_lock_colls) == 0) { DRAW_ROW2(n, CPU_START + i, 18, "%*.*s", ""); } else { DRAW_ROW2(n, CPU_START + i, 18, "%*.*s", vmm_cur[i].v_lock_name); } #undef D #undef CPUV #undef CPUD #define CPUC(idx, field) vmm_cptime_cur[idx].cp_##field #if 0 n = X_START + CPU_LABEL_W; DRAW_ROW(n, CPU_STARTX + i, 15, "%-*s", CPUC(i, msg)); DRAW_ROW(n, CPU_STARTX + i, 35, "%-*s", address_to_symbol((void *)(intptr_t)CPUC(i, stallpc), &symctx)); #endif #undef CPUC } }
int __bro_openssl_write(BroConn *bc, uchar *buf, uint buf_size) { int n; void *old_sig; D_ENTER; #ifdef BRO_DEBUG if (bro_debug_messages) { unsigned int i = 0; int last_hex = 0; D(("Sending %u bytes: ", buf_size)); for (i = 0; i < buf_size; i++) { if (buf[i] >= 32 && buf[i] <= 126) { printf("%s%c", last_hex ? " " : "", buf[i]); last_hex = 0; } else { printf(" 0x%.2x", buf[i]); last_hex = 1; } } printf("\n"); } #endif /* We may get a SIGPIPE if we write to a connection whose peer * died. Since we don't know the application context in which * we're running, we temporarily set the SIGPIPE handler to our * own and then set it back to the old one after we wrote. */ old_sig = signal(SIGPIPE, SIG_IGN); n = BIO_write(bc->bio, buf, buf_size); if (n <= 0) { if (BIO_should_retry(bc->bio)) { n = 0; goto error_return; } print_errors(); __bro_openssl_shutdown(bc); D(("Connection closed.\n")); n = -1; } BIO_flush(bc->bio); error_return: if (old_sig != SIG_ERR) signal(SIGPIPE, old_sig); D_RETURN_(n); }
static int mkgrplist(char *buf, gid_t **list, int len) { int l,at=0; int blks; blks = blk_size(len); D(("cf. blks=%d and len=%d", blks,len)); while ((l = find_member(buf,&at))) { int edge; if (len >= blks) { gid_t *tmp; D(("allocating new block")); tmp = (gid_t *) realloc((*list) , sizeof(gid_t) * (blks += GROUP_BLK)); if (tmp != NULL) { (*list) = tmp; } else { _log_err("out of memory for group list"); free(*list); (*list) = NULL; return -1; } } /* '\0' terminate the entry */ edge = (buf[at+l]) ? 1:0; buf[at+l] = '\0'; D(("found group: %s",buf+at)); /* this is where we convert a group name to a gid_t */ #ifdef WANT_PWDB { int retval; const struct pwdb *pw=NULL; retval = pwdb_locate("group", PWDB_DEFAULT, buf+at , PWDB_ID_UNKNOWN, &pw); if (retval != PWDB_SUCCESS) { _log_err("bad group: %s; %s", buf+at, pwdb_strerror(retval)); } else { const struct pwdb_entry *pwe=NULL; D(("group %s exists", buf+at)); retval = pwdb_get_entry(pw, "gid", &pwe); if (retval == PWDB_SUCCESS) { D(("gid = %d [%p]",* (const gid_t *) pwe->value,list)); (*list)[len++] = * (const gid_t *) pwe->value; pwdb_entry_delete(&pwe); /* tidy up */ } else { _log_err("%s group entry is bad; %s" , pwdb_strerror(retval)); } pw = NULL; /* break link - cached for later use */ } } #else { const struct group *grp; grp = getgrnam(buf+at); if (grp == NULL) { _log_err("bad group: %s", buf+at); } else { D(("group %s exists", buf+at)); (*list)[len++] = grp->gr_gid; } } #endif /* next entry along */ at += l + edge; } D(("returning with [%p/len=%d]->%p",list,len,*list)); return len; }
void dynamic_parse(void *data, pattern_t *pattern, size_t offset) { if(unlikely(!get_flags_dynamic_enable())) return; struct ssn_skb_values * ssv = ( struct ssn_skb_values *)data; //struct l2ct_var_dpi * lvd = &(ssv->ssn->vars_dpi); #if 0 if (unlikely(pattern->pattern_key.dynamic_current_phase - 1 & lvd->ac_state_tbl != pattern->pattern_key.dynamic_current_phase - 1)) { if (i != 4) { D("current_phase[%u], ldv[%p], ac_state_tbl[%u]\n", pattern->pattern_key.dynamic_current_phase,lvd, lvd->ac_state_tbl); aaa =4; } lvd->ac_state_tbl = 0; return; } lvd->ac_state_tbl |= pattern->pattern_key.dynamic_current_phase; if (lvd->ac_state_tbl < pattern->pattern_key.dynamic_need_phase) return; lvd->ac_state_tbl = 0; #endif //get dns or ip + port list //char *sp = ssv->payload + offset + pattern->pattern_len; char *sp = ssv->payload + offset; char *ep = ssv->payload + ssv->payload_len; int pos = 0; uint32_t ip; uint32_t proto_mark; uint16_t port = 0; switch(pattern->pattern_key.dynamic_type) { case 1: { if (pattern->pattern_key.dynamic_port && pattern->pattern_key.dynamic_port != (uint16_t)-1) { if(pattern->pattern_key.dynamic_dir && pattern->pattern_key.dynamic_port != ssv->ssn->sess_key.port_dst) { return; } if(0 == pattern->pattern_key.dynamic_dir && pattern->pattern_key.dynamic_port != ssv->ssn->sess_key.port_src) { return; } } if (pattern->pattern_key.dynamic_dir) { if (pattern->pattern_key.dynamic_port == (uint16_t)-1) { study_cache_try_get(ssv->ssn->sess_key.ip_dst, ssv->dport, ssv->ssn->proto_mark, 0, DYNAMIC_TIMEO); #ifdef DYNAMIC_DEBUG LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n", pattern->pattern_name, ssv->ssn->sess_key.ip_dst, IPQUADS(ssv->ssn->sess_key.ip_dst), ntohs(ssv->dport), ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); #endif } else { study_cache_try_get(ssv->ssn->sess_key.ip_dst, pattern->pattern_key.dynamic_port, ssv->ssn->proto_mark, 0, DYNAMIC_TIMEO); #ifdef DYNAMIC_DEBUG LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n", pattern->pattern_name, ssv->ssn->sess_key.ip_dst, IPQUADS(ssv->ssn->sess_key.ip_dst), ntohs(pattern->pattern_key.dynamic_port), ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); #endif } } else { if (pattern->pattern_key.dynamic_port == (uint16_t)-1) { study_cache_try_get(ssv->ssn->sess_key.ip_src, ssv->sport, ssv->ssn->proto_mark, 0, 0); #ifdef DYNAMIC_DEBUG LOG("pattern[%s]add ip [%u]and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type, \n", pattern->pattern_name, ssv->ssn->sess_key.ip_src, IPQUADS(ssv->ssn->sess_key.ip_src), ntohs(ssv->sport), ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); #endif } else { study_cache_try_get(ssv->ssn->sess_key.ip_src, pattern->pattern_key.dynamic_port, ssv->ssn->proto_mark, 0, 0); #ifdef DYNAMIC_DEBUG LOG("pattern[%s]add ip and port [%u.%u.%u.%u:%u] proto[%u] dynamic_indirect[%d]to study cache, common type\n", pattern->pattern_name, IPQUADS(ssv->ssn->sess_key.ip_src), ntohs(pattern->pattern_key.dynamic_port), ssv->ssn->proto_mark,pattern->pattern_key.dynamic_indirect); #endif } } break; } case 2: { //printf("dns type\n"); parse_dns(data, pattern, offset); break; } case 3:// ip:port[10.211.55.88:88] { do{ pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.ip_key, pattern->pattern_key.ip_key_len, 0); if (pos <= 0) return; sp += pos; for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) { if (sp >= ep) return; } ip = ipv4_stonl(sp); if (unlikely(ip == 0xFFFFFFFF)) return; sp += 6; if (pattern->pattern_key.dynamic_port) { port = pattern->pattern_key.dynamic_port; } else { pos = substr_in_mainstr_nocase(sp, 16, ":", 0); if (pos > 0) { sp += pos; port = port_stons(sp); if (port == 65535) { port = 0; } } } if (likely(pattern->pattern_key.dynamic_indirect == 0) ) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); } else { dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n",pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner); #endif } else { if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n",pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } } } while (pattern->pattern_key.mult_iplist && sp < ep); // lvd->is_dynamic = 1; break; } case 4://such as: "ip":"111.161.80.157","port":1935, { do{ pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.ip_key, pattern->pattern_key.ip_key_len, 0); if (pos <= 0) return; sp += pos; for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) { if (sp >= ep) return; } ip = ipv4_stonl(sp); if (unlikely(ip == 0xFFFFFFFF)) return; sp += 6; pos = subhex_in_mainhex(sp, ep - sp, pattern->pattern_key.port_key, pattern->pattern_key.port_key_len, 0); if (pos <= 0) return; sp += pos; for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) { if (sp >= ep) return; } port = port_stons(sp); if (likely(pattern->pattern_key.dynamic_indirect == 0) ) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); } else { dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner); #endif } else { if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } } } while (pattern->pattern_key.mult_iplist && sp < ep); // lvd->is_dynamic = 1; break; } case 5: { do{ for(; __isspace(*sp)||*sp == '"'||*sp == ':'; sp++) { if (sp >= ep) return; } ip = ipv4_stonl(sp); if (unlikely(ip == 0xFFFFFFFF)) return; sp += 6; if (pattern->pattern_key.dynamic_port) { port = pattern->pattern_key.dynamic_port; } else { pos = subhex_in_mainhex(sp, 16, pattern->pattern_key.port_key,pattern->pattern_key.port_key_len, 0); if (pos > 0) { sp += pos; port = port_stons(sp); if (port == 65535) { port = 0; } } } if (likely(pattern->pattern_key.dynamic_indirect == 0) ) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, ssv->ssn->proto_mark, 0, 0); } else { dynamic_cache_try_get(ip, port, ssv->ssn->proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s]add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark, ssv->isinner); #endif } else { if ((proto_mark = dns_study_lookup_behavior(ssv->dip, ssv->dport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } else if ((proto_mark = dns_study_lookup_behavior(ssv->sip, ssv->sport)) > 0) { if (pattern->pattern_key.dynamic_dir) { study_cache_try_get(ip, port, proto_mark, 0, DNS_STUDY_TIMEO); } else { dynamic_cache_try_get(ip, port, proto_mark, 0); } #ifdef DYNAMIC_DEBUG LOG("[%s] dynamic indirect add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache isinner[%d]\n", pattern->pattern_name, IPQUADS(ip), ntohs(port), proto_mark, ssv->isinner); #endif } } } while (pattern->pattern_key.mult_iplist && sp < ep); // lvd->is_dynamic = 1; break; } #if 0 case 5://such as: ch1.dnf.qq.com, { do{ for(; __isspace(*sp); sp++) { if (sp >= ep) return; } pos = substr_in_mainstr_nocase(sp, ep - sp, pattern->port_key, 0); //pos = substr_in_mainstr_nocase(sp, 16, ":", 0); if (pos > 0) { strncopy(domain, sp, pos - strlen(pattern->port_key)); sp += pos; port = simple_strtol(sp, NULL, 0); domain_cache_try_get(domain, ssv->ssn->proto_mark); printk("---port=%u\n", port); } // else { // port = pattern->dynamic_port; // } DEG("add ip and port [%u.%u.%u.%u:%u]proto[%u]to dynamic cache\n", IPQUADS(ip), ntohs(port), ssv->ssn->proto_mark); } while (pattern->mult_iplist && sp < ep); lvd->is_dynamic = 1; break; } #endif default: break; } }
static int try_connect(const char* host_and_port) { int status, sockfd = -1; char* colon; char* tmp; char host[512]; char port[16]; struct addrinfo hints, *res, *res0; D_ENTER; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_protocol = IPPROTO_TCP; hints.ai_socktype = SOCK_STREAM; if ( ! (tmp = strdup(host_and_port)) ) { D(("Out of memory.\n")); D_RETURN_(-1); } if ( ! (colon = strrchr(tmp, ':')) ) { D(("Invalid host:port string: %s\n", host_and_port)); free(tmp); D_RETURN_(-1); } if ( ! colon[1] ) { D(("Invalid port in host:port string: %s\n", host_and_port)); free(tmp); D_RETURN_(-1); } *colon = '\0'; __bro_util_snprintf(host, sizeof(host), "%s", tmp); __bro_util_snprintf(port, sizeof(port), "%s", colon + 1); free(tmp); D(("Trying to connect to [%s]:%s\n", host, port)); status = getaddrinfo(host, port, &hints, &res0); if ( status != 0 ) { D(("Error in getaddrinfo: %s\n", gai_strerror(status))); D_RETURN_(-1); } for ( res = res0; res; res = res->ai_next ) { sockfd = socket(res->ai_family, res->ai_socktype, res->ai_protocol); if ( sockfd < 0 ) { D(("socket() failed: %s\n", strerror(errno))); continue; } if ( connect(sockfd, res->ai_addr, res->ai_addrlen) < 0 ) { D(("connect() to %s failed: %s\n", host_and_port, strerror(errno))); close(sockfd); sockfd = -1; continue; } break; } freeaddrinfo(res0); D_RETURN_(sockfd); }
void handle_online(atransport *t) { D("adb: online\n"); t->online = 1; XLOGD("adb: online\n"); }
void parse_banner(char *banner, atransport *t) { static const char *prop_seps = ";"; static const char key_val_sep = '='; char *cp; char *type; D("parse_banner: %s\n", banner); type = banner; cp = strchr(type, ':'); if (cp) { *cp++ = 0; /* Nothing is done with second field. */ cp = strchr(cp, ':'); if (cp) { char *save; char *key; key = adb_strtok_r(cp + 1, prop_seps, &save); while (key) { cp = strchr(key, key_val_sep); if (cp) { *cp++ = '\0'; if (!strcmp(key, "ro.product.name")) qual_overwrite(&t->product, cp); else if (!strcmp(key, "ro.product.model")) qual_overwrite(&t->model, cp); else if (!strcmp(key, "ro.product.device")) qual_overwrite(&t->device, cp); } key = adb_strtok_r(NULL, prop_seps, &save); } } } if(!strcmp(type, "bootloader")){ D("setting connection_state to CS_BOOTLOADER\n"); t->connection_state = CS_BOOTLOADER; update_transports(); return; } if(!strcmp(type, "device")) { D("setting connection_state to CS_DEVICE\n"); t->connection_state = CS_DEVICE; update_transports(); return; } if(!strcmp(type, "recovery")) { D("setting connection_state to CS_RECOVERY\n"); t->connection_state = CS_RECOVERY; update_transports(); return; } if(!strcmp(type, "sideload")) { D("setting connection_state to CS_SIDELOAD\n"); t->connection_state = CS_SIDELOAD; update_transports(); return; } t->connection_state = CS_HOST; }
int adb_main(int is_daemon, int server_port) { #if !ADB_HOST int port; char value[PROPERTY_VALUE_MAX]; umask(000); #endif atexit(adb_cleanup); #ifdef HAVE_WIN32_PROC SetConsoleCtrlHandler( ctrlc_handler, TRUE ); #elif defined(HAVE_FORKEXEC) // No SIGCHLD. Let the service subproc handle its children. signal(SIGPIPE, SIG_IGN); #endif init_transport_registration(); #if ADB_HOST HOST = 1; usb_vendors_init(); usb_init(); local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT); adb_auth_init(); char local_name[30]; build_local_name(local_name, sizeof(local_name), server_port); if(install_listener(local_name, "*smartsocket*", NULL)) { exit(1); } #else property_get("ro.adb.secure", value, "0"); auth_enabled = !strcmp(value, "1"); if (auth_enabled) adb_auth_init(); // Our external storage path may be different than apps, since // we aren't able to bind mount after dropping root. const char* adb_external_storage = getenv("ADB_EXTERNAL_STORAGE"); if (NULL != adb_external_storage) { setenv("EXTERNAL_STORAGE", adb_external_storage, 1); } else { D("Warning: ADB_EXTERNAL_STORAGE is not set. Leaving EXTERNAL_STORAGE" " unchanged.\n"); } /* don't listen on a port (default 5037) if running in secure mode */ /* don't run as root if we are running in secure mode */ if (should_drop_privileges()) { struct __user_cap_header_struct header; struct __user_cap_data_struct cap; if (prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0) != 0) { exit(1); } /* add extra groups: ** AID_ADB to access the USB driver ** AID_LOG to read system logs (adb logcat) ** AID_INPUT to diagnose input issues (getevent) ** AID_INET to diagnose network issues (netcfg, ping) ** AID_GRAPHICS to access the frame buffer ** AID_NET_BT and AID_NET_BT_ADMIN to diagnose bluetooth (hcidump) ** AID_SDCARD_R to allow reading from the SD card ** AID_SDCARD_RW to allow writing to the SD card ** AID_MOUNT to allow unmounting the SD card before rebooting ** AID_NET_BW_STATS to read out qtaguid statistics */ gid_t groups[] = { AID_ADB, AID_LOG, AID_INPUT, AID_INET, AID_GRAPHICS, AID_NET_BT, AID_NET_BT_ADMIN, AID_SDCARD_R, AID_SDCARD_RW, AID_MOUNT, AID_NET_BW_STATS }; if (setgroups(sizeof(groups)/sizeof(groups[0]), groups) != 0) { exit(1); } /* then switch user and group to "shell" */ if (setgid(AID_SHELL) != 0) { exit(1); } if (setuid(AID_SHELL) != 0) { exit(1); } /* set CAP_SYS_BOOT capability, so "adb reboot" will succeed */ header.version = _LINUX_CAPABILITY_VERSION; header.pid = 0; cap.effective = cap.permitted = (1 << CAP_SYS_BOOT); cap.inheritable = 0; capset(&header, &cap); D("Local port disabled\n"); } else { char local_name[30]; build_local_name(local_name, sizeof(local_name), server_port); if(install_listener(local_name, "*smartsocket*", NULL)) { exit(1); } } int usb = 0; if (access(USB_ADB_PATH, F_OK) == 0 || access(USB_FFS_ADB_EP0, F_OK) == 0) { // listen on USB usb_init(); usb = 1; } // If one of these properties is set, also listen on that port // If one of the properties isn't set and we couldn't listen on usb, // listen on the default port. property_get("service.adb.tcp.port", value, ""); if (!value[0]){ property_get("persist.adb.tcp.port", value, ""); } if (sscanf(value, "%d", &port) == 1 && port > 0) { printf("using port=%d\n", port); // listen on TCP port specified by service.adb.tcp.port property local_init(port); } else if (!usb) { // listen on default port local_init(DEFAULT_ADB_LOCAL_TRANSPORT_PORT); } D("adb_main(): pre init_jdwp()\n"); XLOGD("adb_main(): pre init_jdwp()\n"); init_jdwp(); D("adb_main(): post init_jdwp()\n"); XLOGD("adb_main(): post init_jdwp()\n"); #endif if (is_daemon) { // inform our parent that we are up and running. #ifdef HAVE_WIN32_PROC DWORD count; WriteFile( GetStdHandle( STD_OUTPUT_HANDLE ), "OK\n", 3, &count, NULL ); #elif defined(HAVE_FORKEXEC) fprintf(stderr, "OK\n"); #endif start_logging(); } D("Event loop starting\n"); XLOGD("Event loop starting\n"); fdevent_loop(); usb_cleanup(); return 0; }
int handle_host_request(char *service, transport_type ttype, char* serial, int reply_fd, asocket *s) { atransport *transport = NULL; char buf[4096]; if(!strcmp(service, "kill")) { fprintf(stderr,"adb server killed by remote request\n"); fflush(stdout); adb_write(reply_fd, "OKAY", 4); usb_cleanup(); exit(0); } #if ADB_HOST // "transport:" is used for switching transport with a specified serial number // "transport-usb:" is used for switching transport to the only USB transport // "transport-local:" is used for switching transport to the only local transport // "transport-any:" is used for switching transport to the only transport if (!strncmp(service, "transport", strlen("transport"))) { char* error_string = "unknown failure"; transport_type type = kTransportAny; if (!strncmp(service, "transport-usb", strlen("transport-usb"))) { type = kTransportUsb; } else if (!strncmp(service, "transport-local", strlen("transport-local"))) { type = kTransportLocal; } else if (!strncmp(service, "transport-any", strlen("transport-any"))) { type = kTransportAny; } else if (!strncmp(service, "transport:", strlen("transport:"))) { service += strlen("transport:"); serial = service; } transport = acquire_one_transport(CS_ANY, type, serial, &error_string); if (transport) { s->transport = transport; adb_write(reply_fd, "OKAY", 4); } else { sendfailmsg(reply_fd, error_string); } return 1; } // return a list of all connected devices if (!strncmp(service, "devices", 7)) { char buffer[4096]; int use_long = !strcmp(service+7, "-l"); if (use_long || service[7] == 0) { memset(buf, 0, sizeof(buf)); memset(buffer, 0, sizeof(buffer)); D("Getting device list \n"); list_transports(buffer, sizeof(buffer), use_long); snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer),buffer); D("Wrote device list \n"); writex(reply_fd, buf, strlen(buf)); return 0; } } // add a new TCP transport, device or emulator if (!strncmp(service, "connect:", 8)) { char buffer[4096]; char* host = service + 8; if (!strncmp(host, "emu:", 4)) { connect_emulator(host + 4, buffer, sizeof(buffer)); } else { connect_device(host, buffer, sizeof(buffer)); } // Send response for emulator and device snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer); writex(reply_fd, buf, strlen(buf)); return 0; } // remove TCP transport if (!strncmp(service, "disconnect:", 11)) { char buffer[4096]; memset(buffer, 0, sizeof(buffer)); char* serial = service + 11; if (serial[0] == 0) { // disconnect from all TCP devices unregister_all_tcp_transports(); } else { char hostbuf[100]; // assume port 5555 if no port is specified if (!strchr(serial, ':')) { snprintf(hostbuf, sizeof(hostbuf) - 1, "%s:5555", serial); serial = hostbuf; } atransport *t = find_transport(serial); if (t) { unregister_transport(t); } else { snprintf(buffer, sizeof(buffer), "No such device %s", serial); } } snprintf(buf, sizeof(buf), "OKAY%04x%s",(unsigned)strlen(buffer), buffer); writex(reply_fd, buf, strlen(buf)); return 0; } // returns our value for ADB_SERVER_VERSION if (!strcmp(service, "version")) { char version[12]; snprintf(version, sizeof version, "%04x", ADB_SERVER_VERSION); snprintf(buf, sizeof buf, "OKAY%04x%s", (unsigned)strlen(version), version); writex(reply_fd, buf, strlen(buf)); return 0; } if(!strncmp(service,"get-serialno",strlen("get-serialno"))) { char *out = "unknown"; transport = acquire_one_transport(CS_ANY, ttype, serial, NULL); if (transport && transport->serial) { out = transport->serial; } snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out); writex(reply_fd, buf, strlen(buf)); return 0; } if(!strncmp(service,"get-devpath",strlen("get-devpath"))) { char *out = "unknown"; transport = acquire_one_transport(CS_ANY, ttype, serial, NULL); if (transport && transport->devpath) { out = transport->devpath; } snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(out),out); writex(reply_fd, buf, strlen(buf)); return 0; } // indicates a new emulator instance has started if (!strncmp(service,"emulator:",9)) { int port = atoi(service+9); local_connect(port); /* we don't even need to send a reply */ return 0; } #endif // ADB_HOST if(!strncmp(service,"forward:",8) || !strncmp(service,"killforward:",12)) { char *local, *remote, *err; int r; atransport *transport; int createForward = strncmp(service,"kill",4); local = service + (createForward ? 8 : 12); remote = strchr(local,';'); if(remote == 0) { sendfailmsg(reply_fd, "malformed forward spec"); return 0; } *remote++ = 0; if((local[0] == 0) || (remote[0] == 0) || (remote[0] == '*')){ sendfailmsg(reply_fd, "malformed forward spec"); return 0; } transport = acquire_one_transport(CS_ANY, ttype, serial, &err); if (!transport) { sendfailmsg(reply_fd, err); return 0; } if (createForward) { r = install_listener(local, remote, transport); } else { r = remove_listener(local, remote, transport); } if(r == 0) { /* 1st OKAY is connect, 2nd OKAY is status */ writex(reply_fd, "OKAYOKAY", 8); return 0; } if (createForward) { sendfailmsg(reply_fd, (r == -1) ? "cannot rebind smartsocket" : "cannot bind socket"); } else { sendfailmsg(reply_fd, "cannot remove listener"); } return 0; } if(!strncmp(service,"get-state",strlen("get-state"))) { transport = acquire_one_transport(CS_ANY, ttype, serial, NULL); char *state = connection_state_name(transport); snprintf(buf, sizeof buf, "OKAY%04x%s",(unsigned)strlen(state),state); writex(reply_fd, buf, strlen(buf)); return 0; } return -1; }
static void * receiver_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *rxring; int i, received = 0; if (setaffinity(targ->thread, targ->affinity)) goto quit; /* setup poll(2) mechanism. */ memset(fds, 0, sizeof(fds)); fds[0].fd = targ->fd; fds[0].events = (POLLIN); /* unbounded wait for the first packet. */ for (;;) { i = poll(fds, 1, 1000); if (i > 0 && !(fds[0].revents & POLLERR)) break; D("waiting for initial packets, poll returns %d %d", i, fds[0].revents); } /* main loop, exit after 1s silence */ gettimeofday(&targ->tic, NULL); if (targ->g->use_pcap) { for (;;) { /* XXX should we poll ? */ pcap_dispatch(targ->g->p, targ->g->burst, receive_pcap, NULL); } } else { while (1) { /* Once we started to receive packets, wait at most 1 seconds before quitting. */ do { i = poll(fds, 1, 1 * 1000); if (i < 0) { gettimeofday(&targ->toc, NULL); targ->toc.tv_sec -= 1; /* Subtract timeout time. */ goto rx_out; } } while (i==0); for (i = targ->qfirst; i < targ->qlast; i++) { int m; rxring = NETMAP_RXRING(nifp, i); if (rxring->avail == 0) continue; m = receive_packets(rxring, targ->g->burst, SKIP_PAYLOAD); received += m; targ->count = received; } // tell the card we have read the data //ioctl(fds[0].fd, NIOCRXSYNC, NULL); } } rx_out: targ->completed = 1; targ->count = received; quit: /* reset the ``used`` flag. */ targ->used = 0; return (NULL); }
static void * sender_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *txring; int i, n = targ->g->npackets / targ->g->nthreads, sent = 0; int options = targ->g->options | OPT_COPY; D("start"); if (setaffinity(targ->thread, targ->affinity)) goto quit; /* setup poll(2) mechanism. */ memset(fds, 0, sizeof(fds)); fds[0].fd = targ->fd; fds[0].events = (POLLOUT); /* main loop.*/ gettimeofday(&targ->tic, NULL); if (targ->g->use_pcap) { int size = targ->g->pkt_size; void *pkt = &targ->pkt; pcap_t *p = targ->g->p; for (i = 0; n == 0 || sent < n; i++) { if (pcap_inject(p, pkt, size) != -1) sent++; if (i > 10000) { targ->count = sent; i = 0; } } } else { while (n == 0 || sent < n) { /* * wait for available room in the send queue(s) */ do { i = poll(fds, 1, 2000); if (i < 0) { D("poll error/timeout on queue %d", targ->me); goto quit; } } while (i==0); /* * scan our queues and send on those with room */ if (options & OPT_COPY && sent > 100000 && !(targ->g->options & OPT_COPY) ) { D("drop copy"); options &= ~OPT_COPY; } for (i = targ->qfirst; i < targ->qlast; i++) { int m, limit = targ->g->burst; if (n > 0 && n - sent < limit) limit = n - sent; txring = NETMAP_TXRING(nifp, i); if (txring->avail == 0) continue; m = send_pkts(txring, targ->pkts, targ->g->pkt_size, limit, options, sent, targ->npkts); sent += m; targ->count = sent; } } /* flush any remaining packets */ ioctl(fds[0].fd, NIOCTXSYNC, NULL); /* final part: wait all the TX queues to be empty. */ for (i = targ->qfirst; i < targ->qlast; i++) { txring = NETMAP_TXRING(nifp, i); while (!NETMAP_TX_RING_EMPTY(txring)) { ioctl(fds[0].fd, NIOCTXSYNC, NULL); usleep(1); /* wait 1 tick */ } } } gettimeofday(&targ->toc, NULL); targ->completed = 1; targ->count = sent; quit: /* reset the ``used`` flag. */ targ->used = 0; return (NULL); }
/* * reply to ping requests */ static void * ponger_body(void *data) { struct targ *targ = (struct targ *) data; struct pollfd fds[1]; struct netmap_if *nifp = targ->nifp; struct netmap_ring *txring, *rxring; int i, rx = 0, sent = 0, n = targ->g->npackets; fds[0].fd = targ->fd; fds[0].events = (POLLIN); if (targ->g->nthreads > 1) { D("can only reply ping with 1 thread"); return NULL; } D("understood ponger %d but don't know how to do it", n); while (n == 0 || sent < n) { uint32_t txcur, txavail; //#define BUSYWAIT #ifdef BUSYWAIT ioctl(fds[0].fd, NIOCRXSYNC, NULL); #else if (poll(fds, 1, 1000) <= 0) { D("poll error/timeout on queue %d", targ->me); continue; } #endif txring = NETMAP_TXRING(nifp, 0); txcur = txring->cur; txavail = txring->avail; /* see what we got back */ for (i = targ->qfirst; i < targ->qlast; i++) { rxring = NETMAP_RXRING(nifp, i); while (rxring->avail > 0) { uint32_t cur = rxring->cur; struct netmap_slot *slot = &rxring->slot[cur]; char *src, *dst; src = NETMAP_BUF(rxring, slot->buf_idx); //D("got pkt %p of size %d", src, slot->len); rxring->avail--; rxring->cur = NETMAP_RING_NEXT(rxring, cur); rx++; if (txavail == 0) continue; dst = NETMAP_BUF(txring, txring->slot[txcur].buf_idx); /* copy... */ pkt_copy(src, dst, slot->len); txring->slot[txcur].len = slot->len; /* XXX swap src dst mac */ txcur = NETMAP_RING_NEXT(txring, txcur); txavail--; sent++; } } txring->cur = txcur; txring->avail = txavail; targ->count = sent; #ifdef BUSYWAIT ioctl(fds[0].fd, NIOCTXSYNC, NULL); #endif //D("tx %d rx %d", sent, rx); } return NULL; }
inline void callFunction(mxArray* plhs[], const mxArray*prhs[], const int nlhs) { if (!mexCheckType<T>(prhs[0])) mexErrMsgTxt("type of argument 1 is not consistent"); if (mxIsSparse(prhs[0])) mexErrMsgTxt("argument 1 should be full"); if (!mexCheckType<T>(prhs[1])) mexErrMsgTxt("type of argument 2 is not consistent"); if (mxIsSparse(prhs[1])) mexErrMsgTxt("argument 2 should be full"); if (!mexCheckType<bool>(prhs[2])) mexErrMsgTxt("type of argument 3 should be boolean"); if (mxIsSparse(prhs[2])) mexErrMsgTxt("argument 3 should be full"); if (!mxIsStruct(prhs[3])) mexErrMsgTxt("argument 3 should be struct"); T* prX = reinterpret_cast<T*>(mxGetPr(prhs[0])); const mwSize* dimsX=mxGetDimensions(prhs[0]); int n=static_cast<int>(dimsX[0]); int M=static_cast<int>(dimsX[1]); T* prD = reinterpret_cast<T*>(mxGetPr(prhs[1])); const mwSize* dimsD=mxGetDimensions(prhs[1]); int nD=static_cast<int>(dimsD[0]); int K=static_cast<int>(dimsD[1]); if (n != nD) mexErrMsgTxt("argument sizes are not consistent"); bool* prmask = reinterpret_cast<bool*>(mxGetPr(prhs[2])); const mwSize* dimsM=mxGetDimensions(prhs[2]); int nM=static_cast<int>(dimsM[0]); int mM=static_cast<int>(dimsM[1]); if (nM != n || mM != M) mexErrMsgTxt("argument sizes are not consistent"); Matrix<T> X(prX,n,M); Matrix<T> D(prD,n,K); SpMatrix<T> alpha; mxArray* pr_L=mxGetField(prhs[3],0,"L"); if (!pr_L) mexErrMsgTxt("Missing field L in param"); const mwSize* dimsL=mxGetDimensions(pr_L); int sizeL=static_cast<int>(dimsL[0])*static_cast<int>(dimsL[1]); mxArray* pr_eps=mxGetField(prhs[3],0,"eps"); if (!pr_eps) mexErrMsgTxt("Missing field eps in param"); const mwSize* dimsE=mxGetDimensions(pr_eps); int sizeE=static_cast<int>(dimsE[0])*static_cast<int>(dimsE[1]); int numThreads = getScalarStructDef<int>(prhs[3],"numThreads",-1); Matrix<bool> mask(prmask,n,M); if (nlhs == 2) { int L=MIN(n,MIN(static_cast<int>(mxGetScalar(pr_L)),K)); plhs[1]=createMatrix<T>(K,L); T* pr_path=reinterpret_cast<T*>(mxGetPr(plhs[1])); Matrix<T> path(pr_path,K,L); path.setZeros(); T eps=static_cast<T>(mxGetScalar(pr_eps)); omp_mask<T>(X,D,alpha,mask,L,eps,numThreads,path); } else { if (sizeL == 1) { int L=static_cast<int>(mxGetScalar(pr_L)); if (sizeE == 1) { T eps=static_cast<T>(mxGetScalar(pr_eps)); omp_mask<T>(X,D,alpha,mask,L,eps,numThreads); } else { T* pE = reinterpret_cast<T*>(mxGetPr(pr_eps)); omp_mask<T>(X,D,alpha,mask,L,pE,numThreads); } } else { if (!mexCheckType<int>(pr_L)) mexErrMsgTxt("Type of param.L should be int32"); int* pL = reinterpret_cast<int*>(mxGetPr(pr_L)); if (sizeE == 1) { T eps=static_cast<T>(mxGetScalar(pr_eps)); omp_mask<T>(X,D,alpha,mask,pL,eps,numThreads); } else { T* pE = reinterpret_cast<T*>(mxGetPr(pr_eps)); omp_mask<T>(X,D,alpha,mask,pL,pE,numThreads,true,true); } } } convertSpMatrix(plhs[0],K,M,alpha.n(),alpha.nzmax(),alpha.v(),alpha.r(), alpha.pB()); }
void handle_packet(apacket *p, atransport *t) { asocket *s; D("handle_packet() %c%c%c%c\n", ((char*) (&(p->msg.command)))[0], ((char*) (&(p->msg.command)))[1], ((char*) (&(p->msg.command)))[2], ((char*) (&(p->msg.command)))[3]); print_packet("recv", p); switch(p->msg.command){ case A_SYNC: XLOGD("%s: %s %08x %08x %04x \n", "recv", "SYNC", p->msg.arg0, p->msg.arg1, p->msg.data_length); if(p->msg.arg0){ send_packet(p, t); if(HOST) send_connect(t); } else { t->connection_state = CS_OFFLINE; handle_offline(t); send_packet(p, t); } return; case A_CNXN: /* CONNECT(version, maxdata, "system-id-string") */ /* XXX verify version, etc */ XLOGD("%s: %s %08x %08x %04x %s\n", "recv", "CNXN", p->msg.arg0, p->msg.arg1, p->msg.data_length, p->data); if(t->connection_state != CS_OFFLINE) { t->connection_state = CS_OFFLINE; handle_offline(t); } parse_banner((char*) p->data, t); if (HOST || !auth_enabled) { handle_online(t); if(!HOST) send_connect(t); } else { send_auth_request(t); } break; case A_AUTH: if (p->msg.arg0 == ADB_AUTH_TOKEN) { t->key = adb_auth_nextkey(t->key); if (t->key) { send_auth_response(p->data, p->msg.data_length, t); } else { /* No more private keys to try, send the public key */ send_auth_publickey(t); } } else if (p->msg.arg0 == ADB_AUTH_SIGNATURE) { if (adb_auth_verify(t->token, p->data, p->msg.data_length)) { adb_auth_verified(t); t->failed_auth_attempts = 0; } else { if (t->failed_auth_attempts++ > 10) adb_sleep_ms(1000); send_auth_request(t); } } else if (p->msg.arg0 == ADB_AUTH_RSAPUBLICKEY) { adb_auth_confirm_key(p->data, p->msg.data_length, t); } break; case A_OPEN: /* OPEN(local-id, 0, "destination") */ if (t->online) { char *name = (char*) p->data; name[p->msg.data_length > 0 ? p->msg.data_length - 1 : 0] = 0; s = create_local_service_socket(name); if(s == 0) { send_close(0, p->msg.arg0, t); } else { s->peer = create_remote_socket(p->msg.arg0, t); s->peer->peer = s; send_ready(s->id, s->peer->id, t); s->ready(s); } } break; case A_OKAY: /* READY(local-id, remote-id, "") */ if (t->online) { if((s = find_local_socket(p->msg.arg1))) { if(s->peer == 0) { s->peer = create_remote_socket(p->msg.arg0, t); s->peer->peer = s; } s->ready(s); } } break; case A_CLSE: /* CLOSE(local-id, remote-id, "") */ if (t->online) { if((s = find_local_socket(p->msg.arg1))) { s->close(s); } } break; case A_WRTE: if (t->online) { if((s = find_local_socket(p->msg.arg1))) { unsigned rid = p->msg.arg0; p->len = p->msg.data_length; if(s->enqueue(s, p) == 0) { D("Enqueue the socket\n"); send_ready(s->id, rid, t); } return; } } break; default: printf("handle_packet: what is %08x?!\n", p->msg.command); XLOGW("handle_packet: what is %08x?!\n", p->msg.command); } put_apacket(p); }
int NP() { printf("<NP>"); D(); N(); printf("</NP>"); }
// vaInitialize static VAStatus xvba_common_Initialize(xvba_driver_data_t *driver_data) { int xvba_version; int fglrx_major_version, fglrx_minor_version, fglrx_micro_version; unsigned int device_id; driver_data->x11_dpy_local = XOpenDisplay(driver_data->x11_dpy_name); if (!driver_data->x11_dpy_local) return VA_STATUS_ERROR_UNKNOWN; if (!fglrx_is_dri_capable(driver_data->x11_dpy, driver_data->x11_screen)) return VA_STATUS_ERROR_UNKNOWN; if (!fglrx_get_version(driver_data->x11_dpy, driver_data->x11_screen, &fglrx_major_version, &fglrx_minor_version, &fglrx_micro_version)) return VA_STATUS_ERROR_UNKNOWN; D(bug("FGLRX driver version %d.%d.%d detected\n", fglrx_major_version, fglrx_minor_version, fglrx_micro_version)); if (!fglrx_check_version(8,80,5)) { xvba_error_message("FGLRX driver version 8.80.5 (Catalyst 10.12) or later is required\n"); return VA_STATUS_ERROR_UNKNOWN; } if (!fglrx_get_device_id(driver_data->x11_dpy, driver_data->x11_screen, &device_id)) return VA_STATUS_ERROR_UNKNOWN; D(bug("FGLRX device ID 0x%04x\n", device_id)); driver_data->device_id = device_id; switch (device_id & 0xff00) { case 0x6700: // Radeon HD 6000 series case 0x6800: // Radeon HD 5000 series D(bug("Evergreen GPU detected\n")); driver_data->is_evergreen_gpu = 1; break; case 0x9800: // Fusion series D(bug("Fusion IGP detected\n")); driver_data->is_evergreen_gpu = 1; driver_data->is_fusion_igp = 1; break; } if (xvba_gate_init() < 0) return VA_STATUS_ERROR_UNKNOWN; if (xvba_query_extension(driver_data->x11_dpy, &xvba_version) < 0) return VA_STATUS_ERROR_UNKNOWN; D(bug("XvBA version %d.%d detected\n", (xvba_version >> 16) & 0xffff, xvba_version & 0xffff)); if (!xvba_check_version(0,74)) { xvba_information_message("Please upgrade to XvBA >= 0.74\n"); return VA_STATUS_ERROR_UNIMPLEMENTED; } driver_data->xvba_context = xvba_create_context(driver_data->x11_dpy, None); if (!driver_data->xvba_context) return VA_STATUS_ERROR_UNKNOWN; sprintf(driver_data->va_vendor, "%s %s - %d.%d.%d", XVBA_STR_DRIVER_VENDOR, XVBA_STR_DRIVER_NAME, XVBA_VIDEO_MAJOR_VERSION, XVBA_VIDEO_MINOR_VERSION, XVBA_VIDEO_MICRO_VERSION); if (XVBA_VIDEO_PRE_VERSION > 0) { const int len = strlen(driver_data->va_vendor); sprintf(&driver_data->va_vendor[len], ".pre%d", XVBA_VIDEO_PRE_VERSION); } CREATE_HEAP(config, CONFIG); CREATE_HEAP(context, CONTEXT); CREATE_HEAP(surface, SURFACE); CREATE_HEAP(buffer, BUFFER); CREATE_HEAP(output, OUTPUT); CREATE_HEAP(image, IMAGE); CREATE_HEAP(subpicture, SUBPICTURE); return VA_STATUS_SUCCESS; }
int __bro_openssl_init(void) { static int deja_vu = FALSE; int use_ssl = FALSE; const char *our_cert, *our_key, *our_pass, *ca_cert; D_ENTER; if (deja_vu) D_RETURN_(TRUE); deja_vu = TRUE; /* I hope these should go before SSL_library_init() -- not even the * O'Reilly book is clear on that. :( --cpk */ if (global_ctx) { if (global_ctx->id_func) CRYPTO_set_id_callback(global_ctx->id_func); if (global_ctx->lock_func) CRYPTO_set_locking_callback(global_ctx->lock_func); if (global_ctx->dl_create_func) CRYPTO_set_dynlock_create_callback(global_ctx->dl_create_func); if (global_ctx->dl_lock_func) CRYPTO_set_dynlock_lock_callback(global_ctx->dl_lock_func); if (global_ctx->dl_free_func) CRYPTO_set_dynlock_destroy_callback(global_ctx->dl_free_func); } SSL_library_init(); prng_init(); #ifdef BRO_DEBUG D(("Loading OpenSSL error strings for debugging\n")); SSL_load_error_strings(); #endif if (__bro_conf_get_int("/broccoli/use_ssl", &use_ssl) && ! use_ssl) { D(("SSL disabled in configuration, not using SSL.\n")); D_RETURN_(TRUE); } our_cert = __bro_conf_get_str("/broccoli/host_cert"); our_key = __bro_conf_get_str("/broccoli/host_key"); if (our_key == NULL) { /* No private key configured; get it from the certificate file */ our_key = our_cert; } if (our_cert == NULL) { if (use_ssl) { D(("SSL requested but host certificate not given -- aborting.\n")); D_RETURN_(FALSE); } else { D(("use_ssl not used and host certificate not given -- not using SSL.\n")); D_RETURN_(TRUE); } } if (our_key == NULL) { if (use_ssl) { D(("SSL requested but host key not given -- aborting.\n")); D_RETURN_(FALSE); } else { D(("use_ssl not used and host key not given -- not using SSL.\n")); D_RETURN_(TRUE); } } /* At this point we either haven't seen use_ssl but a host_cert, or * we have seen use_ssl and it is set to true. Either way, we attempt * to set up an SSL connection now and abort if this fails in any way. */ if (! (ctx = SSL_CTX_new(SSLv3_method()))) D_RETURN_(FALSE); /* We expect things to be stored in PEM format, which means that we * can store multiple entities in one file. In this case, our own * certificate is expected to be stored along with the private key * in the file pointed to by preference setting /broccoli/certificate. * * See page 121 in O'Reilly's OpenSSL book for details. */ if (SSL_CTX_use_certificate_chain_file(ctx, our_cert) != 1) { D(("Error loading certificate from '%s'.\n", our_cert)); goto error_return; } if ( (our_pass = __bro_conf_get_str("/broccoli/host_pass"))) { D(("Host passphrase given in config file, not prompting for input.\n")); SSL_CTX_set_default_passwd_cb(ctx, pem_passwd_cb); SSL_CTX_set_default_passwd_cb_userdata(ctx, (void *) our_pass); } if (SSL_CTX_use_PrivateKey_file(ctx, our_key, SSL_FILETYPE_PEM) != 1) { D(("SSL used but error loading private key from '%s' -- aborting.\n", our_key)); goto error_return; } /* We should not need the passphrase, if existant, ever again. * Therefore we erase it from memory now. */ if (our_pass) { our_pass = NULL; __bro_conf_forget_item("/broccoli/host_pass"); } /* For validation purposes, our trusted CA's certificate will * be needed as well: */ if (! (ca_cert = __bro_conf_get_str("/broccoli/ca_cert"))) { D(("SSL used but CA certificate not given -- aborting.")); goto error_return; } if (! SSL_CTX_load_verify_locations(ctx, ca_cert, 0)) { D(("SSL used but CA certificate could not be loaded -- aborting\n")); goto error_return; } /* Check the consistency of the certificate vs. the private key */ if (SSL_CTX_check_private_key(ctx) != 1) { D(("SSL used but private key does not match the certificate -- aborting\n")); goto error_return; } /* Only use real ciphers. */ if (! SSL_CTX_set_cipher_list(ctx, "HIGH")) { D(("SSL used but can't set cipher list -- aborting\n")); goto error_return; } /* We require certificates from all communication peers, regardless of * whether we're the "server" or "client" (these concepts are blurred in our * case anyway). In order to be able to give better error feedback, we * add our own verification filter callback, "verify_cb". */ SSL_CTX_set_verify(ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, verify_cb); D(("SSL setup successful.\n")); D_RETURN_(TRUE); error_return: SSL_CTX_free(ctx); ctx = NULL; D_RETURN_(FALSE); }
int main() { poc(); SLabel A("A"); SExpressionLabel *pa = A.GetPtr(); SLabel B("B"); SExpressionLabel *pb = B.GetPtr(); SLabel C("C"); SExpressionLabel *pc = C.GetPtr(); SLabel D("D"); SExpressionLabel *pd = D.GetPtr(); SLabel E("E"); SExpressionLabel *pe = E.GetPtr(); SLabel F("F"); SExpressionLabel *pf = F.GetPtr(); SExpressionLabel *pall[] = { pa, pb, pc, pd, pe, pf }; try { TestSection("IntelibBindingsSet"); TestSubsection("Creation"); { IntelibBindingsSet t; TESTB("empty0", !t.GetBinding(pa)); TESTB("empty25", !t.GetBinding(pb)); *(t.AddBinding(pb)) = SReference(2525); TESTTR("root_only", *(t.GetBinding(pb)), "2525"); *(t.AddBinding(pc)) = SReference(3636); TESTB("root_still_there", t.GetBinding(pb)); TESTTR("root_still_has_value", *(t.GetBinding(pb)), "2525"); TESTB("second_val_exists", t.GetBinding(pc)); TESTTR("second_val", *(t.GetBinding(pc)), "3636"); TESTB("root_still_there", t.GetBinding(pb)); } TestSubsection("Allocation"); { IntelibBindingsSet t; SReference* loc[4]; for(int i = 0; i < 4; i++) { loc[i] = t.AddBinding(pall[i]); *loc[i] = (i+1) * 1000; } t.AddBinding(pf); SReference *l1 = t.GetBinding(pb); TESTB("still_there_after_resize", l1); TESTTR("still_value_after_resize", *l1, "2000"); SReference *l0 = t.GetBinding(pa); TESTB("root_there_after_resize", l0); TESTTR("root_value_after_resize", *l0, "1000"); //TESTB("resize_really_done", l1 != loc[1]); } TestSubsection("Iterator"); { IntelibBindingsSet t; IntelibBindingsSet::Iterator iter0(t); SReference ref; const SExpressionLabel *key; TESTB("iterator_on_empty", !iter0.GetNext(key, ref)); *(t.AddBinding(pa)) = SReference(2); *(t.AddBinding(pb)) = SReference(20); *(t.AddBinding(pc)) = SReference(200); IntelibBindingsSet::Iterator iter1(t); int sum2 = 0; while(iter1.GetNext(key, ref)) { if(ref.GetPtr()) sum2 += ref.GetInt(); } TEST("iterator_values", sum2, 222); } TestSubsection("LotsOfBindings"); { IntelibBindingsSet t; *(t.AddBinding(pa)) = SReference(1); *(t.AddBinding(pb)) = SReference(2); *(t.AddBinding(pc)) = SReference(3); *(t.AddBinding(pd)) = SReference(4); *(t.AddBinding(pe)) = SReference(5); *(t.AddBinding(pf)) = SReference(6); TESTB("value_there_1", t.GetBinding(pa)); TESTB("value_there_2", t.GetBinding(pb)); TESTB("value_there_3", t.GetBinding(pc)); TESTB("value_there_4", t.GetBinding(pd)); TESTB("value_there_5", t.GetBinding(pe)); TESTB("value_there_6", t.GetBinding(pf)); } TestScore(); } catch(const IntelibX &ex) { printf("Caught IntelibX: %s\n%s\n", ex.Description(), ex.Parameter().GetPtr() ? ex.Parameter()->TextRepresentation().c_str() : "" ); } catch(...) { printf("Something strange caught\n"); } poc(); return 0; }
static int openssl_connect(BroConn *bc) { int flags, sockfd = -1; BIO *bio = NULL; BIO *ssl_bio = NULL; D_ENTER; if (! bc || ! bc->peer || ! *(bc->peer)) D_RETURN_(FALSE); /* Make sure OpenSSL is initialised -- this has effect only once */ if (! __bro_openssl_init()) D_RETURN_(FALSE); /* Use socket provided by user if BroConn came via bro_conn_new_socket */ if ( bc->socket >= 0 ) { D(("Connection created from externally provided socket.\n")); sockfd = bc->socket; } else sockfd = try_connect(bc->peer); if ( sockfd == -1 ) { D(("Error connecting to %s.\n", bc->peer)); goto err_return; } if ( ! (bio = BIO_new_socket(sockfd, BIO_CLOSE)) ) { D(("Error creating connection BIO from socket.\n")); goto err_return; } if ( (flags = fcntl(sockfd, F_GETFL, 0)) < 0 ) { D(("Error getting socket flags.\n")); goto err_return; } if ( fcntl(sockfd, F_SETFL, flags|O_NONBLOCK) < 0 ) { D(("Error setting socket to non-blocking.\n")); goto err_return; } /* Don't know whether this is needed but it does not hurt either. * It is however not sufficient to just call this; we manually need to * set the socket to non-blocking as done above. */ BIO_set_nbio(bio, 1); /* Add SSL if available */ if ( ctx ) { if ( ! (ssl_bio = BIO_new_ssl(ctx, 1)) ) { D(("Error creating ssl BIO.\n")); goto err_return; } BIO_set_close(ssl_bio, BIO_CLOSE); BIO_push(ssl_bio, bio); bio = ssl_bio; } bc->bio = bio; D(("Connection established successfully.\n")); D_RETURN_(TRUE); err_return: print_errors(); #ifdef BRO_DEBUG if (ctx) D(("--- SSL CONNECTION SETUP FAILED. ---")); else D(("--- CLEARTEXT CONNECTION SETUP FAILED. ---")); #endif if (bio) BIO_free_all(bio); bc->state->rx_dead = bc->state->tx_dead = TRUE; bc->bio = NULL; D_RETURN_(FALSE); }
// Receive a message from the render window thread. // On exit, |*msg| gets a copy of the message. The caller // must always call sendResult() after processing the message. void receiveMessage(RenderWindowMessage* msg) { D("entering\n"); mIn.receive(msg); D("message cmd=%d\n", msg->cmd); }
/* take the current date and see if the range "date" passes it */ static boolean check_time(const void *AT, const char *times, int len, int rule) { boolean not,pass; int marked_day, time_start, time_end; const TIME *at; int i,j=0; at = AT; D(("checking: 0%o/%.4d vs. %s", at->day, at->minute, times)); if (times == NULL) { /* this should not happen */ _log_err("internal error: " __FILE__ " line %d", __LINE__); return FALSE; } if (times[j] == '!') { ++j; not = TRUE; } else { not = FALSE; } for (marked_day = 0; len > 0 && isalpha(times[j]); --len) { int this_day=-1; D(("%c%c ?", times[j], times[j+1])); for (i=0; days[i].d != NULL; ++i) { if (tolower(times[j]) == days[i].d[0] && tolower(times[j+1]) == days[i].d[1] ) { this_day = days[i].bit; break; } } j += 2; if (this_day == -1) { _log_err("bad day specified (rule #%d)", rule); return FALSE; } marked_day ^= this_day; } if (marked_day == 0) { _log_err("no day specified"); return FALSE; } D(("day range = 0%o", marked_day)); time_start = 0; for (i=0; len > 0 && i < 4 && isdigit(times[i+j]); ++i, --len) { time_start *= 10; time_start += times[i+j]-'0'; /* is this portable? */ } j += i; if (times[j] == '-') { time_end = 0; for (i=1; len > 0 && i < 5 && isdigit(times[i+j]); ++i, --len) { time_end *= 10; time_end += times[i+j]-'0'; /* is this portable? */ } j += i; } else time_end = -1; D(("i=%d, time_end=%d, times[j]='%c'", i, time_end, times[j])); if (i != 5 || time_end == -1) { _log_err("no/bad times specified (rule #%d)", rule); return TRUE; } D(("times(%d to %d)", time_start,time_end)); D(("marked_day = 0%o", marked_day)); /* compare with the actual time now */ pass = FALSE; if (time_start < time_end) { /* start < end ? --> same day */ if ((at->day & marked_day) && (at->minute >= time_start) && (at->minute < time_end)) { D(("time is listed")); pass = TRUE; } } else { /* spans two days */ if ((at->day & marked_day) && (at->minute >= time_start)) { D(("caught on first day")); pass = TRUE; } else { marked_day <<= 1; marked_day |= (marked_day & 0200) ? 1:0; D(("next day = 0%o", marked_day)); if ((at->day & marked_day) && (at->minute <= time_end)) { D(("caught on second day")); pass = TRUE; } } } return (not ^ pass); }
// Send result from the render window thread to the main one. // Must always be called after receiveMessage(). void sendResult(bool result) { D("waiting to send result (%s)\n", result ? "success" : "failure"); mOut.send(result); D("result sent\n"); }
static int check_account(const char *service, const char *tty , const char *user) { int from=0,to=0,fd=-1; char *buffer=NULL; int count=0; TIME here_and_now; int retval=PAM_SUCCESS; gid_t *grps; int no_grps; /* * first we get the current list of groups - the application * will have previously done an initgroups(), or equivalent. */ D(("counting supplementary groups")); no_grps = getgroups(0, NULL); /* find the current number of groups */ if (no_grps > 0) { grps = calloc( blk_size(no_grps) , sizeof(gid_t) ); D(("copying current list into grps [%d big]",blk_size(no_grps))); (void) getgroups(no_grps, grps); #ifdef DEBUG { int z; for (z=0; z<no_grps; ++z) { D(("gid[%d]=%d", z, grps[z])); } } #endif } else { D(("no supplementary groups known")); no_grps = 0; grps = NULL; } here_and_now = time_now(); /* find current time */ /* parse the rules in the configuration file */ do { int good=TRUE; /* here we get the service name field */ fd = read_field(fd,&buffer,&from,&to); if (!buffer || !buffer[0]) { /* empty line .. ? */ continue; } ++count; D(("working on rule #%d",count)); good = logic_field(service, buffer, count, is_same); D(("with service: %s", good ? "passes":"fails" )); /* here we get the terminal name field */ fd = read_field(fd,&buffer,&from,&to); if (!buffer || !buffer[0]) { _log_err(PAM_GROUP_CONF "; no tty entry #%d", count); continue; } good &= logic_field(tty, buffer, count, is_same); D(("with tty: %s", good ? "passes":"fails" )); /* here we get the username field */ fd = read_field(fd,&buffer,&from,&to); if (!buffer || !buffer[0]) { _log_err(PAM_GROUP_CONF "; no user entry #%d", count); continue; } good &= logic_field(user, buffer, count, is_same); D(("with user: %s", good ? "passes":"fails" )); /* here we get the time field */ fd = read_field(fd,&buffer,&from,&to); if (!buffer || !buffer[0]) { _log_err(PAM_GROUP_CONF "; no time entry #%d", count); continue; } good &= logic_field(&here_and_now, buffer, count, check_time); D(("with time: %s", good ? "passes":"fails" )); fd = read_field(fd,&buffer,&from,&to); if (!buffer || !buffer[0]) { _log_err(PAM_GROUP_CONF "; no listed groups for rule #%d" , count); continue; } /* * so we have a list of groups, we need to turn it into * something to send to setgroups(2) */ if (good) { D(("adding %s to gid list", buffer)); good = mkgrplist(buffer, &grps, no_grps); if (good < 0) { no_grps = 0; } else { no_grps = good; } } /* check the line is terminated correctly */ fd = read_field(fd,&buffer,&from,&to); if (buffer && buffer[0]) { _log_err(PAM_GROUP_CONF "; poorly terminated rule #%d", count); } if (good > 0) { D(("rule #%d passed, added %d groups", count, good)); } else if (good < 0) { retval = PAM_BUF_ERR; } else { D(("rule #%d failed", count)); } } while (buffer); /* now set the groups for the user */ if (no_grps > 0) { int err; D(("trying to set %d groups", no_grps)); #ifdef DEBUG for (err=0; err<no_grps; ++err) { D(("gid[%d]=%d", err, grps[err])); } #endif if ((err = setgroups(no_grps, grps))) { D(("but couldn't set groups %d", err)); _log_err("unable to set the group membership for user (err=%d)" , err); retval = PAM_CRED_ERR; } } if (grps) { /* tidy up */ memset(grps, 0, sizeof(gid_t) * blk_size(no_grps)); _pam_drop(grps); no_grps = 0; } return retval; }
// Process the current message, and updates its |result| field. // Returns true on success, or false on failure. bool process() const { const RenderWindowMessage& msg = *this; FrameBuffer* fb; bool result = false; switch (msg.cmd) { case CMD_INITIALIZE: D("CMD_INITIALIZE w=%d h=%d\n", msg.init.width, msg.init.height); result = FrameBuffer::initialize(msg.init.width, msg.init.height, msg.init.useSubWindow); break; case CMD_FINALIZE: D("CMD_FINALIZE\n"); FrameBuffer::getFB()->finalize(); result = true; break; case CMD_SET_POST_CALLBACK: D("CMD_SET_POST_CALLBACK\n"); fb = FrameBuffer::getFB(); fb->setPostCallback(msg.set_post_callback.on_post, msg.set_post_callback.on_post_context); result = true; break; case CMD_SETUP_SUBWINDOW: D("CMD_SETUP_SUBWINDOW: parent=%p x=%d y=%d w=%d h=%d rotation=%f\n", (void*)msg.subwindow.parent, msg.subwindow.x, msg.subwindow.y, msg.subwindow.w, msg.subwindow.h, msg.subwindow.rotation); result = FrameBuffer::getFB()->setupSubWindow( msg.subwindow.parent, msg.subwindow.x, msg.subwindow.y, msg.subwindow.w, msg.subwindow.h, msg.subwindow.rotation); break; case CMD_REMOVE_SUBWINDOW: D("CMD_REMOVE_SUBWINDOW\n"); result = FrameBuffer::getFB()->removeSubWindow(); break; case CMD_SET_ROTATION: D("CMD_SET_ROTATION rotation=%f\n", msg.rotation); fb = FrameBuffer::getFB(); if (fb) { fb->setDisplayRotation(msg.rotation); result = true; } break; case CMD_REPAINT: D("CMD_REPAINT\n"); fb = FrameBuffer::getFB(); if (fb) { fb->repost(); result = true; } break; default: ; } return result; }
static int read_field(int fd, char **buf, int *from, int *to) { /* is buf set ? */ if (! *buf) { *buf = (char *) malloc(PAM_GROUP_BUFLEN); if (! *buf) { _log_err("out of memory"); return -1; } *from = *to = 0; fd = open(PAM_GROUP_CONF, O_RDONLY); } /* do we have a file open ? return error */ if (fd < 0 && *to <= 0) { _log_err( PAM_GROUP_CONF " not opened"); memset(*buf, 0, PAM_GROUP_BUFLEN); _pam_drop(*buf); return -1; } /* check if there was a newline last time */ if ((*to > *from) && (*to > 0) && ((*buf)[*from] == '\0')) { /* previous line ended */ (*from)++; (*buf)[0] = '\0'; return fd; } /* ready for more data: first shift the buffer's remaining data */ *to -= *from; shift_bytes(*buf, *from, *to); *from = 0; (*buf)[*to] = '\0'; while (fd >= 0 && *to < PAM_GROUP_BUFLEN) { int i; /* now try to fill the remainder of the buffer */ i = read(fd, *to + *buf, PAM_GROUP_BUFLEN - *to); if (i < 0) { _log_err("error reading " PAM_GROUP_CONF); return -1; } else if (!i) { close(fd); fd = -1; /* end of file reached */ } else *to += i; /* * contract the buffer. Delete any comments, and replace all * multiple spaces with single commas */ i = 0; #ifdef DEBUG_DUMP D(("buffer=<%s>",*buf)); #endif while (i < *to) { if ((*buf)[i] == ',') { int j; for (j=++i; j<*to && (*buf)[j] == ','; ++j); if (j!=i) { shift_bytes(i + (*buf), j-i, (*to) - j); *to -= j-i; } } switch ((*buf)[i]) { int j,c; case '#': for (j=i; j < *to && (c = (*buf)[j]) != '\n'; ++j); if (j >= *to) { (*buf)[*to = ++i] = '\0'; } else if (c == '\n') { shift_bytes(i + (*buf), j-i, (*to) - j); *to -= j-i; ++i; } else { _log_err("internal error in " __FILE__ " at line %d", __LINE__ ); return -1; } break; case '\\': if ((*buf)[i+1] == '\n') { shift_bytes(i + *buf, 2, *to - (i+2)); *to -= 2; } else { ++i; /* we don't escape non-newline characters */ } break; case '!': case ' ': case '\t': if ((*buf)[i] != '!') (*buf)[i] = ','; /* delete any trailing spaces */ for (j=++i; j < *to && ( (c = (*buf)[j]) == ' ' || c == '\t' ); ++j); shift_bytes(i + *buf, j-i, (*to)-j ); *to -= j-i; break; default: ++i; } } } (*buf)[*to] = '\0'; /* now return the next field (set the from/to markers) */ { int i; for (i=0; i<*to; ++i) { switch ((*buf)[i]) { case '#': case '\n': /* end of the line/file */ (*buf)[i] = '\0'; *from = i; return fd; case FIELD_SEPARATOR: /* end of the field */ (*buf)[i] = '\0'; *from = ++i; return fd; } } *from = i; (*buf)[*from] = '\0'; } if (*to <= 0) { D(("[end of text]")); *buf = NULL; } return fd; }
static int create_subprocess(const char *cmd, const char *arg0, const char *arg1, pid_t *pid) { #ifdef HAVE_WIN32_PROC D("create_subprocess(cmd=%s, arg0=%s, arg1=%s)\n", cmd, arg0, arg1); fprintf(stderr, "error: create_subprocess not implemented on Win32 (%s %s %s)\n", cmd, arg0, arg1); return -1; #else /* !HAVE_WIN32_PROC */ char *devname; int ptm; ptm = unix_open("/dev/ptmx", O_RDWR); // | O_NOCTTY); if(ptm < 0){ printf("[ cannot open /dev/ptmx - %s ]\n",strerror(errno)); return -1; } fcntl(ptm, F_SETFD, FD_CLOEXEC); if(grantpt(ptm) || unlockpt(ptm) || ((devname = (char*) ptsname(ptm)) == 0)){ printf("[ trouble with /dev/ptmx - %s ]\n", strerror(errno)); adb_close(ptm); return -1; } *pid = fork(); if(*pid < 0) { printf("- fork failed: %s -\n", strerror(errno)); adb_close(ptm); return -1; } if(*pid == 0){ int pts; setsid(); pts = unix_open(devname, O_RDWR); if(pts < 0) { fprintf(stderr, "child failed to open pseudo-term slave: %s\n", devname); exit(-1); } dup2(pts, 0); dup2(pts, 1); dup2(pts, 2); adb_close(pts); adb_close(ptm); // set OOM adjustment to zero char text[64]; snprintf(text, sizeof text, "/proc/%d/oom_adj", getpid()); int fd = adb_open(text, O_WRONLY); if (fd >= 0) { adb_write(fd, "0", 1); adb_close(fd); } else { D("adb: unable to open %s\n", text); } execl(cmd, cmd, arg0, arg1, NULL); fprintf(stderr, "- exec '%s' failed: %s (%d) -\n", cmd, strerror(errno), errno); exit(-1); } else { // Don't set child's OOM adjustment to zero. // Let the child do it itself, as sometimes the parent starts // running before the child has a /proc/pid/oom_adj. // """adb: unable to open /proc/644/oom_adj""" seen in some logs. return ptm; } #endif /* !HAVE_WIN32_PROC */ }
static _res_thread* _res_thread_get(void) { _res_thread* rt; pthread_once( &_res_once, _res_init_key ); rt = pthread_getspecific( _res_key ); if (rt != NULL) { /* We already have one thread-specific DNS state object. * Check the serial value for any changes to net.* properties */ D("%s: Called for tid=%d rt=%p rt->pi=%p rt->serial=%d", __FUNCTION__, gettid(), rt, rt->_pi, rt->_serial); if (rt->_pi == NULL) { /* The property wasn't created when _res_thread_get() was * called the last time. This should only happen very * early during the boot sequence. First, let's try to see if it * is here now. */ #if defined(PROPERTY_SYSTEM_SUPPORT) rt->_pi = (struct prop_info*) __system_property_find("net.change"); #endif if (rt->_pi == NULL) { /* Still nothing, return current state */ D("%s: exiting for tid=%d rt=%p since system property not found", __FUNCTION__, gettid(), rt); return rt; } } #if defined(PROPERTY_SYSTEM_SUPPORT) if (rt->_serial == __system_property_serial(rt->_pi)) { /* Nothing changed, so return the current state */ D("%s: tid=%d rt=%p nothing changed, returning", __FUNCTION__, gettid(), rt); return rt; } /* Update the recorded serial number, and go reset the state */ rt->_serial = __system_property_serial(rt->_pi); #endif goto RESET_STATE; } /* It is the first time this function is called in this thread, * we need to create a new thread-specific DNS resolver state. */ rt = _res_thread_alloc(); if (rt == NULL) { return NULL; } pthread_setspecific( _res_key, rt ); D("%s: tid=%d Created new DNS state rt=%p", __FUNCTION__, gettid(), rt); RESET_STATE: /* Reset the state, note that res_ninit() can now properly reset * an existing state without leaking memory. */ D("%s: tid=%d, rt=%p, resetting DNS state (options RES_INIT=%d)", __FUNCTION__, gettid(), rt, (rt->_nres->options & RES_INIT) != 0); if ( res_ninit( rt->_nres ) < 0 ) { /* This should not happen */ D("%s: tid=%d rt=%p, woot, res_ninit() returned < 0", __FUNCTION__, gettid(), rt); _res_thread_free(rt); pthread_setspecific( _res_key, NULL ); return NULL; } return rt; }
static void transport_registration_func(int _fd, unsigned ev, void *data) { tmsg m; adb_thread_t output_thread_ptr; adb_thread_t input_thread_ptr; int s[2]; atransport *t; if(!(ev & FDE_READ)) { return; } if(transport_read_action(_fd, &m)) { fatal_errno("cannot read transport registration socket"); } t = m.transport; if(m.action == 0){ D("transport: %s removing and free'ing %d\n", t->serial, t->transport_socket); /* IMPORTANT: the remove closes one half of the ** socket pair. The close closes the other half. */ fdevent_remove(&(t->transport_fde)); adb_close(t->fd); adb_mutex_lock(&transport_lock); t->next->prev = t->prev; t->prev->next = t->next; adb_mutex_unlock(&transport_lock); run_transport_disconnects(t); if (t->product) free(t->product); if (t->serial) free(t->serial); if (t->model) free(t->model); if (t->device) free(t->device); if (t->devpath) free(t->devpath); memset(t,0xee,sizeof(atransport)); free(t); update_transports(); return; } /* don't create transport threads for inaccessible devices */ if (t->connection_state != CS_NOPERM) { /* initial references are the two threads */ t->ref_count = 2; if(adb_socketpair(s)) { fatal_errno("cannot open transport socketpair"); } D("transport: %s (%d,%d) starting\n", t->serial, s[0], s[1]); t->transport_socket = s[0]; t->fd = s[1]; fdevent_install(&(t->transport_fde), t->transport_socket, transport_socket_events, t); fdevent_set(&(t->transport_fde), FDE_READ); if(adb_thread_create(&input_thread_ptr, input_thread, t)){ fatal_errno("cannot create input thread"); } if(adb_thread_create(&output_thread_ptr, output_thread, t)){ fatal_errno("cannot create output thread"); } } /* put us on the master device list */ adb_mutex_lock(&transport_lock); t->next = &transport_list; t->prev = transport_list.prev; t->next->prev = t; t->prev->next = t; adb_mutex_unlock(&transport_lock); t->disconnects.next = t->disconnects.prev = &t->disconnects; update_transports(); }