bool NoximGlobalTrafficTable::load(const char *fname) { // Open file ifstream fin(fname, ios::in); if (!fin) return false; // Initialize variables traffic_table.clear(); // Cycle reading file while (!fin.eof()) { char line[512]; fin.getline(line, sizeof(line) - 1); if (line[0] != '\0') { if (line[0] != '%') { int src, dst; // Mandatory float pir, por; int t_on, t_off, t_period; int t_use_lvp; int params = sscanf(line, "%d %d %d %f %f %d %d %d", &src, &dst, &t_use_lvp, &pir, &por, &t_on, &t_off, &t_period); if (params >= 2) { // Create a communication from the parameters read on the line NoximCommunication communication; // Mandatory fields communication.src = src; communication.dst = dst; // Use low voltage path if (params >= 3 && t_use_lvp == 1) communication.use_low_voltage_path = true; else communication.use_low_voltage_path = false; // Custom PIR if (params >= 4 && pir >= 0 && pir <= 1) communication.pir = pir; else communication.pir = NoximGlobalParams::packet_injection_rate; // Custom POR if (params >= 5 && por >= 0 && por <= 1) communication.por = por; else communication.por = communication.pir; // NoximGlobalParams::probability_of_retransmission; // Custom Ton if (params >= 6 && t_on >= 0) communication.t_on = t_on; else communication.t_on = 0; // Custom Toff if (params >= 7 && t_off >= 0) { assert(t_off > t_on); communication.t_off = t_off; } else communication.t_off = DEFAULT_RESET_TIME + NoximGlobalParams::simulation_time; // Custom Tperiod if (params >= 8 && t_period > 0) { assert(t_period > t_off); communication.t_period = t_period; } else communication.t_period = DEFAULT_RESET_TIME + NoximGlobalParams::simulation_time; // Add this communication to the vector of communications traffic_table.push_back(communication); } } } } return true; }
static void init_from_conf_file() { FILE *conf_file; char *line = NULL; #define LINEBUFLEN 256 char var[LINEBUFLEN]; char val[LINEBUFLEN]; size_t len = 0; ssize_t numread; int assigns; char default_icon_path[] = {"/rom/etc/icon.ico"}; #ifdef RTCONFIG_RALINK char default_wl_interface[] = {"ra0"}; #else char default_wl_interface[] = {"eth1"}; #endif /* Set default values for configuration options */ /* (avoid strdup() since it doesn't use xmalloc wrapper) */ g_icon_path = xmalloc(strlen(default_icon_path)+1); strcpy(g_icon_path,default_icon_path); /* Examine configuration file, if it exists */ conf_file = fopen("/rom/etc/lld2d.conf", "r"); if (conf_file == NULL) return; while ((numread = getline(&line, &len, conf_file)) != -1) { var[0] = val[0] = '\0'; assigns = sscanf(line, "%s = %s", var, val); if (assigns==2) { /* compare to each of the 2 allowed vars... */ if (!strcmp(var,"icon")) { char *path = NULL; char *cur = NULL; path = xmalloc(strlen(val)+6); // always allow enough room for a possible prefix of '/etc/' cur = path; /* Check for leading '/' and prefix '/etc/' if missing */ if (val[0] != '/') { strcpy(cur,"/etc/"); cur += 5; } strncpy(cur,val,strlen(val)); if (g_icon_path) xfree(g_icon_path); // always use the most recent occurrence g_icon_path = path; DEBUG({printf("configvar 'g_icon_path' = %s\n", g_icon_path);}) } else if (!strcmp(var,"jumbo-icon")) { char *path = NULL; char *cur = NULL; path = xmalloc(strlen(val)+6); // always allow enough room for a possible prefix of '/etc/' cur = path; /* Check for leading '/' and prefix '/etc/' if missing */ if (val[0] != '/') { strcpy(cur,"/etc/"); cur += 5; } strncpy(cur,val,strlen(val)); if (g_jumbo_icon_path) xfree(g_jumbo_icon_path); // always use the most recent occurrence g_jumbo_icon_path = path; DEBUG({printf("configvar 'g_jumbo_icon_path' = %s\n", g_jumbo_icon_path);}) } else if (!strcmp(var, "wl-interface")) { /* patch here for wireless interface config file, bobtseng 2007.9.7. */
network_connect(struct scpi_instrument *scpi) { struct sockaddr_in MyAddress, MyControlAddress; int status; struct timeval timeout; char buf[128]; timeout.tv_sec = SOCKETS_TIMEOUT; timeout.tv_usec = 0; /* Create socket (allocate resources) - IPv4, TCP */ scpi->main_socket = socket(PF_INET, SOCK_STREAM, 0); if (scpi->main_socket == -1) { printf("Error: Unable to create socket (%i)...\n",errno); return -1; } /* set Recieve and Transmit Timeout, so connect doesn't take so long to fail */ status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)); if (status < 0) perror("setsockopt failed\n"); status = setsockopt(scpi->main_socket, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout,sizeof(timeout)); if (status < 0) perror("setsockopt failed\n"); /* Establish TCP connection */ memset(&MyAddress,0,sizeof(struct sockaddr_in)); MyAddress.sin_family = PF_INET; MyAddress.sin_port = htons(scpi->main_port); MyAddress.sin_addr.s_addr = inet_addr(scpi->ip_address); status = connect(scpi->main_socket, (struct sockaddr *)&MyAddress, sizeof(struct sockaddr_in)); if(status == -1) { printf("Error: Unable to establish connection to ip:%s (%i)...\n", scpi->ip_address, errno); return -1; } /* Minimize latency by setting TCP_NODELAY option */ network_setnodelay(scpi->main_socket); /* Ask for control port */ sprintf(buf, "SYST:COMM:TCPIP:CONTROL?\n"); status = send(scpi->main_socket, buf, strlen(buf), 0); if (status == -1) return -1; if (scpi_network_read((scpi)) == 0) { scpi->control_socket = scpi->main_socket; return 0; } sscanf(scpi->response, "%" SCNd16, &scpi->control_port); /* Create socket for control port */ scpi->control_socket = socket(PF_INET, SOCK_STREAM, 0); if(scpi->control_socket == -1) { printf("Error: Unable to create control port socket (%i)...\n",errno); return -1; } /* Establish TCP connection to control port */ memset(&MyControlAddress, 0, sizeof(struct sockaddr_in)); MyControlAddress.sin_family = PF_INET; MyControlAddress.sin_port = htons(scpi->control_port); MyControlAddress.sin_addr.s_addr = inet_addr(scpi->ip_address); status = connect(scpi->control_socket, (struct sockaddr *) &MyControlAddress, sizeof(struct sockaddr_in)); if(status == -1) { printf("Error: Unable to establish connection to control port (%i)...\n", errno); return -1; } return 0; }
/** * Process counter data and dispatch values */ static int node_handler_fetch_data(void *arg, const char *val, const char *key) { value_t uv; double tmp_d; uint64_t tmp_u; struct values_tmp *vtmp = (struct values_tmp*) arg; uint32_t type = DSET_TYPE_UNFOUND; int index = vtmp->index; char ds_name[DATA_MAX_NAME_LEN]; memset(ds_name, 0, sizeof(ds_name)); if(parse_keys(key, ds_name)) { return 1; } if(index >= vtmp->d->ds_num) { //don't overflow bounds of array index = (vtmp->d->ds_num - 1); } /** * counters should remain in same order we parsed schema... we maintain the * index variable to keep track of current point in list of counters. first * use index to guess point in array for retrieving type. if that doesn't * work, use the old way to get the counter type */ if(strcmp(ds_name, vtmp->d->ds_names[index]) == 0) { //found match type = vtmp->d->ds_types[index]; } else if((index > 0) && (strcmp(ds_name, vtmp->d->ds_names[index-1]) == 0)) { //try previous key type = vtmp->d->ds_types[index-1]; } if(type == DSET_TYPE_UNFOUND) { //couldn't find right type by guessing, check the old way type = backup_search_for_type(vtmp->d, ds_name); } switch(type) { case DSET_LATENCY: if(vtmp->avgcount_exists == -1) { sscanf(val, "%" PRIu64, &vtmp->avgcount); vtmp->avgcount_exists = 0; //return after saving avgcount - don't dispatch value //until latency calculation return 0; } else { double sum, result; sscanf(val, "%lf", &sum); if(vtmp->avgcount == 0) { vtmp->avgcount = 1; } /** User wants latency values as long run avg */ if(long_run_latency_avg) { result = (sum / vtmp->avgcount); } else { result = get_last_avg(vtmp->d, ds_name, vtmp->latency_index, sum, vtmp->avgcount); if(result == -ENOMEM) { return -ENOMEM; } } uv.gauge = result; vtmp->avgcount_exists = -1; vtmp->latency_index = (vtmp->latency_index + 1); } break; case DSET_BYTES: sscanf(val, "%lf", &tmp_d); uv.gauge = tmp_d; break; case DSET_RATE: sscanf(val, "%" PRIu64, &tmp_u); uv.derive = tmp_u; break; case DSET_TYPE_UNFOUND: default: ERROR("ceph plugin: ds %s was not properly initialized.", ds_name); return -1; } sstrncpy(vtmp->vlist.type, ceph_dset_types[type], sizeof(vtmp->vlist.type)); sstrncpy(vtmp->vlist.type_instance, ds_name, sizeof(vtmp->vlist.type_instance)); vtmp->vlist.values = &uv; vtmp->vlist.values_len = 1; vtmp->index = (vtmp->index + 1); plugin_dispatch_values(&vtmp->vlist); return 0; }
/***************************************************************************** *Name : *Description :receive testcase num from echo command *Parameter : *Return : *Note : *****************************************************************************/ static ssize_t nand_test_store(struct kobject *kobject,struct attribute *attr, const char *buf, size_t count) { int ret; int argnum = 0; char cmd[32] = {0}; unsigned int param0 = 0; unsigned int param1 = 0; unsigned int param2 = 0; struct nand_kobject* nand_kobj; nand_kobj = (struct nand_kobject*)kobject; argnum = sscanf(buf, "%s %u %u %u ", cmd, ¶m0, ¶m1, ¶m2); printk("argnum=%i, cmd=%s, param0=%u, param1=%u, param2=%u\n", argnum, cmd, param0, param1, param2); if (-1 == argnum) { printk("cmd format err!"); goto NAND_TEST_STORE_EXIT; } if(strcmp(cmd,"help") == 0) { printk("nand debug cmd:\n"); printk(" help \n"); } else if(strcmp(cmd,"flush") == 0) { printk("nand debug cmd:\n"); printk(" flush \n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = nand_kobj->nftl_blk->flush_write_cache(nand_kobj->nftl_blk,param0); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"gcall") == 0) { printk("nand debug cmd:\n"); printk(" gcall \n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = gc_all(nand_kobj->nftl_blk->nftl_zone); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"gcone") == 0) { printk("nand debug cmd:\n"); printk(" gcone \n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = gc_one(nand_kobj->nftl_blk->nftl_zone); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"test") == 0) { printk("nand debug cmd:\n"); printk(" test \n"); mutex_lock(nand_kobj->nftl_blk->blk_lock); ret = nftl_set_zone_test((void*)nand_kobj->nftl_blk->nftl_zone,param0); mutex_unlock(nand_kobj->nftl_blk->blk_lock); goto NAND_TEST_STORE_EXIT; } else if(strcmp(cmd,"showall") == 0) { printk("nand debug cmd:\n"); printk(" show all \n"); print_free_list(nand_kobj->nftl_blk->nftl_zone); print_block_invalid_list(nand_kobj->nftl_blk->nftl_zone); print_nftl_zone(nand_kobj->nftl_blk->nftl_zone); goto NAND_TEST_STORE_EXIT; } else { printk("err, nand debug undefined cmd: %s\n", cmd); } NAND_TEST_STORE_EXIT: return count; }
int main(int argc, char *argv[]) { int k, i, j, x, y; int A[5][5]; seq seq1 = {o, a, a, a, b, a}; seq seq2 = {o, b, a, a, b, a}; if(argc != 2 || (sscanf(argv[1], "%d", &k)) != 1) { printf("\tBitte Syntax beachten: ./afg41 <Substringlaenge>\n"); exit(EXIT_FAILURE); } printf("\n"); for(i = 1; i <= 6 - k; i++){ for(j = 1; j <= 6 - k; j++){ printf("\tmc("); for(x = k; x > 0; x--) { printf("%c", seq1[i+(k-x)]); if(x == 1) { printf(", "); } } for(y = k; y > 0; y--) { printf("%c", seq2[j+(k-y)]); if(y == 1) { printf(")\n"); } } } } for(j = 0; j < 6; j++) { printf("\n"); for(i = 0; i < 6; i++) { if((i == 0) || (j == 0)) { A[i][j] = 0; } else { A[i][j] = A[i-1][j-1]; if(seq1[i] == seq2[j]) { A[i][j] += 1; } } printf("\t%d", A[i][j]); } } printf("\n\n"); for(i = 1; i <= 6 - k; i++){ for(j = 1; j <= 6 - k; j++){ printf("\tmc("); for(x = k; x > 0; x--) { printf("%c", seq1[i+(k-x)]); if(x == 1) { printf(", "); } } for(y = k; y > 0; y--) { printf("%c", seq2[j+(k-y)]); if(y == 1) { printf(") = %d\n", (A[i+(k-1)][j+(k-1)] - A[i-1][j-1])); } } } } printf("\n"); return(EXIT_SUCCESS); }
void process_input(int* needs_refresh, const char *str, int fd, void (*cb)(int fd, const char *data, size_t len)) { static unsigned lcore_id, task_id, nb_packets, val, id, port, queue, rate, ip[4], prefix, next_hop_idx, interface, gre_id, svlan, cvlan, mac[6], user; unsigned count; float speed; uint32_t pkt_size; static char mode[20]; struct rte_ring *ring; unsigned short offset; uint32_t value; uint8_t value_len; if (strcmp(str, "quit") == 0) { plog_info("Leaving...\n"); stop_core_all(); stop_dppd = 1; } else if (sscanf(str, "dump %u %u %u", &lcore_id, &task_id, &nb_packets) == 3) { if (lcore_id >= RTE_MAX_LCORE) { plog_err("Invalid core id %u (lcore ID above %d)\n", lcore_id, RTE_MAX_LCORE); } else if (!dppd_core_active(lcore_id, 0)) { plog_err("Invalid core id %u (lcore is not active)\n", lcore_id); } else { cmd_dump(lcore_id, task_id, nb_packets); } } else if (sscanf(str, "rate %u %u %u", &queue, &port, &rate) == 3) { if (port > DPPD_MAX_PORTS) { plog_err("Max port id allowed is %u (specified %u)\n", DPPD_MAX_PORTS, port); } else if (!dppd_port_cfg[port].active) { plog_err("Port %u not active\n", port); } else if (queue >= dppd_port_cfg[port].n_txq) { plog_err("Number of active queues is %u\n", dppd_port_cfg[port].n_txq); } else if (rate > dppd_port_cfg[port].link_speed) { plog_err("Max rate allowed on port %u queue %u is %u Mbps\n", port, queue, dppd_port_cfg[port].link_speed); } else { if (rate == 0) { plog_info("Disabling rate limiting on port %u queue %u\n", port, queue); } else { plog_info("Setting rate limiting to %u Mbps on port %u queue %u\n", rate, port, queue); } rte_eth_set_queue_rate_limit(port, queue, rate); } } else if (sscanf(str, "count %u %u %u", &lcore_id, &task_id, &count) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else { ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->pkt_count = count; plog_info("Core %u task %u stopping after %u packets\n", lcore_id, task_id, count); } } } else if (sscanf(str, "pkt_size %u %u %d", &lcore_id, &task_id, &pkt_size) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else if (pkt_size > 1514 || pkt_size < 34) { // 34 for 14 + 20 (MAC, EtherType and IP) plog_err("pkt_size out of range (must be betweeen 34 and 1514)\n"); } else { ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->pkt_size = pkt_size; plog_info("Setting pkt_size to %u \n", pkt_size); } } } else if (sscanf(str, "speed %u %u %f", &lcore_id, &task_id, &speed) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else if (speed > 100.0f || speed < 0.0f) { plog_err("Speed out of range (must be betweeen 0%% and 100%%)\n"); } else { uint64_t bps = speed * 12500000; ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->rate_bps = bps; plog_info("Setting rate to %"PRIu64" Bps\n", bps); } } } else if (sscanf(str, "speed_byte %u %u %u", &lcore_id, &task_id, &value) == 3) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else if (value > 1250000000) { plog_err("Speed out of range (must be <= 1250000000)\n"); } else { ((struct task_gen *)lcore_cfg[lcore_id].task[task_id])->rate_bps = value; plog_info("Setting rate to %"PRIu32" Bps\n", value); } } } else if (strcmp(str, "reset values all") == 0) { lcore_id = -1; while (dppd_core_next(&lcore_id, 0) == 0) { for (task_id = 0; task_id < lcore_cfg[lcore_id].nb_tasks; task_id++) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen") == 0) { struct task_gen *task = ((struct task_gen *)lcore_cfg[lcore_id].task[task_id]); plog_info("Resetting values on core %d task %d from %d values\n", lcore_id, task_id, task->n_values); task->n_values = 0; } } } } else if (sscanf(str, "reset values %u %u", &lcore_id, &task_id) == 2) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else { struct task_gen *task = ((struct task_gen *)lcore_cfg[lcore_id].task[task_id]); plog_info("Resetting values on core %d task %d from %d values\n", lcore_id, task_id, task->n_values); task->n_values = 0; } } } else if (sscanf(str, "set value %u %u %hu %u %hhu", &lcore_id, &task_id, &offset, &value, &value_len) == 5) { if (check_core_task(lcore_id, task_id)) { if (strcmp(lcore_cfg[lcore_id].targs[task_id].task_init->mode_str, "gen")) { plog_err("Core %u task %u is not generating packets\n", lcore_id, task_id); } else if (offset > ETHER_MAX_LEN) { plog_err("Offset out of range (must be less then %u)\n", ETHER_MAX_LEN); } else if (value_len > 4) { plog_err("Length out of range (must be less then 4)\n"); } else { struct task_gen *task = ((struct task_gen *)lcore_cfg[lcore_id].task[task_id]); if (task->n_values >= 64) { plog_info("Unable to set Byte %"PRIu16" to %"PRIu8" - too many value set\n", offset, value); } else { task->value[task->n_values] = rte_cpu_to_be_32(value) >> ((4 - value_len) * 8); task->offset[task->n_values] = offset; task->value_len[task->n_values] = value_len; task->n_values++; plog_info("Setting Byte %"PRIu16" to %"PRIu32"\n", offset, value); } } } } else if (sscanf(str, "thread info %u %u", &lcore_id, &task_id) == 2) {
/** Get a value (object, clock, or global) \verbatim gl('get',name) \endverbatim **/ void cmex_get(int nlhs, mxArray *plhs[], /**< {data} */ int nrhs, const mxArray *prhs[] ) /**< (name) */ { if (nrhs>0) { char name[1024]; OBJECT *obj=NULL; if (!mxIsChar(prhs[0])) output_error("entity name (arg 1) is not a string"); else if (nlhs>1) output_error("only one return value is possible"); else if (mxGetString(prhs[0],name,sizeof(name))!=0) output_error("object name too long"); else if (strcmp(name,"clock")==0) { char *fnames[] = {"timestamp","timestring","timezone"}; char buffer[256]; mxArray *pTimestamp = mxCreateDoubleMatrix(1,1,mxREAL); mxArray *pTimestring = mxCreateString(convert_from_timestamp(global_clock,buffer,sizeof(buffer))?buffer:"(error)"); mxArray *pTimezone = mxCreateString(timestamp_current_timezone()); *(double*)mxGetPr(pTimestamp) = ((double)global_clock)/TS_SECOND; plhs[0] = mxCreateStructMatrix(1,1,sizeof(fnames)/sizeof(fnames[0]),fnames); mxSetFieldByNumber(plhs[0],0,0,pTimestamp); mxSetFieldByNumber(plhs[0],0,1,pTimestring); mxSetFieldByNumber(plhs[0],0,2,pTimezone); } else if (strcmp(name,"property")==0 && nrhs>1) { if (mxGetString(prhs[1],name,sizeof(name))!=0) output_error("missing property name"); else { char classname[256]; char propname[256]; if (sscanf(name,"%[^.].%s",classname,propname)==2) { CLASS *pClass = class_get_class_from_classname(classname); if (pClass) { PROPERTY *pProp = class_find_property(pClass,propname); if (pProp) { char *fields[] = {"class","name","type","size","access","unit","delegation","keywords"}; int fn = 0; mxArray *oclass = mxCreateString(classname); mxArray *prop = mxCreateString(pProp->name); mxArray *type = mxCreateString(class_get_property_typename(pProp->ptype)); mxArray *size = mxCreateDoubleMatrix(1,1,mxREAL); mxArray *access = mxCreateString("(na)"); /** @todo implement get_property access info (ticket #187) */ mxArray *unit = mxCreateString(pProp->unit->name); mxArray *delegation = mxCreateString(pProp->delegation?pProp->delegation->oclass->name:"(none)"); mxArray *keywords = mxCreateString("(na)"); /** @todo implement get_property keywords (ticket #188) */ *(mxGetPr(size)) = pProp->size==0?1:pProp->size; plhs[0] = mxCreateStructMatrix(1,1,sizeof(fields)/sizeof(fields[0]),fields); mxSetFieldByNumber(plhs[0],0,fn++,oclass); mxSetFieldByNumber(plhs[0],0,fn++,prop); mxSetFieldByNumber(plhs[0],0,fn++,type); mxSetFieldByNumber(plhs[0],0,fn++,size); mxSetFieldByNumber(plhs[0],0,fn++,access); mxSetFieldByNumber(plhs[0],0,fn++,unit); mxSetFieldByNumber(plhs[0],0,fn++,delegation); mxSetFieldByNumber(plhs[0],0,fn++,keywords); } else output_error("property %s is not found in class %s", propname,classname); } else output_error("class %s is not found"); } else output_error("property name not in class.name format"); } } else if ((convert_to_object(name,&obj,NULL))==0) { GLOBALVAR *var = global_find(name); if (var==NULL) output_error("entity '%s' not found", name); else if (var->prop->ptype==PT_double) { size_t size = var->prop->size?var->prop->size:1; plhs[0] = mxCreateDoubleMatrix(size,1,mxREAL); memcpy(mxGetPr(plhs[0]),(void*)var->prop->addr,sizeof(double)*size); } else if (var->prop->ptype==PT_int32) { size_t size = var->prop->size?var->prop->size:1; plhs[0] = mxCreateDoubleMatrix(size,1,mxREAL); memcpy(mxGetPr(plhs[0]),(void*)var->prop->addr,sizeof(double)*size); } else if (var->prop->ptype!=PT_double) output_error("cannot retrieve globals that are of type %s",class_get_property_typename(var->prop->ptype)); } else if ((plhs[0]=get_object_data(obj))==NULL) output_error("unable to extract %s data", name); } else output_error("object not specified"); return; }
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; #ifdef WORKAROUND_BUG6558362 if(is_daemon) adb_set_affinity(); #endif 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, 0)) { 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()) { drop_capabilities_bounding_set_if_needed(); /* 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_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_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); } 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, 0)) { 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"); init_jdwp(); D("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"); fdevent_loop(); usb_cleanup(); return 0; }
// FOR SYNCED MESSAGES void CGame::ActionReceived(const Action& action, int playernum) { if (action.command == "cheat") { SetBoolArg(gs->cheatEnabled, action.extra); if (gs->cheatEnabled) logOutput.Print("Cheating!"); else logOutput.Print("No more cheating"); } else if (action.command == "nohelp") { SetBoolArg(gs->noHelperAIs, action.extra); selectedUnits.PossibleCommandChange(NULL); logOutput.Print("LuaUI control is %s", gs->noHelperAIs ? "disabled" : "enabled"); } else if (action.command == "nospecdraw") { bool buf; SetBoolArg(buf, action.extra); inMapDrawer->SetSpecMapDrawingAllowed(buf); } else if (action.command == "godmode") { if (!gs->cheatEnabled) logOutput.Print("godmode requires /cheat"); else { SetBoolArg(gs->godMode, action.extra); CLuaUI::UpdateTeams(); if (gs->godMode) { logOutput.Print("God Mode Enabled"); } else { logOutput.Print("God Mode Disabled"); } CPlayer::UpdateControlledTeams(); } } else if (action.command == "globallos") { if (!gs->cheatEnabled) { logOutput.Print("globallos requires /cheat"); } else { SetBoolArg(gs->globalLOS, action.extra); if (gs->globalLOS) { logOutput.Print("Global LOS Enabled"); } else { logOutput.Print("Global LOS Disabled"); } } } else if (action.command == "nocost" && gs->cheatEnabled) { if (unitDefHandler->ToggleNoCost()) { logOutput.Print("Everything is for free!"); } else { logOutput.Print("Everything costs resources again!"); } } else if (action.command == "give" && gs->cheatEnabled) { std::string s = "give "; //FIXME lazyness s += action.extra; // .give [amount] <unitName> [team] <@x,y,z> const vector<string> &args = CSimpleParser::Tokenize(s, 0); if (args.size() < 3) { logOutput.Print("Someone is spoofing invalid .give messages!"); return; } float3 pos; if (sscanf(args[args.size() - 1].c_str(), "@%f,%f,%f", &pos.x, &pos.y, &pos.z) != 3) { logOutput.Print("Someone is spoofing invalid .give messages!"); return; } int amount = 1; int team = playerHandler->Player(playernum)->team; int allyteam = -1; int amountArgIdx = -1; int teamArgIdx = -1; if (args.size() == 5) { amountArgIdx = 1; teamArgIdx = 3; } else if (args.size() == 4) { if (args[1].find_first_not_of("0123456789") == string::npos) { amountArgIdx = 1; } else { teamArgIdx = 2; } } if (amountArgIdx >= 0) { const string& amountStr = args[amountArgIdx]; amount = atoi(amountStr.c_str()); if ((amount < 0) || (amountStr.find_first_not_of("0123456789") != string::npos)) { logOutput.Print("Bad give amount: %s", amountStr.c_str()); return; } } if (teamArgIdx >= 0) { const string& teamStr = args[teamArgIdx]; team = atoi(teamStr.c_str()); if ((team < 0) || (team >= teamHandler->ActiveTeams()) || (teamStr.find_first_not_of("0123456789") != string::npos)) { logOutput.Print("Bad give team: %s", teamStr.c_str()); return; } } const string unitName = (amountArgIdx >= 0) ? args[2] : args[1]; if (unitName == "all") { // player entered ".give all" int numRequestedUnits = unitDefHandler->unitDefs.size() - 1; /// defid=0 is not valid int currentNumUnits = teamHandler->Team(team)->units.size(); int sqSize = (int) streflop::ceil(streflop::sqrt((float) numRequestedUnits)); // make sure team unit-limit not exceeded if ((currentNumUnits + numRequestedUnits) > uh->MaxUnitsPerTeam()) { numRequestedUnits = uh->MaxUnitsPerTeam() - currentNumUnits; } // make sure square is entirely on the map float sqHalfMapSize = sqSize / 2 * 10 * SQUARE_SIZE; pos.x = std::max(sqHalfMapSize, std::min(pos.x, float3::maxxpos - sqHalfMapSize - 1)); pos.z = std::max(sqHalfMapSize, std::min(pos.z, float3::maxzpos - sqHalfMapSize - 1)); for (int a = 1; a <= numRequestedUnits; ++a) { float posx = pos.x + (a % sqSize - sqSize / 2) * 10 * SQUARE_SIZE; float posz = pos.z + (a / sqSize - sqSize / 2) * 10 * SQUARE_SIZE; float3 pos2 = float3(posx, pos.y, posz); const UnitDef* ud = unitDefHandler->GetUnitDefByID(a); if (ud) { const CUnit* unit = unitLoader.LoadUnit(ud, pos2, team, false, 0, NULL); if (unit) { unitLoader.FlattenGround(unit); } } } } else if (!unitName.empty()) { int numRequestedUnits = amount; int currentNumUnits = teamHandler->Team(team)->units.size(); if (currentNumUnits >= uh->MaxUnitsPerTeam()) { LogObject() << "Unable to give any more units to team " << team << "(current: " << currentNumUnits << ", max: " << uh->MaxUnits() << ")"; return; } // make sure team unit-limit is not exceeded if ((currentNumUnits + numRequestedUnits) > uh->MaxUnitsPerTeam()) { numRequestedUnits = uh->MaxUnitsPerTeam() - currentNumUnits; } const UnitDef* unitDef = unitDefHandler->GetUnitDefByName(unitName); if (unitDef != NULL) { int xsize = unitDef->xsize; int zsize = unitDef->zsize; int squareSize = (int) streflop::ceil(streflop::sqrt((float) numRequestedUnits)); int total = numRequestedUnits; float3 minpos = pos; minpos.x -= ((squareSize - 1) * xsize * SQUARE_SIZE) / 2; minpos.z -= ((squareSize - 1) * zsize * SQUARE_SIZE) / 2; for (int z = 0; z < squareSize; ++z) { for (int x = 0; x < squareSize && total > 0; ++x) { float minposx = minpos.x + x * xsize * SQUARE_SIZE; float minposz = minpos.z + z * zsize * SQUARE_SIZE; const float3 upos(minposx, minpos.y, minposz); const CUnit* unit = unitLoader.LoadUnit(unitDef, upos, team, false, 0, NULL); if (unit) { unitLoader.FlattenGround(unit); } --total; } } logOutput.Print("Giving %i %s to team %i", numRequestedUnits, unitName.c_str(), team); } else { if (teamArgIdx < 0) { team = -1; // default to world features allyteam = -1; } else { allyteam = teamHandler->AllyTeam(team); } const FeatureDef* featureDef = featureHandler->GetFeatureDef(unitName); if (featureDef) { int xsize = featureDef->xsize; int zsize = featureDef->zsize; int squareSize = (int) streflop::ceil(streflop::sqrt((float) numRequestedUnits)); int total = amount; // FIXME -- feature count limit? float3 minpos = pos; minpos.x -= ((squareSize - 1) * xsize * SQUARE_SIZE) / 2; minpos.z -= ((squareSize - 1) * zsize * SQUARE_SIZE) / 2; for (int z = 0; z < squareSize; ++z) { for (int x = 0; x < squareSize && total > 0; ++x) { float minposx = minpos.x + x * xsize * SQUARE_SIZE; float minposz = minpos.z + z * zsize * SQUARE_SIZE; float minposy = ground->GetHeight2(minposx, minposz); const float3 upos(minposx, minposy, minposz); CFeature* feature = new CFeature(); feature->Initialize(upos, featureDef, 0, 0, team, allyteam, ""); --total; } } logOutput.Print("Giving %i %s (feature) to team %i", numRequestedUnits, unitName.c_str(), team); } else { logOutput.Print(unitName + " is not a valid unitname"); } } } } else if (action.command == "destroy" && gs->cheatEnabled) { std::stringstream ss(action.extra); logOutput.Print("Killing units: %s", action.extra.c_str()); do { unsigned id; ss >> id; if (!ss) break; if (id >= uh->units.size()) continue; if (uh->units[id] == NULL) continue; uh->units[id]->KillUnit(false, false, 0); } while (true); }
void http_do_requests(GF_DownloadSession *sess) { GF_Err e; Bool is_ice; GF_NETIO_Parameter par; char sHTTP[GF_DOWNLOAD_BUFFER_SIZE]; char buf[1024]; char comp[400]; char *new_location; char *hdr, *hdr_val; u32 bytesRead, res; s32 LinePos, Pos; u32 rsp_code, ContentLength, first_byte, last_byte, total_size, range, no_range; s32 BodyStart; /*sent HTTP request*/ if (sess->status==GF_NETIO_CONNECTED) { char range_buf[1024]; char pass_buf[1024]; const char *user_agent; u32 size; Bool has_accept, has_connection, has_range, has_agent; /*setup authentification*/ strcpy(pass_buf, ""); if (sess->user) { if (!sess->passwd) { char szUSR[50], szPASS[50]; strcpy(szUSR, sess->user); strcpy(szPASS, ""); /*failed getting pass*/ if (!sess->dm->GetUserPassword || !sess->dm->GetUserPassword(sess->dm->usr_cbk, sess->server_name, szUSR, szPASS)) { sess->status = GF_NETIO_STATE_ERROR; return; } sess->passwd = strdup(szPASS); } sprintf(pass_buf, "%s:%s", sess->user, sess->passwd); size = gf_base64_encode(pass_buf, strlen(pass_buf), range_buf, 1024); range_buf[size] = 0; sprintf(pass_buf, "Authorization: Basic %s", range_buf); } /*MIX2005 KMS project*/ #if 0 if (strstr(sess->remote_path, "getKey.php?")) { char *sLogin, *sPass; sLogin = gf_cfg_get_key(sess->dm->cfg, "General", "KMS_User"); sPass = gf_cfg_get_key(sess->dm->cfg, "General", "KMS_Password"); if (!sLogin) sLogin = "******"; if (!sPass) sPass = "******"; sprintf(https_get_buffer, "%s&login=%s&password=%s", sess->remote_path, sLogin, sPass); } #endif user_agent = gf_cfg_get_key(sess->dm->cfg, "Downloader", "UserAgent"); if (!user_agent) user_agent = GF_DOWNLOAD_AGENT_NAME; par.error = 0; par.msg_type = GF_NETIO_GET_METHOD; par.name = NULL; gf_dm_sess_user_io(sess, &par); if (par.name) { if (!strcmp(par.name, "GET")) sess->http_read_type = 0; else if (!strcmp(par.name, "HEAD")) sess->http_read_type = 1; else sess->http_read_type = 2; } else { sess->http_read_type = 0; } sprintf(sHTTP, "%s %s HTTP/1.0\r\nHost: %s\r\n" , par.name ? par.name : "GET", sess->remote_path, sess->server_name); /*signal we support title streaming*/ if (!strcmp(sess->remote_path, "/")) strcat(sHTTP, "icy-metadata:1\r\n"); /*get all headers*/ has_agent = has_accept = has_connection = has_range = 0; while (1) { par.msg_type = GF_NETIO_GET_HEADER; par.name = NULL; par.value = NULL; gf_dm_sess_user_io(sess, &par); if (!par.name) break; strcat(sHTTP, par.name); strcat(sHTTP, ": "); strcat(sHTTP, par.value); strcat(sHTTP, "\r\n"); if (!strcmp(par.name, "Accept")) has_accept = 1; else if (!strcmp(par.name, "Connection")) has_connection = 1; else if (!strcmp(par.name, "Range")) has_range = 1; else if (!strcmp(par.name, "User-Agent")) has_agent = 1; } if (!has_agent) { strcat(sHTTP, "User-Agent: "); strcat(sHTTP, user_agent); strcat(sHTTP, "\r\n"); } if (!has_accept) strcat(sHTTP, "Accept: */*\r\n"); if (!has_connection) strcat(sHTTP, "Connection: Keep-Alive\r\n"); if (!has_range && sess->cache_start_size) { sprintf(range_buf, "Range: bytes=%d-\r\n", sess->cache_start_size); strcat(sHTTP, range_buf); } if (strlen(pass_buf)) { strcat(sHTTP, pass_buf); strcat(sHTTP, "\r\n"); } if (sess->flags & GF_DOWNLOAD_IS_ICY) strcat(sHTTP, "Icy-Metadata: 1\r\n"); par.msg_type = GF_NETIO_GET_CONTENT; par.data = NULL; par.size = 0; gf_dm_sess_user_io(sess, &par); if (par.data && par.size) { sprintf(range_buf, "Content-Length: %d\r\n", par.size); strcat(sHTTP, range_buf); } strcat(sHTTP, "\r\n"); #ifdef GPAC_HAS_SSL if (sess->ssl) { e = GF_IP_NETWORK_FAILURE; if (!SSL_write(sess->ssl, sHTTP, strlen(sHTTP))) e = GF_OK; } else #endif e = gf_sk_send(sess->sock, sHTTP, strlen(sHTTP)); GF_LOG(GF_LOG_DEBUG, GF_LOG_NETWORK, ("[HTTP] %s\n\n", sHTTP)); if (e) { sess->status = GF_NETIO_STATE_ERROR; sess->last_error = e; gf_dm_sess_notify_state(sess, GF_NETIO_STATE_ERROR, e); return; } if (par.size && par.data) { u32 done = 0; while (done<par.size) { #ifdef GPAC_HAS_SSL if (sess->ssl) { e = GF_IP_NETWORK_FAILURE; if (!SSL_write(sess->ssl, par.data+done, par.size-done)) e = GF_OK; } else #endif e = gf_sk_send(sess->sock, par.data+done, par.size-done); if (e) { sess->status = GF_NETIO_STATE_ERROR; sess->last_error = e; gf_dm_sess_notify_state(sess, GF_NETIO_STATE_ERROR, e); return; } } } sess->status = GF_NETIO_WAIT_FOR_REPLY; gf_dm_sess_notify_state(sess, GF_NETIO_WAIT_FOR_REPLY, GF_OK); return; } /*process HTTP request*/ if (sess->status == GF_NETIO_WAIT_FOR_REPLY) { bytesRead = res = 0; new_location = NULL; while (1) { e = gf_dm_read_data(sess, sHTTP + bytesRead, GF_DOWNLOAD_BUFFER_SIZE - bytesRead, &res); switch (e) { case GF_IP_NETWORK_EMPTY: if (!bytesRead) return; continue; /*socket has been closed while configuring, retry (not sure if the server got the GET)*/ case GF_IP_CONNECTION_CLOSED: gf_dm_disconnect(sess); if (sess->num_retry) sess->status = GF_NETIO_SETUP; else { sess->last_error = e; sess->status = GF_NETIO_STATE_ERROR; } return; case GF_OK: if (!res) return; break; default: goto exit; } bytesRead += res; /*locate body start*/ BodyStart = gf_token_find(sHTTP, 0, bytesRead, "\r\n\r\n"); if (BodyStart <= 0) { BodyStart=0; continue; } BodyStart += 4; break; } if (bytesRead < 0) { e = GF_REMOTE_SERVICE_ERROR; goto exit; } if (!BodyStart) BodyStart = bytesRead; sHTTP[BodyStart-1] = 0; GF_LOG(GF_LOG_DEBUG, GF_LOG_NETWORK, ("[HTTP] %s\n\n", sHTTP)); LinePos = gf_token_get_line(sHTTP, 0, bytesRead, buf, 1024); Pos = gf_token_get(buf, 0, " \t\r\n", comp, 400); if (sess->mime_type) free(sess->mime_type); sess->mime_type = NULL; is_ice = 0; if (!strncmp("ICY", comp, 4)) { is_ice = 1; /*be prepared not to recieve any mime type from ShoutCast servers*/ sess->mime_type = strdup("audio/mpeg"); } else if ((strncmp("HTTP", comp, 4) != 0)) { e = GF_REMOTE_SERVICE_ERROR; goto exit; } Pos = gf_token_get(buf, Pos, " ", comp, 400); if (Pos <= 0) { e = GF_REMOTE_SERVICE_ERROR; goto exit; } rsp_code = (u32) atoi(comp); Pos = gf_token_get(buf, Pos, " \r\n", comp, 400); no_range = range = ContentLength = first_byte = last_byte = total_size = 0; //parse header while (1) { char *sep, *hdr_sep; if ( (u32) LinePos + 4 > BodyStart) break; LinePos = gf_token_get_line(sHTTP, LinePos , bytesRead, buf, 1024); if (LinePos < 0) break; hdr_sep = NULL; hdr_val = NULL; hdr = buf; sep = strchr(buf, ':'); if (sep) { sep[0]=0; hdr_val = sep+1; while (hdr_val[0]==' ') hdr_val++; hdr_sep = strrchr(hdr_val, '\r'); if (hdr_sep) hdr_sep[0] = 0; } par.error = 0; par.msg_type = GF_NETIO_PARSE_HEADER; par.name = hdr; par.value = hdr_val; gf_dm_sess_user_io(sess, &par); if (!stricmp(hdr, "Content-Length") ) ContentLength = (u32) atoi(hdr_val); else if (!stricmp(hdr, "Content-Type")) { if (sess->mime_type) free(sess->mime_type); sess->mime_type = strdup(hdr_val); while (1) { u32 len = strlen(sess->mime_type); char c = len ? sess->mime_type[len-1] : 0; if ((c=='\r') || (c=='\n')) { sess->mime_type[len-1] = 0; } else { break; } } hdr = strchr(sess->mime_type, ';'); if (hdr) hdr[0] = 0; } else if (!stricmp(hdr, "Content-Range")) { range = 1; if (!strncmp(hdr_val, "bytes", 5)) { hdr_val += 5; if (hdr_val[0] == ':') hdr_val += 1; hdr_val += http_skip_space(hdr_val); if (hdr_val[0] == '*') { sscanf(hdr_val, "*/%d", &total_size); } else { sscanf(hdr_val, "%d-%d/%d", &first_byte, &last_byte, &total_size); } } } else if (!stricmp(hdr, "Accept-Ranges")) { if (strstr(hdr_val, "none")) no_range = 1; } else if (!stricmp(hdr, "Location")) new_location = strdup(hdr_val); else if (!stricmp(hdr, "icy-metaint")) sess->icy_metaint = atoi(hdr_val); else if (!stricmp(hdr, "ice") || !stricmp(hdr, "icy") ) is_ice = 1; if (sep) sep[0]=':'; if (hdr_sep) hdr_sep[0] = '\r'; } if (no_range) first_byte = 0; if (sess->cache_start_size) { if (total_size && (sess->cache_start_size >= total_size) ) { rsp_code = 200; ContentLength = total_size; } if (ContentLength && (sess->cache_start_size == ContentLength) ) rsp_code = 200; } par.msg_type = GF_NETIO_PARSE_REPLY; par.error = GF_OK; par.reply = rsp_code; par.value = comp; switch (rsp_code) { case 200: case 201: case 202: case 206: gf_dm_sess_user_io(sess, &par); e = GF_OK; break; /*redirection: extract the new location*/ case 301: case 302: if (!new_location || !strlen(new_location) ) { gf_dm_sess_user_io(sess, &par); e = GF_URL_ERROR; goto exit; } while ( (new_location[strlen(new_location)-1] == '\n') || (new_location[strlen(new_location)-1] == '\r') ) new_location[strlen(new_location)-1] = 0; /*reset and reconnect*/ gf_dm_disconnect(sess); sess->status = GF_NETIO_SETUP; e = gf_dm_setup_from_url(sess, new_location); if (e) { sess->status = GF_NETIO_STATE_ERROR; sess->last_error = e; gf_dm_sess_notify_state(sess, sess->status, e); return; } return; case 404: case 416: /*try without cache (some servers screw up when content-length is specified)*/ if (sess->cache_start_size) { gf_dm_disconnect(sess); sess->status = GF_NETIO_SETUP; return; } else if (is_ice && !(sess->flags & GF_DOWNLOAD_IS_ICY)) { gf_dm_disconnect(sess); sess->status = GF_NETIO_SETUP; sess->flags |= GF_DOWNLOAD_IS_ICY; return; } gf_dm_sess_user_io(sess, &par); e = GF_URL_ERROR; goto exit; case 503: default: gf_dm_sess_user_io(sess, &par); e = GF_REMOTE_SERVICE_ERROR; goto exit; } /*head*/ if (sess->http_read_type==1) { gf_dm_disconnect(sess); gf_dm_sess_notify_state(sess, GF_NETIO_DATA_TRANSFERED, GF_OK); sess->status = GF_NETIO_DISCONNECTED; sess->http_read_type = 0; return; } if (!ContentLength && sess->mime_type && strstr(sess->mime_type, "ogg")) is_ice = 1; /*some servers may reply without content length, but we MUST have it*/ // if (!is_ice && !ContentLength) e = GF_REMOTE_SERVICE_ERROR; if (e) goto exit; /*force disabling cache (no content length)*/ if (is_ice) { sess->flags |= GF_NETIO_SESSION_NOT_CACHED; if (sess->mime_type && !stricmp(sess->mime_type, "video/nsv")) { free(sess->mime_type); sess->mime_type = strdup("audio/aac"); } } /*done*/ if (sess->cache_start_size && ( (total_size && sess->cache_start_size >= total_size) || (sess->cache_start_size == ContentLength)) ) { sess->total_size = sess->bytes_done = sess->cache_start_size; /*disconnect*/ gf_dm_disconnect(sess); BodyStart = bytesRead; gf_dm_sess_notify_state(sess, GF_NETIO_DATA_TRANSFERED, GF_OK); } else if (sess->flags & GF_DOWNLOAD_IS_ICY) { sess->icy_bytes = 0; sess->status = GF_NETIO_DATA_EXCHANGE; } /*we don't expect anything*/ else if (!ContentLength && sess->http_read_type) { gf_dm_disconnect(sess); gf_dm_sess_notify_state(sess, GF_NETIO_DATA_TRANSFERED, GF_OK); sess->status = GF_NETIO_DISCONNECTED; sess->http_read_type = 0; } /*no range header, Accep-Ranges deny or dumb server : restart*/ else if (!range || !first_byte || (first_byte != sess->cache_start_size) ) { sess->cache_start_size = sess->bytes_done = 0; sess->total_size = ContentLength; if (! (sess->flags & GF_NETIO_SESSION_NOT_CACHED) ) { sess->cache = fopen(sess->cache_name, "wb"); if (!sess->cache) { e = GF_IO_ERR; goto exit; } } sess->status = GF_NETIO_DATA_EXCHANGE; } /*resume*/ else { sess->total_size = ContentLength + sess->cache_start_size; if (! (sess->flags & GF_NETIO_SESSION_NOT_CACHED) ) { sess->cache = fopen(sess->cache_name, "ab"); if (!sess->cache) { e = GF_IO_ERR; goto exit; } } sess->status = GF_NETIO_DATA_EXCHANGE; sess->bytes_done = sess->cache_start_size; } sess->window_start = sess->start_time = gf_sys_clock(); sess->bytes_in_wnd = 0; //we may have existing data in this buffer ... if (!e && (BodyStart < (u32) bytesRead)) { gf_dm_data_recieved(sess, sHTTP + BodyStart, bytesRead - BodyStart); /*store data if no callbacks or cache*/ if (sess->flags & GF_NETIO_SESSION_NOT_CACHED) { if (sess->init_data) free(sess->init_data); sess->init_data_size = bytesRead - BodyStart; sess->init_data = (char *) malloc(sizeof(char) * sess->init_data_size); memcpy(sess->init_data, sHTTP+BodyStart, sess->init_data_size); } } exit: if (e) { gf_dm_disconnect(sess); sess->status = GF_NETIO_STATE_ERROR; sess->last_error = e; gf_dm_sess_notify_state(sess, sess->status, e); } return; } /*fetch data*/ while (1) { u32 size; #if 1 if (sess->limit_data_rate && sess->bytes_per_sec) { if (sess->bytes_per_sec>sess->limit_data_rate) { /*update state*/ u32 runtime = gf_sys_clock() - sess->window_start; sess->bytes_per_sec = (1000 * (sess->bytes_in_wnd)) / runtime; if (sess->bytes_per_sec > sess->limit_data_rate) return; } } #endif e = gf_dm_read_data(sess, sHTTP, GF_DOWNLOAD_BUFFER_SIZE, &size); if (!size || e == GF_IP_NETWORK_EMPTY) { if (!sess->total_size && (gf_sys_clock() - sess->window_start > 1000)) { sess->total_size = sess->bytes_done; gf_dm_sess_notify_state(sess, GF_NETIO_DATA_TRANSFERED, GF_OK); } return; } if (e) { gf_dm_disconnect(sess); sess->last_error = e; gf_dm_sess_notify_state(sess, sess->status, e); return; } gf_dm_data_recieved(sess, sHTTP, size); /*socket empty*/ if (size < GF_DOWNLOAD_BUFFER_SIZE) return; } }
int main(int argc, char **argv) { /* The following things are used for getopt: */ extern char *optarg; extern int optind; extern int opterr; int ch; in_addr_t dest; struct sockaddr_in destaddr,fromaddr,servaddr; socklen_t fromlen; int sockfd_r; struct hostent *hp; char *buf; char dest_str[16]; #define RBLEN 500 char recbuf[RBLEN+1]; ssize_t recmegslen; fromlen = sizeof(fromaddr); // this is important otherwise recvfrom will return "Invalid argument" opterr = 0; while ((ch = getopt(argc, argv, "hp:")) != -1) { switch (ch) { case 'p': sscanf(optarg,"%d",&portnum); break; case 'h': help(); case '?': fprintf(stderr, "ERROR: No such option. -h for help.\n"); exit(1); /*no default action for case */ } } if (optind != argc -2){ /* exactly two arguments must be given */ help(); } if (strlen(argv[optind])>45){ fprintf(stderr,"Error: command too long. Max is 45\n"); exit(1); } buf=argv[optind]; // hp=gethostbyname(argv[optind+1]); if (hp==NULL){ fprintf(stderr,"Error: %s is not a IP address and not a resolvable hostname\n",argv[optind+1]); exit(1); } // take the first address: strncpy(dest_str,inet_ntoa(*(struct in_addr*)hp->h_addr_list[0]),sizeof(dest_str)); dest_str[sizeof(dest_str)-1]='\0'; dest=inet_addr(dest_str); if (dest==INADDR_NONE){ fprintf(stderr,"Error: IP addr. not valid\n"); exit(1); } // printf("II: data: %s, ip: %s port: %d\n",argv[optind],dest_str,portnum); /* initialize the socket address for the destination: */ destaddr.sin_family = AF_INET; destaddr.sin_addr.s_addr = dest; destaddr.sin_port = htons(portnum); // dest port /* initialize the socket address for this server: */ servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(portnum); // source port memset(&servaddr.sin_zero, 0, sizeof(servaddr.sin_zero)); // zero fill if ((sockfd_r = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0) { perror("open socket failed"); exit(1); } if (bind(sockfd_r, (struct sockaddr *)&servaddr, sizeof(servaddr))){ perror("bind socket failed"); exit(1); } // we are bound. The parent will get the message even if the sender // sends it before we call recvfrom /* the closing \0 will be sent as well: */ if(sendto(sockfd_r,buf,strlen(buf)+1,0,(struct sockaddr *)&destaddr,sizeof(destaddr)) == -1){ perror("sendto failed"); exit(1); } // we will timeout if there is no answer after a few sec signal(SIGALRM, &timeout_handler); alarm(3); recmegslen=recvfrom(sockfd_r,recbuf,RBLEN-1,0,(struct sockaddr *)&fromaddr,&fromlen); if(recmegslen == -1){ perror("recvfrom failed"); exit(1); } close(sockfd_r); recbuf[recmegslen]='\0'; printf("OK: %s: %s\n",inet_ntoa(fromaddr.sin_addr),recbuf); // return(0); }
/* minimal header reading. modify if you want to parse more information */ int RGBE_ReadHeader(FILE *fp, int *width, int *height, rgbe_header_info *info) { char buf[128]; int found_format; float tempf; int i; found_format = 0; if (info) { info->valid = 0; info->programtype[0] = 0; info->gamma = info->exposure = 1.0; } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == NULL) return rgbe_error(rgbe_read_error,NULL); if ((buf[0] != '#')||(buf[1] != '?')) { /* if you want to require the magic token then uncomment the next line */ /*return rgbe_error(rgbe_format_error,"bad initial token"); */ } else if (info) { info->valid |= RGBE_VALID_PROGRAMTYPE; for(i=0;i<sizeof(info->programtype)-1;i++) { if ((buf[i+2] == 0) || isspace(buf[i+2])) break; info->programtype[i] = buf[i+2]; } info->programtype[i] = 0; if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); } for(;;) { #if 0 if ((buf[0] == 0)||(buf[0] == '\n')) return rgbe_error(rgbe_format_error,"no FORMAT specifier found"); #endif if (((buf[0] == 0)||(buf[0] == '\n'))&&(found_format == 0)) return rgbe_error(rgbe_format_error,"no FORMAT specifier found"); else if (strcmp(buf,"FORMAT=32-bit_rle_rgbe\n") == 0) { found_format = 1; #if 0 break; /* format found so break out of loop */ #endif } else if (info && (sscanf(buf,"GAMMA=%g",&tempf) == 1)) { info->gamma = tempf; info->valid |= RGBE_VALID_GAMMA; } else if (info && (sscanf(buf,"EXPOSURE=%g",&tempf) == 1)) { info->exposure = tempf; info->valid |= RGBE_VALID_EXPOSURE; } else if (strcmp(buf,"\n") == 0) { /* blank line found so break out of loop */ break; } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); } if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); #if 0 if (strcmp(buf,"\n") != 0) return rgbe_error(rgbe_format_error, "missing blank line after FORMAT specifier"); if (fgets(buf,sizeof(buf)/sizeof(buf[0]),fp) == 0) return rgbe_error(rgbe_read_error,NULL); #endif if (sscanf(buf,"-Y %d +X %d",height,width) < 2) return rgbe_error(rgbe_format_error,"missing image size specifier"); return RGBE_RETURN_SUCCESS; }
static pascal OSStatus DBClientDataCallback (HIViewRef browser, DataBrowserItemID itemID, DataBrowserPropertyID property, DataBrowserItemDataRef itemData, Boolean changeValue) { OSStatus err, result; CFStringRef str; Boolean r; uint32 address; uint8 value; char code[256]; result = noErr; switch (property) { case kCmCheckBox: ThemeButtonValue buttonValue; if (changeValue) { err = GetDataBrowserItemDataButtonValue(itemData, &buttonValue); citem[itemID - 1].enabled = (buttonValue == kThemeButtonOn) ? true : false; } else err = SetDataBrowserItemDataButtonValue(itemData, citem[itemID - 1].enabled ? kThemeButtonOn : kThemeButtonOff); break; case kCmAddress: if (changeValue) { err = GetDataBrowserItemDataText(itemData, &str); r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding()); CFRelease(str); if (r) { Boolean translated; if (S9xProActionReplayToRaw(code, address, value) == NULL) translated = true; else if (S9xGameGenieToRaw(code, address, value) == NULL) translated = true; else { translated = false; if (sscanf(code, "%" SCNx32, &address) != 1) address = 0; else address &= 0xFFFFFF; } citem[itemID - 1].address = address; sprintf(code, "%06" PRIX32, address); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); if (translated) { DataBrowserItemID id[1]; citem[itemID - 1].value = value; id[0] = itemID; err = UpdateDataBrowserItems(browser, kDataBrowserNoItem, 1, id, kDataBrowserItemNoProperty, kCmValue); } } } else { sprintf(code, "%06" PRIX32, citem[itemID - 1].address); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); } break; case kCmValue: if (changeValue) { err = GetDataBrowserItemDataText(itemData, &str); r = CFStringGetCString(str, code, 256, CFStringGetSystemEncoding()); CFRelease(str); if (r) { uint32 byte; if (sscanf(code, "%" SCNx32, &byte) == 1) citem[itemID - 1].value = (uint8) byte; else { citem[itemID - 1].value = 0; err = SetDataBrowserItemDataText(itemData, CFSTR("00")); } } } else { sprintf(code, "%02" PRIX8, citem[itemID - 1].value); str = CFStringCreateWithCString(kCFAllocatorDefault, code, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); } break; case kCmDescription: if (changeValue) { code[0] = 0; err = GetDataBrowserItemDataText(itemData, &str); strcpy(code, GetMultiByteCharacters(str, 19)); CFRelease(str); if (code[0] == 0) { code[0] = ' '; code[1] = 0; } strcpy(citem[itemID - 1].description, code); } else { str = CFStringCreateWithCString(kCFAllocatorDefault, citem[itemID - 1].description, CFStringGetSystemEncoding()); err = SetDataBrowserItemDataText(itemData, str); CFRelease(str); } break; case kDataBrowserItemIsActiveProperty: err = SetDataBrowserItemDataBooleanValue(itemData, true); break; case kDataBrowserItemIsEditableProperty: err = SetDataBrowserItemDataBooleanValue(itemData, true); break; default: result = errDataBrowserPropertyNotSupported; } return (result); }
static MagickBooleanType WriteXTRNImage(const ImageInfo *image_info, Image *image,ExceptionInfo *exception) { Image * p; ImageInfo *clone_info; int scene; MagickBooleanType status; void *param1, *param2, *param3; param1 = param2 = param3 = (void *) NULL; status=MagickTrue; if (LocaleCompare(image_info->magick,"XTRNFILE") == 0) { clone_info=CloneImageInfo(image_info); *clone_info->magick='\0'; status=WriteImage(clone_info,image,exception); if (status == MagickFalse) CatchImageException(image); clone_info=DestroyImageInfo(clone_info); } else if (LocaleCompare(image_info->magick,"XTRNIMAGE") == 0) { Image **image_ptr; ImageInfo **image_info_ptr; clone_info=CloneImageInfo(image_info); if (clone_info->filename[0]) { (void) sscanf(clone_info->filename,"%lx,%lx",¶m1,¶m2); image_info_ptr=(ImageInfo **) param1; image_ptr=(Image **) param2; if ((image_info_ptr != (ImageInfo **) NULL) && (image_ptr != (Image **) NULL)) { *image_ptr=CloneImage(image,0,0,MagickFalse,exception); *image_info_ptr=clone_info; } } } else if (LocaleCompare(image_info->magick,"XTRNBLOB") == 0) { char **blob_data; size_t *blob_length; char filename[MagickPathExtent]; clone_info=CloneImageInfo(image_info); if (clone_info->filename[0]) { (void) sscanf(clone_info->filename,"%lx,%lx,%2048s", ¶m1,¶m2,filename); blob_data=(char **) param1; blob_length=(size_t *) param2; scene = 0; (void) CopyMagickString(clone_info->filename,filename, MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) CopyMagickString(p->filename,filename,MagickPathExtent); p->scene=scene++; } SetImageInfo(clone_info,1,exception); (void) CopyMagickString(image->magick,clone_info->magick, MagickPathExtent); if (*blob_length == 0) *blob_length=8192; *blob_data=(char *) ImageToBlob(clone_info,image,blob_length, exception); if (*blob_data == NULL) status=MagickFalse; if (status == MagickFalse) CatchImageException(image); } clone_info=DestroyImageInfo(clone_info); } else if (LocaleCompare(image_info->magick,"XTRNARRAY") == 0) { char filename[MagickPathExtent]; size_t blob_length; unsigned char *blob_data; clone_info=CloneImageInfo(image_info); if (*clone_info->filename != '\0') { (void) sscanf(clone_info->filename,"%lx,%2048s",¶m1,filename); image->client_data=param1; scene=0; (void) CopyMagickString(clone_info->filename,filename, MagickPathExtent); for (p=image; p != (Image *) NULL; p=GetNextImageInList(p)) { (void) CopyMagickString(p->filename,filename,MagickPathExtent); p->scene=scene++; } SetImageInfo(clone_info,1,exception); (void) CopyMagickString(image->magick,clone_info->magick, MagickPathExtent); blob_data=ImageToBlob(clone_info,image,&blob_length, exception); if (blob_data == (unsigned char *) NULL) status=MagickFalse; else SafeArrayFifo(image,blob_data,blob_length); if (status == MagickFalse) CatchImageException(image); } clone_info=DestroyImageInfo(clone_info); } return(MagickTrue); }
bool Image::loadPPM(const std::string &fname) { clear(); /* BaseTextFile file; file.addLineCommentDef("#"); file.loadFile(fname, false); std::string type; file >> type; int nChannels; if (type == "P5") nChannels = 1; else if (type == "P6") nChannels = 3; else return false; int w, h; file >> w; file >> h; int dummy; file >> dummy; Console::print("%d %d %d\n", w, h, dummy); // Create the image create(w, h, nChannels, Image::I8BITS); // read the image data fread(&m_data[0], sizeof(unsigned char), m_data.size(), file.getFP()); return true; */ FILE *fp; char imageType[3],str[1024]; // Read PGM image file with filename "file" // The PGM file format for a GREYLEVEL image is: // P5 (2 ASCII characters) <CR> // two ASCII numbers for nx ny (number of rows and columns <CR> // 255 (ASCII number) <CR> // binary pixel data with one byte per pixel // The PGM file format for a COLOR image is: // P6 (2 ASCII characters) <CR> // two ASCII numbers for nx ny (number of rows and columns <CR> // 255 (ASCII number) <CR> // binary pixel data with three bytes per pixel (one byte for eacg RGB) fp=fopen(fname.c_str(),"rb"); if (!fp) return false; // read the first ASCII line to find out if we read a color image or // a greylevel image fgets(str,100,fp); sscanf(str,"%s",imageType); Format format = Image::I8BITS; int nChannels = 0; if(!strncmp(imageType,"P5",2)) // greylevel image nChannels = 1; else if(!strncmp(imageType,"P6",2)) // color image nChannels = 3; else return false; // skip comments embedded in header fgets(str,1024,fp); while(str[0]=='#') fgets(str,1024,fp); // read image dimensions int w, h; sscanf(str,"%d %d", &w, &h); // read the next line into dummy variable fgets(str,1024,fp); // Create the image create(w, h, nChannels, format); // read the image data fread(&m_data[0], sizeof(unsigned char), w*h*m_bytesPerPixel, fp); fclose(fp); if (m_width==0 || m_height==0) return false; return true; }
/* Receive data from host and call *callback () * @param waitress handle * @return WaitressReturn_t */ WaitressReturn_t WaitressFetchCall (WaitressHandle_t *waith) { struct addrinfo hints, *res; int sockfd; char recvBuf[WAITRESS_RECV_BUFFER]; char writeBuf[2*1024]; ssize_t recvSize = 0; WaitressReturn_t wRet = WAITRESS_RET_OK; struct pollfd sockpoll; int pollres; /* header parser vars */ char *nextLine = NULL, *thisLine = NULL; enum {HDRM_HEAD, HDRM_LINES, HDRM_FINISHED} hdrParseMode = HDRM_HEAD; char statusCode[3], val[256]; unsigned int bufFilled = 0; /* initialize */ waith->contentLength = 0; waith->contentReceived = 0; memset (&hints, 0, sizeof hints); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; /* Use proxy? */ if (WaitressProxyEnabled (waith)) { if (getaddrinfo (waith->proxyHost, waith->proxyPort, &hints, &res) != 0) { return WAITRESS_RET_GETADDR_ERR; } } else { if (getaddrinfo (waith->host, waith->port, &hints, &res) != 0) { return WAITRESS_RET_GETADDR_ERR; } } if ((sockfd = socket (res->ai_family, res->ai_socktype, res->ai_protocol)) == -1) { freeaddrinfo (res); return WAITRESS_RET_SOCK_ERR; } sockpoll.fd = sockfd; fcntl (sockfd, F_SETFL, O_NONBLOCK); /* increase socket receive buffer */ const int sockopt = 256*1024; setsockopt (sockfd, SOL_SOCKET, SO_RCVBUF, &sockopt, sizeof (sockopt)); /* non-blocking connect will return immediately */ connect (sockfd, res->ai_addr, res->ai_addrlen); sockpoll.events = POLLOUT; pollres = poll (&sockpoll, 1, waith->socktimeout); freeaddrinfo (res); if (pollres == 0) { return WAITRESS_RET_TIMEOUT; } else if (pollres == -1) { return WAITRESS_RET_ERR; } /* check connect () return value */ socklen_t pollresSize = sizeof (pollres); getsockopt (sockfd, SOL_SOCKET, SO_ERROR, &pollres, &pollresSize); if (pollres != 0) { return WAITRESS_RET_CONNECT_REFUSED; } /* send request */ if (WaitressProxyEnabled (waith)) { snprintf (writeBuf, sizeof (writeBuf), "%s http://%s:%s%s HTTP/1.0\r\n", (waith->method == WAITRESS_METHOD_GET ? "GET" : "POST"), waith->host, waith->port, waith->path); } else { snprintf (writeBuf, sizeof (writeBuf), "%s %s HTTP/1.0\r\n", (waith->method == WAITRESS_METHOD_GET ? "GET" : "POST"), waith->path); } WRITE_RET (writeBuf, strlen (writeBuf)); snprintf (writeBuf, sizeof (writeBuf), "Host: %s\r\nUser-Agent: " PACKAGE "\r\n", waith->host); WRITE_RET (writeBuf, strlen (writeBuf)); if (waith->method == WAITRESS_METHOD_POST && waith->postData != NULL) { snprintf (writeBuf, sizeof (writeBuf), "Content-Length: %zu\r\n", strlen (waith->postData)); WRITE_RET (writeBuf, strlen (writeBuf)); } if (waith->extraHeaders != NULL) { WRITE_RET (waith->extraHeaders, strlen (waith->extraHeaders)); } WRITE_RET ("\r\n", 2); if (waith->method == WAITRESS_METHOD_POST && waith->postData != NULL) { WRITE_RET (waith->postData, strlen (waith->postData)); } /* receive answer */ nextLine = recvBuf; while (hdrParseMode != HDRM_FINISHED) { READ_RET (recvBuf+bufFilled, sizeof (recvBuf)-1 - bufFilled, &recvSize); if (recvSize == 0) { /* connection closed too early */ CLOSE_RET (WAITRESS_RET_CONNECTION_CLOSED); } bufFilled += recvSize; memset (recvBuf+bufFilled, 0, sizeof (recvBuf) - bufFilled); thisLine = recvBuf; /* split */ while ((nextLine = strchr (thisLine, '\n')) != NULL && hdrParseMode != HDRM_FINISHED) { /* make lines parseable by string routines */ *nextLine = '\0'; if (*(nextLine-1) == '\r') { *(nextLine-1) = '\0'; } /* skip \0 */ ++nextLine; switch (hdrParseMode) { /* Status code */ case HDRM_HEAD: if (sscanf (thisLine, "HTTP/1.%*1[0-9] %3[0-9] ", statusCode) == 1) { if (memcmp (statusCode, "200", 3) == 0 || memcmp (statusCode, "206", 3) == 0) { /* everything's fine... */ } else if (memcmp (statusCode, "403", 3) == 0) { CLOSE_RET (WAITRESS_RET_FORBIDDEN); } else if (memcmp (statusCode, "404", 3) == 0) { CLOSE_RET (WAITRESS_RET_NOTFOUND); } else { CLOSE_RET (WAITRESS_RET_STATUS_UNKNOWN); } hdrParseMode = HDRM_LINES; } /* endif */ break; /* Everything else, except status code */ case HDRM_LINES: /* empty line => content starts here */ if (*thisLine == '\0') { hdrParseMode = HDRM_FINISHED; } else { memset (val, 0, sizeof (val)); if (sscanf (thisLine, "Content-Length: %255c", val) == 1) { waith->contentLength = atol (val); } } break; default: break; } /* end switch */ thisLine = nextLine; } /* end while strchr */ memmove (recvBuf, thisLine, thisLine-recvBuf); bufFilled -= (thisLine-recvBuf); } /* end while hdrParseMode */ /* push remaining bytes */ if (bufFilled > 0) { waith->contentReceived += bufFilled; if (waith->callback (thisLine, bufFilled, waith->data) == WAITRESS_CB_RET_ERR) { CLOSE_RET (WAITRESS_RET_CB_ABORT); } } /* receive content */ do { READ_RET (recvBuf, sizeof (recvBuf), &recvSize); if (recvSize > 0) { waith->contentReceived += recvSize; if (waith->callback (recvBuf, recvSize, waith->data) == WAITRESS_CB_RET_ERR) { wRet = WAITRESS_RET_CB_ABORT; break; } } } while (recvSize > 0); close (sockfd); if (wRet == WAITRESS_RET_OK && waith->contentReceived < waith->contentLength) { return WAITRESS_RET_PARTIAL_FILE; } return wRet; }
/* initialize the epics record and the hardware */ static long dsetInit_devAiAsyncSerial(aiRecord *pai) { CONTEXT *p_myContext; CALLBACK *p_myCallback; char p_writeBuffer[BUFLEN]; char p_readBuffer[BUFLEN]; int myPrimaryAddress; int myPortNumber; int myParity; int myNumberOfDataBits; int myNumberOfStopBits; int myBaudRate; char p_myCommand[BUFLEN]; #ifdef DEBUG1 packageInfo(); printf(__FILE__ "[%d] -> %s (%s)\n", __LINE__, __func__, pai->name); #endif /* Parse the db file paramters */ /* and set the value of key variables */ if(sscanf(pai->inp.value.instio.string, "spn=%d pad=%d br=%d nodb=%d p=%d nosb=%d c=%[^\n]", &myPortNumber, &myPrimaryAddress, &myBaudRate, &myNumberOfDataBits, &myParity, &myNumberOfStopBits, p_myCommand)!=7) { printf( __FILE__ "[%d] Error: Couldn't parse the parameters correctly!", __LINE__ ); printf( __FILE__ "[%d] >%s<!", __LINE__, pai->inp.value.instio.string ); sleep(SLEEPTIME_ERROR); return(ERROR); } /* end_of_if */ initSerialPort2(myPortNumber); setBaudRate2(myPortNumber,myBaudRate); setNumberOfDataBits2(myPortNumber,myNumberOfDataBits); setParity2(myPortNumber,myParity); setFlowControl2(myPortNumber,NO_FLOW_CONTROL); /* Required for this dev */ setNumberOfStopBits2(myPortNumber,myNumberOfStopBits); #ifdef DEBUG2 printf(__FILE__ "[%d] portNumber = %d\n", __LINE__, myPortNumber); printf(__FILE__ "[%d] primaryAddress = %d\n", __LINE__, myPrimaryAddress); printf(__FILE__ "[%d] baudRate = %d\n", __LINE__, getBaudRate2(myPortNumber)); printf(__FILE__ "[%d] numberOfDataBits = %d\n", __LINE__, getNumberOfDataBits2(myPortNumber)); printf(__FILE__ "[%d] parity = %d\n", __LINE__, getParity2(myPortNumber)); printf(__FILE__ "[%d] numberOfStopBits = %d\n", __LINE__, getNumberOfStopBits2(myPortNumber)); printf(__FILE__ "[%d] p_myCommand = >%s<\n", __LINE__, p_myCommand); #endif if (lockSerialPort2(myPortNumber,LOCK, pai->name)<=ERROR) { printf( __FILE__ "[%d] Error: Couldn't lock serial port (%s)\n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } /* Disable front panel */ /* This operation should work if */ /* communication parameters are ok */ strcpy(p_writeBuffer,"XFRONT"); strcat(p_writeBuffer,TERMINATOR); openSerialPort2(myPortNumber); if (writeSerialPort2(myPortNumber, p_writeBuffer ) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't write on %s\n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_WRITE); memset(p_readBuffer,0,BUFLEN); if (readSerialPort2(myPortNumber, p_readBuffer, BUFLEN) <= ERROR) { printf( __FILE__ "[%d] Error: Couldn't read on %s\n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_READ); if (lockSerialPort2(myPortNumber,UNLOCK, pai->name)<=ERROR) { printf ( __FILE__ "Error"); sleep(SLEEPTIME_ERROR); return(ERROR); } p_myCallback=(CALLBACK *)calloc(1,sizeof(CALLBACK)); callbackSetCallback(myCallback_devAiAsyncSerial,p_myCallback); callbackSetUser(pai,p_myCallback); p_myContext=(CONTEXT *)calloc(1,sizeof(CONTEXT)); p_myContext->portNumber=myPortNumber; p_myContext->p_callback=p_myCallback; p_myContext->primaryAddress=myPrimaryAddress; strncpy(p_myContext->p_command, p_myCommand, BUFLEN); pai->dpvt=(void *)p_myContext; /* Check acknowledgement */ if (strncmp(p_readBuffer,"OK",2)!=0) { printf( __FILE__ "[%d] Error: Couldn't communicate with %s\n", __LINE__, pai->name); printf( __FILE__ "[%d] Check configuration parameters?\n", __LINE__); return(ERROR); } #ifdef DEBUG1 printf( __FILE__ "[%d] <- %s\n", __LINE__, __func__); #endif return(SUCCESS); } /* end init_press_record() */
/* * Read and write all the ports specified in hex on the command line. * The program uses the faster ioperm[set port IO permissions]/iopl[change IO privilege level] calls on x86. * The program acts as inb/inw/inl according to its own name. */ int port_io(int argc, char **argv) { unsigned int i, n, port, size, error = 0; unsigned int val, opt; prgname = argv[0]; switch (prgname[strlen(prgname)-1]) { case 'w': size = 2; break; case 'l': size = 4; break; case 'b': case 'p': default: size = 1; } setuid(0); printf("Please choose the option: 1 - read, 2 - write: "); scanf("%d",&opt); if (opt == 1) { for (i = 1; i < argc; i++) { if ( sscanf(argv[i], "%x%n", &port, &n) < 1 || n != strlen(argv[i]) ) { fprintf(stderr, "%s: argument \"%s\" is not a hex number\n", argv[0], argv[i]); error++; continue; } if (port & (size-1)) { fprintf(stderr, "%s: argument \"%s\" is not properly aligned\n", argv[0], argv[i]); error++; continue; } error += read_one(port, size); } } else if (opt == 2) { for (i = 1; i < argc-1; i++) { if ( sscanf(argv[i], "%x%n", &port, &n) < 1 || n != strlen(argv[i]) ) { fprintf(stderr, "%s: argument \"%s\" is not a hex number\n", argv[0], argv[i]); error++; continue; } if (port & (size-1)) { fprintf(stderr, "%s: argument \"%s\" is not properly aligned\n", argv[0], argv[i]); error++; continue; } if ( sscanf(argv[i+1], "%x%n", &val, &n) < 1 || n != strlen(argv[i+1]) ) { fprintf(stderr, "%s: argument \"%s\" is not a hex number\n", argv[0], argv[i+1]); error++; continue; } if (size < 4 && val > (size == 1 ? 0xff : 0xffff)) { fprintf(stderr, "%s: argument \"%s\" out of range\n", argv[0], argv[i+1]); error++; continue; } error += write_one(port, val, size); } } return (error ? 1 : 0); }
/* GZMAT */ int rgzmat(char *filename, int *atomnum, ATOM * atom, CONTROLINFO cinfo, MOLINFO minfo) { typedef struct { char name[MAXCHAR]; } STRNAME; FILE *fpin; int i, j, index, index0; int overflow_flag = 0; int findindex; int numatom; int coordinate_flag = 0; STRNAME *bondstr; STRNAME *anglestr; STRNAME *twiststr; char tmpchar1[MAXCHAR]; char tmpchar2[MAXCHAR]; char line[MAXCHAR]; if ((fpin = fopen(filename, "r")) == NULL) { fprintf(stdout, "Cannot open the input file %s to read in rgzmat(), exit\n", filename); exit(1); } bondstr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (bondstr == NULL) { fprintf(stdout, "memory allocation error for *bondstr in rgzmat()\n"); exit(1); } anglestr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (anglestr == NULL) { fprintf(stdout, "memory allocation error for *anglestr in rgzmat()\n"); exit(1); } twiststr = (STRNAME *) malloc(sizeof(STRNAME) * (cinfo.maxatom +10)); if (twiststr == NULL) { fprintf(stdout, "memory allocation error for *twiststr in rgzmat()\n"); exit(1); } initial(cinfo.maxatom, atom, minfo.resname); index = 0; index0 = 1; numatom = 0; for (;;) { if (fgets(line, MAXCHAR, fpin) == NULL) { /* printf("\nFinished reading %s file.", cinfo.ifilename); */ break; } if (spaceline(line) == 1) { if(coordinate_flag == 1) break; index++; continue; } if (index >= 2) index++; if (index <= 3) continue; if (index >= 4) { if (spaceline(line) == 1 || strncmp(line, "Vari", 4) == 0 || strncmp(line, "vari", 4) == 0) index0 = -1; if (strncmp(line, "Const", 5) == 0 || strncmp(line, "const", 5) == 0) index0 = -1; } if (index == 4) { if (overflow_flag == 0) sscanf(line, "%s", atom[numatom].name); numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("\nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index == 5) { if (overflow_flag == 0) { sscanf(line, "%s%d%s", atom[numatom].name, &atom[numatom].bondatom, bondstr[numatom].name); if(atom[numatom].bondatom > numatom) { printf("\nError: bond atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } } numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("\nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index == 6) { if (overflow_flag == 0) { sscanf(line, "%s%d%s%d%s", atom[numatom].name, &atom[numatom].bondatom, bondstr[numatom].name, &atom[numatom].angleatom, anglestr[numatom].name); if(atom[numatom].bondatom > numatom) { printf("\nError: bond atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } if(atom[numatom].angleatom > numatom) { printf("\nError: angle atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } } numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("\nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index0 != -1) { if (overflow_flag == 0) { sscanf(line, "%s%d%s%d%s%d%s", atom[numatom].name, &atom[numatom].bondatom, bondstr[numatom].name, &atom[numatom].angleatom, anglestr[numatom].name, &atom[numatom].twistatom, twiststr[numatom].name); if(atom[numatom].bondatom > numatom) { printf("\nError: bond atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } if(atom[numatom].angleatom > numatom) { printf("\nError: angle atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } if(atom[numatom].twistatom > numatom) { printf("\nError: torsional atom ID is larger than ID of current atom (%d,%s), exit", numatom+1, atom[numatom].name); exit(1); } } numatom++; if (numatom >= cinfo.maxatom && overflow_flag == 0) { printf ("\nInfo: the atom number exceeds the MAXATOM, reallocate memory automatically"); overflow_flag = 1; } continue; } if (index0 == -1) { if (strchr(line, '=') == NULL) continue; coordinate_flag = 1; for(i=0;i<strlen(line);i++) if(line[i] == '=') line[i] = ' '; sscanf(line, "%s %s", tmpchar1, tmpchar2); for (i = 1; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(bondstr[i].name); j++) if (bondstr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(bondstr[i].name, tmpchar2); break; } } for (i = 2; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(anglestr[i].name); j++) if (anglestr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(anglestr[i].name, tmpchar2); break; } } for (i = 3; i < numatom; i++) { findindex = 1; for (j = 0; j < strlen(twiststr[i].name); j++) if (twiststr[i].name[j] != tmpchar1[j]) { findindex = 0; break; } if (findindex == 1) { strcpy(twiststr[i].name, tmpchar2); break; } } } } atom[1].bondatom--; atom[2].bondatom--; atom[2].angleatom--; for (i = 3; i < numatom; i++) { atom[i].bondatom--; atom[i].angleatom--; atom[i].twistatom--; } for (i = 1; i < numatom; i++) atom[i].bond = atof(bondstr[i].name); for (i = 2; i < numatom; i++) atom[i].angle = atof(anglestr[i].name); for (i = 3; i < numatom; i++) atom[i].twist = atof(twiststr[i].name); *atomnum = numatom; /* printf("\n atom number is %5d", *atomnum); */ fclose(fpin); free(bondstr); free(anglestr); free(twiststr); return overflow_flag; }
// Attempts to load the texture from the source. bool TextureResource::Load(RenderInterface* render_interface) const { // Check for special loader tokens. if (!source.Empty() && source[0] == '?') { Vector2i dimensions; bool delete_data = false; const byte* data = NULL; // Find the generation protocol and generate the data accordingly. String protocol = source.Substring(1, source.Find("::") - 1); if (protocol == "font") { // The requested texture is a font layer. delete_data = true; FontFaceHandle* handle; FontEffect* layer_id; int layout_id; int texture_id; if (sscanf(source.CString(), "?font::%p/%p/%d/%d", &handle, &layer_id, &layout_id, &texture_id) == 4) { handle->GenerateLayerTexture(data, dimensions, layer_id, layout_id, texture_id); } } // If texture data was generated, great! Otherwise, fallback to the LoadTexture() code and // hope the client knows what the hell to do with the question mark in their file name. if (data != NULL) { TextureHandle handle; bool success = render_interface->GenerateTexture(handle, data, dimensions); if (delete_data) delete[] data; if (success) { texture_data[render_interface] = TextureData(handle, dimensions); return true; } else { Log::Message(Log::LT_WARNING, "Failed to generate internal texture %s.", source.CString()); texture_data[render_interface] = TextureData(0, Vector2i(0, 0)); return false; } } } TextureHandle handle; Vector2i dimensions; if (!render_interface->LoadTexture(handle, dimensions, source)) { Log::Message(Log::LT_WARNING, "Failed to load texture from %s.", source.CString()); texture_data[render_interface] = TextureData(0, Vector2i(0, 0)); return false; } texture_data[render_interface] = TextureData(handle, dimensions); return true; }
void wgzmat(char *filename, int atomnum, ATOM atom[], MOLINFO minfo) { FILE *fpin; FILE *fpout; char *amberhome; char espparm_file[MAXCHAR]; char line[MAXCHAR]; char akeyword[MAXCHAR]=""; char ckeyword[MAXCHAR]; char tmpchar0[MAXCHAR]; char tmpchar1[MAXCHAR]; char tmpchar2[MAXCHAR]; char tmpchar3[MAXCHAR]; int i,j; int iradius_flag; int ibs= 0; int esp_flag; int nespparm = 0; int nbasisset = 0; double default_radius = 1.7; ESPPARM espparm[120]; BASISSET basisset[100]; if ((fpout = fopen(filename, "w")) == NULL) { fprintf(stdout, "Cannot open a file %s to write in wgzmat(), exit\n", filename); exit(1); } intercoord(atomnum, atom); fprintf(fpout, "%s\n", "--Link1--"); if(strlen(minfo.gn) >= 5) fprintf(fpout, "%s\n", minfo.gn); fprintf(fpout, "%s%s\n", "%chk=", minfo.chkfile); if(strlen(minfo.gm) >= 4) fprintf(fpout, "%s\n", minfo.gm); // check ESP-related keyword esp_flag = 0; for(i=0;i<strlen(minfo.gkeyword);i++) ckeyword[i] = toupper(minfo.gkeyword[i]); if((strstr(ckeyword, "POP=") != 0 || strstr(ckeyword, "POP(") != 0) && (strstr(ckeyword, "MK") != 0 || strstr(ckeyword, "CHELP") != 0)) esp_flag = 1; // when the default gaussian keyword is used, or esp_flag ==1, read ESP.PARM if(minfo.igkeyword == 0 || esp_flag == 1) { amberhome = (char *) getenv("AMBERHOME"); if( amberhome == NULL ){ fprintf( stdout, "AMBERHOME is not set!\n" ); exit(1); } strcpy(espparm_file, amberhome); strcat(espparm_file, "/dat/antechamber/ESPPARM.DAT"); if ((fpin = fopen(espparm_file, "r")) == NULL) { fprintf(stdout, "Cannot open espparm_file %s in read_espparm(), exit\n", espparm_file); exit(1); } for (;;) { if (fgets(line, MAXCHAR, fpin) == NULL) break; if(strncmp(line, "DEFAULT RADIUS", 14) == 0) sscanf(&line[14], "%lf", &default_radius); if(strncmp(line, "BASIS SET", 9) == 0) { sscanf(&line[9], "%d%s", &basisset[nbasisset].id, basisset[nbasisset].bs); nbasisset++; } if(strncmp(line, "PARM", 4) == 0) { sscanf(&line[4], "%ld%s%lf%lf%d%d", &espparm[nespparm].atomicnum, espparm[nespparm].elem, &espparm[nespparm].vdw, &espparm[nespparm].mk, &espparm[nespparm].flag, &espparm[nespparm].bs); nespparm++; } } fclose(fpin); iradius_flag = 0; ibs = 0; for(i=0;i<atomnum;i++) { for(j=0;j<nespparm;j++) if(atom[i].atomicnum == espparm[j].atomicnum || strcmp(atom[i].element, espparm[j].elem) == 0) { if(ibs < espparm[j].bs) ibs=espparm[j].bs; if(espparm[j].flag != 0) { iradius_flag = 1; espparm[j].flag = 2; } break; } } if(minfo.igkeyword == 0) { strcpy(minfo.gkeyword, "#HF/"); strcat(minfo.gkeyword, basisset[ibs-1].bs); strcat(minfo.gkeyword, " SCF=tight Test Pop=MK iop(6/33=2) iop(6/42=6) opt"); } } // additional keywords if(esp_flag == 1) { if(iradius_flag == 1) { if(strstr(minfo.gkeyword, "ReadRadii") == 0 && strstr(minfo.gkeyword, "READRADII") == 0 && strstr(minfo.gkeyword, "readradii") == 0) { strcat(akeyword, "Pop=ReadRadii"); } } if(minfo.gv == 1) { if(strstr(minfo.gkeyword, "6/50=1") == 0) { strcat(akeyword, " iop(6/50=1)"); } } } if(strlen(akeyword) >= 1) { fprintf(fpout, "%s\n", minfo.gkeyword); fprintf(fpout, "#%s\n", akeyword); fprintf(fpout, "\n", minfo.gkeyword); } else fprintf(fpout, "%s\n\n", minfo.gkeyword); fprintf(fpout, "%s\n\n", "remark line goes here"); fprintf(fpout, "%d%4d\n", minfo.icharge, minfo.multiplicity); element(atomnum, atom); for (i = 0; i < atomnum; i++) { /* newitoa(i + 1, tmpchar0); */ sprintf(tmpchar0, "%d", i+1); if (i == 0) { fprintf(fpout, "%5s\n", atom[i].element); continue; } if (i == 1) { strcpy(tmpchar1, "b"); strcat(tmpchar1, tmpchar0); fprintf(fpout, "%5s%5d%8s\n", atom[i].element, atom[i].bondatom + 1, tmpchar1); continue; } if (i == 2) { strcpy(tmpchar1, "b"); strcat(tmpchar1, tmpchar0); fprintf(fpout, "%5s%5d%8s", atom[i].element, atom[i].bondatom + 1, tmpchar1); strcpy(tmpchar2, "a"); strcat(tmpchar2, tmpchar0); fprintf(fpout, "%5d%8s\n", atom[i].angleatom + 1, tmpchar2); continue; } strcpy(tmpchar1, "b"); strcat(tmpchar1, tmpchar0); fprintf(fpout, "%5s%5d%8s", atom[i].element, atom[i].bondatom + 1, tmpchar1); strcpy(tmpchar2, "a"); strcat(tmpchar2, tmpchar0); fprintf(fpout, "%5d%8s", atom[i].angleatom + 1, tmpchar2); strcpy(tmpchar3, "t"); strcat(tmpchar3, tmpchar0); fprintf(fpout, "%5d%8s\n", atom[i].twistatom + 1, tmpchar3); } fprintf(fpout, "Variables:\n"); fprintf(fpout, "b2= %8.4lf\n", atom[1].bond); fprintf(fpout, "b3= %8.4lf\n", atom[2].bond); fprintf(fpout, "a3= %8.4lf\n", atom[2].angle); for (i = 3; i < atomnum; i++) { /* newitoa(i + 1, tmpchar0); */ sprintf(tmpchar0, "%d", i+1); strcpy(tmpchar1, "b"); strcat(tmpchar1, tmpchar0); strcpy(tmpchar2, "a"); strcat(tmpchar2, tmpchar0); strcpy(tmpchar3, "t"); strcat(tmpchar3, tmpchar0); fprintf(fpout, "%s= %8.4lf\n", tmpchar1, atom[i].bond); fprintf(fpout, "%s= %8.4lf\n", tmpchar2, atom[i].angle); fprintf(fpout, "%s= %8.4lf\n", tmpchar3, atom[i].twist); } if(esp_flag == 1) { if(minfo.gv == 1 && iradius_flag == 1) { for(i=0;i<nespparm;i++) if(espparm[i].flag == 2) { if(espparm[i].mk <= 0) espparm[i].mk=default_radius; fprintf(fpout, "\n%s %8.2lf", espparm[i].elem, espparm[i].mk); } fprintf(fpout, "\n\n%s\n", minfo.gesp); for(i=0;i<nespparm;i++) if(espparm[i].flag == 2) { if(espparm[i].mk <= 0) espparm[i].mk=default_radius; fprintf(fpout, "\n%s %8.2lf", espparm[i].elem, espparm[i].mk); } fprintf(fpout, "\n\n%s\n", minfo.gesp); } if(minfo.gv == 0 && iradius_flag == 1) { for(i=0;i<nespparm;i++) if(espparm[i].flag == 2) { if(espparm[i].mk <= 0) espparm[i].mk=default_radius; fprintf(fpout, "\n%s %8.2lf", espparm[i].elem, espparm[i].mk); } fprintf(fpout, "\n"); for(i=0;i<nespparm;i++) if(espparm[i].flag == 2) { if(espparm[i].mk <= 0) espparm[i].mk=default_radius; fprintf(fpout, "\n%s %8.2lf", espparm[i].elem, espparm[i].mk); } fprintf(fpout, "\n"); } if(minfo.gv == 1 && iradius_flag == 0) { fprintf(fpout, "\n%s\n", minfo.gesp); fprintf(fpout, "\n%s\n", minfo.gesp); } } fprintf(fpout, "\n\n"); fclose(fpout); }
void KPaletteTable::readNamedColor( void ) { if( mNamedColorList->count() != 0 ) { return; // Strings already present } TDEGlobal::locale()->insertCatalogue("tdelibs_colors"); // // Code somewhat inspired by KPalette. // const char * const *path = namedColorFilePath(); for( int i=0; path[i]; ++i ) { TQFile paletteFile( path[i] ); if( !paletteFile.open( IO_ReadOnly ) ) { continue; } TQString line; TQStringList list; while( paletteFile.readLine( line, 100 ) != -1 ) { int red, green, blue; int pos = 0; if( sscanf(line.ascii(), "%d %d %d%n", &red, &green, &blue, &pos ) == 3 ) { // // Remove duplicates. Every name with a space and every name // that start with "gray". // TQString name = line.mid(pos).stripWhiteSpace(); if( name.isNull() || name.find(' ') != -1 || name.find( "gray" ) != -1 || name.find( "grey" ) != -1 ) { continue; } const TQColor color ( red, green, blue ); if ( color.isValid() ) { const TQString colorName( i18n("color", name.latin1() ) ); list.append( colorName ); d->m_namedColorMap[ colorName ] = color; } } } list.sort(); mNamedColorList->insertStringList( list ); break; } if( mNamedColorList->count() == 0 ) { // // Give the error dialog box a chance to center above the // widget (or dialog). If we had displayed it now we could get a // situation where the (modal) error dialog box pops up first // preventing the real dialog to become visible until the // error dialog box is removed (== bad UI). // TQTimer::singleShot( 10, this, TQT_SLOT(slotShowNamedColorReadError()) ); } }
int main(int argc, char *argv[]) { char inFile[512], *configFile=NULL, type[10]; const int pid = getpid(); extern int logflag, quietflag; int quiet_f; /* log_f is a static global */ int createFlag = FLAG_NOT_SET; // create configuration file flag int configFlag = FLAG_NOT_SET; // use configuration file flag logflag = quietflag = FALSE; log_f = quiet_f = FLAG_NOT_SET; // Begin command line parsing *********************************************** if ( (checkForOption("--help", argc, argv) != FLAG_NOT_SET) || (checkForOption("-h", argc, argv) != FLAG_NOT_SET) || (checkForOption("-help", argc, argv) != FLAG_NOT_SET) ) { print_help(); } get_asf_share_dir_with_argv0(argv[0]); handle_license_and_version_args(argc, argv, ASF_NAME_STRING); // Check which options were provided log_f = checkForOption("-log", argc, argv); quiet_f = checkForOption("-quiet", argc, argv); createFlag = checkForOption("-create", argc, argv); configFlag = checkForOption("-config", argc, argv); // We need to make sure the user specified the proper number of arguments int needed_args = 1 + REQUIRED_ARGS; // command & REQUIRED_ARGS int num_flags = 0; if (log_f != FLAG_NOT_SET) {needed_args += 2; num_flags++;} // option & param if (quiet_f != FLAG_NOT_SET) {needed_args += 1; num_flags++;} // option if (createFlag != FLAG_NOT_SET) {needed_args += 3; num_flags++;} // option & params if (configFlag != FLAG_NOT_SET) {needed_args += 2; num_flags++;} // option & param // Make sure we have the right number of args if(argc != needed_args) { print_usage(); } // Make sure all options occur before the config file name argument if (num_flags == 1 && (log_f > 1 || quiet_f > 1)) { print_usage(); } else if (num_flags > 1 && (log_f >= argc - REQUIRED_ARGS - 1 || quiet_f >= argc - REQUIRED_ARGS - 1)) { print_usage(); } // Make sure that only one option is used if (createFlag != FLAG_NOT_SET && configFlag != FLAG_NOT_SET) asfPrintError("The tool can either create or use the " "configuration file, not both!\n"); // Do the actual flagging & such for each flag if (createFlag != FLAG_NOT_SET) { sprintf(type, "%s", argv[createFlag+1]); configFile = (char *) MALLOC(sizeof(char)*1024); sprintf(configFile, "%s", argv[createFlag+2]); } if (configFlag != FLAG_NOT_SET) { configFile = (char *) MALLOC(sizeof(char)*1024); sprintf(configFile, "%s", argv[configFlag+1]); } if (log_f != FLAG_NOT_SET) { strcpy(logFile, argv[log_f+1]); } else { // default behavior: log to tmp<pid>.log sprintf(logFile, "tmp%i.log", pid); } logflag = TRUE; fLog = FOPEN(logFile, "a"); // Set old school quiet flag (for use in our libraries) quietflag = quiet_f != FLAG_NOT_SET; // Fetch required arguments strcpy(inFile, argv[argc-1]); // Report the command line asfSplashScreen(argc, argv); // Initialze structure dataset_t *data = (dataset_t *) MALLOC(sizeof(dataset_t)); strcpy(data->dataset_id, MAGIC_UNSET_STRING); strcpy(data->origin, MAGIC_UNSET_STRING); strcpy(data->title, MAGIC_UNSET_STRING); strcpy(data->online_link, MAGIC_UNSET_STRING); data->west_bounding = MAGIC_UNSET_DOUBLE; data->east_bounding = MAGIC_UNSET_DOUBLE; data->north_bounding = MAGIC_UNSET_DOUBLE; data->south_bounding = MAGIC_UNSET_DOUBLE; data->near_start_lat = MAGIC_UNSET_DOUBLE; data->near_start_lon = MAGIC_UNSET_DOUBLE; data->far_start_lat = MAGIC_UNSET_DOUBLE; data->far_start_lon = MAGIC_UNSET_DOUBLE; data->far_end_lat = MAGIC_UNSET_DOUBLE; data->far_end_lon = MAGIC_UNSET_DOUBLE; data->near_end_lat = MAGIC_UNSET_DOUBLE; data->near_end_lon = MAGIC_UNSET_DOUBLE; data->center_lat = MAGIC_UNSET_DOUBLE; data->center_lon = MAGIC_UNSET_DOUBLE; strcpy(data->processing_level, MAGIC_UNSET_STRING); strcpy(data->platform, MAGIC_UNSET_STRING); strcpy(data->instrument, MAGIC_UNSET_STRING); data->band_count = MAGIC_UNSET_INT; data->browse_location = NULL; data->browse_format = NULL; strcpy(data->access, MAGIC_UNSET_STRING); strcpy(data->copyright, MAGIC_UNSET_STRING); data->start_time = NULL; data->center_time = NULL; data->end_time = NULL; strcpy(data->orbit_direction, MAGIC_UNSET_STRING); strcpy(data->mode, MAGIC_UNSET_STRING); strcpy(data->spatial_reference, MAGIC_UNSET_STRING); strcpy(data->cell_value, MAGIC_UNSET_STRING); strcpy(data->raster_object, MAGIC_UNSET_STRING); data->row_count = MAGIC_UNSET_INT; data->col_count = MAGIC_UNSET_INT; strcpy(data->format, MAGIC_UNSET_STRING); data->fees = MAGIC_UNSET_DOUBLE; // Open XML for reading xmlDoc *doc = xmlReadFile(inFile, NULL, 0); if (!doc) asfPrintError("Could not parse metadata file (%s)\n", inFile); // Read in all parameters and perform error checking char string[512], tmp[255], errorMessage[8192]="Metadata parsing errors:\n"; int nValue, error = FALSE; double fValue; // Dataset ID strcpy(string, xml_get_string_value(doc, "metadata.idinfo.datsetid")); if (strlen(string) > MAX_DATASET_ID) { error = TRUE; sprintf(tmp, "Dataset ID - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_DATASET_ID); strcat(errorMessage, tmp); } else { strcpy(data->dataset_id, xml_get_string_value(doc, "metadata.idinfo.datsetid")); //printf("Dataset ID: %s\n", data->dataset_id); } // Origin strcpy(string, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.origin")); if (strlen(string) > MAX_ORIGIN) { error = TRUE; sprintf(tmp, "Origin - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_ORIGIN); strcat(errorMessage, tmp); } else { strcpy(data->origin, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.origin")); //printf("Origin: %s\n", data->origin); } // Title strcpy(string, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.title")); if (strlen(string) > MAX_TITLE) { error = TRUE; sprintf(tmp, "Title - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_TITLE); strcat(errorMessage, tmp); } else { strcpy(data->title, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.title")); //printf("Title: %s\n", data->title); } // Online link strcpy(string, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.onlink")); if (strlen(string) > MAX_ONLINE_LINK) { error = TRUE; sprintf(tmp, "Online link - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_ONLINE_LINK); strcat(errorMessage, tmp); } else { strcpy(data->online_link, xml_get_string_value(doc, "metadata.idinfo.citation.citeinfo.onlink")); //printf("Online link: %s\n", data->online_link); } // West bounding coordinate fValue = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.westbc"); if (fValue < -180.0 || fValue > 180.0) { error = TRUE; sprintf(tmp, "West bounding coordinate - Value (%.4lf) outside the " "expected value range (-180.0 < value < 180.0)\n", fValue); strcat(errorMessage, tmp); } else { data->west_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.westbc"); //printf("West bounding coordinate: %.4lf\n", data->west_bounding); } // East bounding coordinate fValue = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.eastbc"); if (fValue < -180.0 || fValue > 180.0) { error = TRUE; sprintf(tmp, "East bounding coordinate - Value (%.4lf) outside the " "expected value range (-180.0 < value < 180.0)\n", fValue); strcat(errorMessage, tmp); } else { data->east_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.eastbc"); //printf("East bounding coordinate: %.4lf\n", data->east_bounding); } // North bounding coordinate fValue = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.northbc"); if (fValue < -90.0 || fValue > 90.0) { error = TRUE; sprintf(tmp, "West bounding coordinate - Value (%.4lf) outside the " "expected value range (-90.0 < value < 90.0)\n", fValue); strcat(errorMessage, tmp); } else { data->north_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.northbc"); //printf("West bounding coordinate: %.4lf\n", data->north_bounding); } // South bounding coordinate fValue = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.southbc"); if (fValue < -90.0 || fValue > 90.0) { error = TRUE; sprintf(tmp, "South bounding coordinate - Value (%.4lf) outside the " "expected value range (-90.0 < value < 90.0)\n", fValue); strcat(errorMessage, tmp); } else { data->south_bounding = xml_get_double_value(doc, "metadata.idinfo.spdom.bounding.southbc"); //printf("South bounding coordinate: %.4lf\n", data->south_bounding); } // Open KML for reading char centerFile[512], boundaryFile[512], *baseName; char coordStr[50]; float height; baseName = get_basename(inFile); sprintf(boundaryFile, "%s_boundary.kml", baseName); sprintf(centerFile, "%s_center.kml", baseName); xmlDoc *xmlBoundary = xmlReadFile(boundaryFile, NULL, 0); if (!xmlBoundary) asfPrintError("Could not parse boundary file (%s)\n", boundaryFile); else { strcpy(coordStr, xml_get_string_value(xmlBoundary, "kml.Document.Placemark.Polygon.outerBoundaryIs.LinearRing.coordinates")); sscanf(coordStr, "%f,%f,%f\n%f,%f,%f\n%f,%f,%f\n%f,%f", &data->near_start_lat, &data->near_start_lon, &height, &data->near_end_lat, &data->near_end_lon, &height, &data->far_end_lat, &data->far_end_lon, &height, &data->far_start_lat, &data->far_start_lon); //printf("Near start latitude: %.4f\n", data->near_start_lat); //printf("Near start longitude: %.4f\n", data->near_start_lon); //printf("Near end latitude: %.4f\n", data->near_end_lat); //printf("Near end longitude: %.4f\n", data->near_end_lon); //printf("Far start latitude: %.4f\n", data->far_start_lat); //printf("Far start longitude: %.4f\n", data->far_start_lon); //printf("Far end latitude: %.4f\n", data->far_end_lat); //printf("Far end longitude: %.4f\n", data->far_end_lon); } xmlFreeDoc(xmlBoundary); xmlDoc *xmlCenter = xmlReadFile(centerFile, NULL, 0); if (!xmlCenter) asfPrintWarning("Could not parse center point file (%s)\n", centerFile); else { strcpy(coordStr, xml_get_string_value(xmlCenter, "kml.Document.Placemark.Point.coordinates")); sscanf(coordStr, "%f,%f", &data->center_lat, &data->center_lon); //printf("Center latitude: %.4f\n", data->center_lat); //printf("Center longitude: %.4f\n", data->center_lon); } xmlFreeDoc(xmlCenter); // Processing level strcpy(string, xml_get_string_value(doc, "metadata.idinfo.proclevl.prolevid")); if (strlen(string) > MAX_PROCESSING_LEVEL) { error = TRUE; sprintf(tmp, "Processing level - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_PROCESSING_LEVEL); strcat(errorMessage, tmp); } else { strcpy(data->processing_level, xml_get_string_value(doc, "metadata.idinfo.proclevl.prolevid")); //printf("Processing level: %s\n", data->processing_level); } // Place strcpy(string, xml_get_string_value(doc, "metadata.idinfo.keywords.place.placekey[0]")); if (strlen(string) > MAX_PLACE) { error = TRUE; sprintf(tmp, "Place - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_PLACE); strcat(errorMessage, tmp); } else { data->place = (char *) MALLOC(sizeof(char)*MAX_PLACE); strcpy(data->place, xml_get_string_value(doc, "metadata.idinfo.keywords.place.placekey[0]")); //printf("Place: %s\n", data->place); } // Platform strcpy(string, xml_get_string_value(doc, "metadata.idinfo.plainsid.platflnm")); if (strlen(string) > MAX_PLATFORM) { error = TRUE; sprintf(tmp, "Platform - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_PLATFORM); strcat(errorMessage, tmp); } else { strcpy(data->platform, xml_get_string_value(doc, "metadata.idinfo.plainsid.platflnm")); //printf("Platform: %s\n", data->platform); } // Instrument strcpy(string, xml_get_string_value(doc, "metadata.idinfo.plainsid.instflnm")); if (strlen(string) > MAX_INSTRUMENT) { error = TRUE; sprintf(tmp, "Instrument - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_INSTRUMENT); strcat(errorMessage, tmp); } else { strcpy(data->instrument, xml_get_string_value(doc, "metadata.idinfo.plainsid.instflnm")); //printf("Instrument: %s\n", data->instrument); } // Number of bands nValue = xml_get_int_value(doc, "metadata.idinfo.bandidnt.numbands"); if (nValue < 0) { error = TRUE; sprintf(tmp, "Number of bands - Value (%i) outside the " "expected value range (value > 0)\n", nValue); strcat(errorMessage, tmp); } else { data->band_count = xml_get_int_value(doc, "metadata.idinfo.bandidnt.numbands"); //printf("Number of bands: %i\n", data->band_count); } // Browse image location strcpy(string, xml_get_string_value(doc, "metadata.idinfo.browse.browsen")); if (strlen(string) > MAX_BROWSE_LOCATION) { error = TRUE; sprintf(tmp, "Browse image location - String length: %d, allowed " "characters: %d\n", (int) strlen(string), MAX_BROWSE_LOCATION); strcat(errorMessage, tmp); } else if (strcmp_case(string, MAGIC_UNSET_STRING) != 0) { data->browse_location = (char *) MALLOC(sizeof(char)*MAX_BROWSE_LOCATION); strcpy(data->browse_location, xml_get_string_value(doc, "metadata.idinfo.browse.browsen")); //printf("Browse image location: %s\n", data->browse_location); } // Browse image format strcpy(string, xml_get_string_value(doc, "metadata.idinfo.browse.browset")); if (strlen(string) > MAX_BROWSE_FORMAT) { error = TRUE; sprintf(tmp, "Browse image format - String length: %d, allowed characters:" " %d\n", (int) strlen(string), MAX_BROWSE_FORMAT); strcat(errorMessage, tmp); } else if (strcmp_case(string, MAGIC_UNSET_STRING) != 0) { data->browse_format = (char *) MALLOC(sizeof(char)*MAX_BROWSE_FORMAT); strcpy(data->browse_format, xml_get_string_value(doc, "metadata.idinfo.browse.browset")); //printf("Browse format: %s\n", data->browse_format); } // Data access level strcpy(string, xml_get_string_value(doc, "metadata.idinfo.secinfo.secclass")); if (strlen(string) > MAX_ACCESS) { error = TRUE; sprintf(tmp, "Data access level - String length: %d, allowed characters: " "%d\n", (int) strlen(string), MAX_ACCESS); strcat(errorMessage, tmp); } else { strcpy(data->access, xml_get_string_value(doc, "metadata.idinfo.secinfo.secclass")); //printf("Data access level: %s\n", data->access); } // Copyright strcpy(string, xml_get_string_value(doc, "metadata.idinfo.copyright")); if (strlen(string) > MAX_COPYRIGHT) { error = TRUE; sprintf(tmp, "Copyright - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_COPYRIGHT); strcat(errorMessage, tmp); } else { strcpy(data->copyright, xml_get_string_value(doc, "metadata.idinfo.copyright")); //printf("Copyright: %s\n", data->copyright); } // Start time char dateStr[25], timeStr[25], *message; int year, month, day, hour, minute, second; strcpy(dateStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.rngdates.begdate")); year = subStr(0, 4, dateStr); month = subStr(4, 2, dateStr); day = subStr(6, 2, dateStr); strcpy(timeStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.rngdates.begtime")); hour = subStr(0, 2, timeStr); minute = subStr(2, 2, timeStr); second = subStr(4, 2, timeStr); if (strcmp_case(dateStr, MAGIC_UNSET_STRING) != 0 && strcmp_case(timeStr, MAGIC_UNSET_STRING) != 0) { if (isNumeric(dateStr) && isNumeric(timeStr)) { message = checkTime(year, month, day, hour, minute, second); if (message) { error = TRUE; sprintf(tmp, "Start time - %s", message); strcat(errorMessage, tmp); } else { data->start_time = (char *) MALLOC(sizeof(char)*MAX_START_TIME); sprintf(data->start_time, "%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second); //printf("Start time: %s\n", data->start_time); } } } // Center time strcpy(dateStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.sngdate.caldate")); year = subStr(0, 4, dateStr); month = subStr(4, 2, dateStr); day = subStr(6, 2, dateStr); strcpy(timeStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.sngdate.time")); hour = subStr(0, 2, timeStr); minute = subStr(2, 2, timeStr); second = subStr(4, 2, timeStr); if (strcmp_case(dateStr, MAGIC_UNSET_STRING) != 0 && strcmp_case(timeStr, MAGIC_UNSET_STRING) != 0) { if (isNumeric(dateStr) && isNumeric(timeStr)) { message = checkTime(year, month, day, hour, minute, second); if (message) { error = TRUE; sprintf(tmp, "Center time - %s", message); strcat(errorMessage, tmp); } else { data->center_time = (char *) MALLOC(sizeof(char)*MAX_CENTER_TIME); sprintf(data->center_time, "%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second); //printf("Center time: %s\n", data->center_time); } } } // End time strcpy(dateStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.rngdates.enddate")); year = subStr(0, 4, dateStr); month = subStr(4, 2, dateStr); day = subStr(6, 2, dateStr); strcpy(timeStr, xml_get_string_value(doc, "metadata.idinfo.timeperd.timeinfo.rngdates.endtime")); hour = subStr(0, 2, timeStr); minute = subStr(2, 2, timeStr); second = subStr(4, 2, timeStr); if (strcmp_case(dateStr, MAGIC_UNSET_STRING) != 0 && strcmp_case(timeStr, MAGIC_UNSET_STRING) != 0) { if (isNumeric(dateStr) && isNumeric(timeStr)) { message = checkTime(year, month, day, hour, minute, second); if (message) { error = TRUE; sprintf(tmp, "End time - %s", message); strcat(errorMessage, tmp); } else { data->end_time = (char *) MALLOC(sizeof(char)*MAX_END_TIME); sprintf(data->end_time, "%04d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second); //printf("End time: %s\n", data->end_time); } } } // Orbit direction nValue = xml_get_int_value(doc, "metadata.dataqual.acqinfo.ascdscin"); if (nValue != MAGIC_UNSET_INT) { if (nValue < 0 || nValue > 1) { error = TRUE; sprintf(tmp, "Orbit direction - Value (%i) outside the " "expected value range (0 <= value <= 1)\n", nValue); strcat(errorMessage, tmp); } else { if (nValue == 0) strcpy(data->orbit_direction, "Ascending"); else if (nValue == 1) strcpy(data->orbit_direction, "Descending"); //printf("Orbit direction: %s\n", data->orbit_direction); } } else strcpy(data->orbit_direction, "Unknown"); // Imaging mode strcpy(string, xml_get_string_value(doc, "metadata.idinfo.plainsid.mode")); if (strcmp_case(string, MAGIC_UNSET_STRING) != 0) { if (strlen(string) > MAX_MODE) { error = TRUE; sprintf(tmp, "Imaging mode - String length: %d, allowed characters: %d" "\n", (int) strlen(string), MAX_MODE); strcat(errorMessage, tmp); } else { strcpy(data->mode, xml_get_string_value(doc, "metadata.idinfo.plainsid.mode")); //printf("Imaging mode: %s\n", data->mode); } } else strcpy(data->mode, "Unknown"); // Spatial reference strcpy(string, xml_get_string_value(doc, "metadata.spdoinfo.direct")); if (strcmp_case(string, "Point") != 0 && strcmp_case(string, "Vector") != 0 && strcmp_case(string, "Raster") != 0) { error = TRUE; sprintf(tmp, "Spatial reference - String (%s) not valid; expected " "\"Point\", \"Vector\" or \"Raster\"\n", string); strcat(errorMessage, tmp); } else { strcpy(data->spatial_reference, xml_get_string_value(doc, "metadata.spdoinfo.direct")); //printf("Spatial reference: %s\n", data->spatial_reference); } // Cell value type strcpy(string, xml_get_string_value(doc, "metadata.spdoinfo.rastinfo.cvaltype")); if (strlen(string) > MAX_CELL_VALUE) { error = TRUE; sprintf(tmp, "Cell value type - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_CELL_VALUE); strcat(errorMessage, tmp); } else { strcpy(data->cell_value, xml_get_string_value(doc, "metadata.spdoinfo.rastinfo.cvaltype")); //printf("Cell value type: %s\n", data->cell_value); } // Raster object type strcpy(string, xml_get_string_value(doc, "metadata.spdoinfo.rastinfo.rasttype")); if (strcmp_case(string, "Point") != 0 && strcmp_case(string, "Pixel") != 0 && strcmp_case(string, "Grid Cell") != 0 && strcmp_case(string, "Voxel") != 0 && strcmp_case(string, "Swath") != 0) { error = TRUE; sprintf(tmp, "Raster object type - String (%s) not valid; expected " "\"Point\", \"Pixel\", \"Grid Cell\", \"Voxel\" or \"Swath\".\n", string); strcat(errorMessage, tmp); } else { strcpy(data->raster_object, xml_get_string_value(doc, "metadata.spdoinfo.rastinfo.rasttype")); //printf("Raster object type: %s\n", data->raster_object); } // Number of rows nValue = xml_get_int_value(doc, "metadata.spdoinfo.rastinfo.rowcount"); if (nValue < 0) { error = TRUE; sprintf(tmp, "Number of rows - Value (%i) outside the " "expected value range (value > 0)\n", nValue); strcat(errorMessage, tmp); } else { data->row_count = xml_get_int_value(doc, "metadata.spdoinfo.rastinfo.rowcount"); //printf("Number of rows: %i\n", data->row_count); } // Number of columns nValue = xml_get_int_value(doc, "metadata.spdoinfo.rastinfo.colcount"); if (nValue < 0) { error = TRUE; sprintf(tmp, "Number of columns - Value (%i) outside the " "expected value range (value > 0)\n", nValue); strcat(errorMessage, tmp); } else { data->col_count = xml_get_int_value(doc, "metadata.spdoinfo.rastinfo.colcount"); //printf("Number of columns: %i\n", data->col_count); } // Format name strcpy(string, xml_get_string_value(doc, "metadata.distinfo.stdorder.digform.digtinfo.formname")); if (strlen(string) > MAX_FORMAT) { error = TRUE; sprintf(tmp, "Format name - String length: %d, allowed characters: %d\n", (int) strlen(string), MAX_FORMAT); strcat(errorMessage, tmp); } else { strcpy(data->format, xml_get_string_value(doc, "metadata.distinfo.stdorder.digform.digtinfo.formname")); //printf("Format name: %s\n", data->format); } // Fees fValue = xml_get_double_value(doc, "metadata.distinfo.stdorder.fees"); if (fValue < 0.0) { error = TRUE; sprintf(tmp, "Fees - Value (%.2lf) outside the expected value range " "(value >= 0.0)\n", fValue); strcat(errorMessage, tmp); } else { data->fees = xml_get_double_value(doc, "metadata.distinfo.stdorder.fees"); //printf("Fees: %.2lf\n", data->fees); } if (error) asfPrintError("%s", errorMessage); xmlFreeDoc(doc); xmlCleanupParser(); FREE(configFile); FCLOSE(fLog); remove(logFile); // Add dataset to database addData(data); FREE(data); asfPrintStatus("\nSuccessful completion!\n\n"); return(EXIT_SUCCESS); }
void M_LoadDefaults (void) { int i; int len; FILE* f; char def[80]; char strparm[100]; char* newstring = NULL; // killough int parm; boolean isstring; // set everything to base values numdefaults = sizeof(defaults) / sizeof(defaults[0]); for (i = 0 ; i < numdefaults ; i++) { if (defaults[i].location.ppsz) *defaults[i].location.ppsz = strdup(defaults[i].defaultvalue.psz); if (defaults[i].location.pi) *defaults[i].location.pi = defaults[i].defaultvalue.i; } // check for a custom default file #if ((defined GL_DOOM) && (defined _MSC_VER)) #define BOOM_CFG "glboom.cfg" #else #define BOOM_CFG "prboom.cfg" #endif i = M_CheckParm ("-config"); if (i && i < myargc-1) defaultfile = strdup(myargv[i+1]); else { const char* exedir = I_DoomExeDir(); /* get config file from same directory as executable */ #if 1 int len = doom_snprintf(NULL, 0, BOOM_CFG); defaultfile = malloc(len+1); doom_snprintf(defaultfile, len+1, BOOM_CFG); #else int len = doom_snprintf(NULL, 0, "%s/" BOOM_CFG, exedir); defaultfile = malloc(len+1); doom_snprintf(defaultfile, len+1, "%s/" BOOM_CFG, exedir); #endif } lprintf (LO_CONFIRM, " default file: %s\n",defaultfile); // read the file in, overriding any set defaults f = fopen (defaultfile, "r"); if (f) { while (!feof(f)) { isstring = false; if (fscanf (f, "%79s %[^\n]\n", def, strparm) == 2) { //jff 3/3/98 skip lines not starting with an alphanum if (!isalnum(def[0])) continue; if (strparm[0] == '"') { // get a string default isstring = true; len = strlen(strparm); newstring = (char *) malloc(len); strparm[len-1] = 0; // clears trailing double-quote mark strcpy(newstring, strparm+1); // clears leading double-quote mark } else if ((strparm[0] == '0') && (strparm[1] == 'x')) { // CPhipps - allow ints to be specified in hex sscanf(strparm+2, "%x", &parm); } else { sscanf(strparm, "%i", &parm); // Keycode hack removed } for (i = 0 ; i < numdefaults ; i++) if ((defaults[i].type != def_none) && !strcmp(def, defaults[i].name)) { // CPhipps - safety check if (isstring != IS_STRING(defaults[i])) { lprintf(LO_WARN, "M_LoadDefaults: Type mismatch reading %s\n", defaults[i].name); continue; } if (!isstring) { //jff 3/4/98 range check numeric parameters if ((defaults[i].minvalue==UL || defaults[i].minvalue<=parm) && (defaults[i].maxvalue==UL || defaults[i].maxvalue>=parm)) *(defaults[i].location.pi) = parm; } else { union { const char **c; char **s; } u; // type punning via unions u.c = defaults[i].location.ppsz; free(*(u.s)); *(u.s) = newstring; } break; } } } fclose (f); } //jff 3/4/98 redundant range checks for hud deleted here }
void gw_dm_listener(void *arg) { fd_set in_pipes; int i, j,num_mads; int greater, rc, rcm; char c; char info[GW_DM_MAX_INFO]; char s_id[GW_DM_MAX_ID]; char result[GW_DM_MAX_RESULT]; char action[GW_DM_MAX_ACTION]; char str[GW_DM_MAX_STRING]; char *s_host_id, *queue_name, *s_rank, *lasts; int job_id, host_id, rank; gw_dm_mad_t * dm_mad; pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL); pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); while (1) { greater = gw_dm_set_pipes (&in_pipes, &num_mads); select( greater+1, &in_pipes, NULL, NULL, NULL); for (i= 0; i<=greater; i++) { if ( FD_ISSET(i, &in_pipes) ) { dm_mad = gw_dm_get_mad_by_fd(i); if ( dm_mad == NULL ) continue; j = 0; do { rc = read(i, (void *) &c, sizeof(char)); str[j++] = c; } while ((rc > 0) && (c != '\n') && (j < (GW_DM_MAX_STRING-1))); str[j] = '\0'; if (rc <= 0) /* Error Reading message from MAD! */ { gw_log_print("DM",'W',"Error reading MAD (%s) message\n", dm_mad->name); pthread_mutex_lock(&(gw_dm.mutex)); gw_dm.scheduling = GW_TRUE; /* Prevents to call the scheduler while recovering*/ pthread_mutex_unlock(&(gw_dm.mutex)); rcm = gw_dm_mad_reload(dm_mad); if ( rcm == 0 ) { gw_log_print("DM",'I',"MAD (%s) successfully reloaded\n", dm_mad->name); gw_user_pool_dm_recover(dm_mad); gw_host_pool_dm_recover(dm_mad); gw_job_pool_dm_recover(dm_mad); } else { gw_log_print("DM",'E',"Error reloading the scheduler (%s)\n", dm_mad->name); dm_mad->mad_dm_pipe = -1; if ( num_mads == 1 ) { gw_log_print("DM",'E',"GridWay needs to be restarted! (no scheduler)\n"); return; } } pthread_mutex_lock(&(gw_dm.mutex)); gw_dm.scheduling = GW_FALSE; /* Activate the scheduler again*/ pthread_mutex_unlock(&(gw_dm.mutex)); continue; } info[0] = '\0'; sscanf(str,"%" GW2STR(GW_DM_MAX_ACTION) "s %" GW2STR(GW_DM_MAX_ID) "s %" GW2STR(GW_DM_MAX_RESULT) "s %" GW2STR(GW_DM_MAX_INFO) "[^\n]", action, s_id, result, info); #ifdef GWDMDEBUG gw_log_print("DM",'D',"MAD (%s) message %s %s %s %s (info length=%d).\n", dm_mad->name, action, s_id, result, info, strlen(info)); #endif if (strcmp(action, "SCHEDULE_JOB") == 0) { if (strcmp(result, "SUCCESS") == 0) { job_id = atoi(s_id); s_host_id = strtok_r(info, ":", &lasts); queue_name = strtok_r(NULL, ":", &lasts); s_rank = lasts; if (s_host_id == NULL || queue_name == NULL || s_rank == NULL) { gw_log_print("DM",'E',"Bad resource specification (%s) from scheduler.\n", info); continue; } host_id = atoi(s_host_id); rank = atoi(s_rank); gw_dm_dispatch_job(job_id, host_id, queue_name, rank); } else { gw_log_print("DM",'E',"Can't schedule job %s: %s.\n", s_id, info); job_id = atoi(s_id); gw_dm_uncheck_job(job_id); } } else if (strcmp(action, "SCHEDULE_END") == 0) { pthread_mutex_lock(&(gw_dm.mutex)); gw_dm.scheduling = GW_FALSE; pthread_mutex_unlock(&(gw_dm.mutex)); } else { gw_log_print("DM",'E',"Unknown MAD action %s.\n", action); } } } } }
/* * The data returned by the following routine is always in left-most byte * first and left-most bit first. If it doesn't return BitmapSuccess then * its arguments won't have been touched. This routine should look as much * like the Xlib routine XReadBitmapfile as possible. */ int XmuReadBitmapData ( FILE *fstream, /* handle on file */ unsigned int *width, /* RETURNED */ unsigned int *height, /* RETURNED */ unsigned char **datap, /* RETURNED */ int *x_hot, int *y_hot) /* RETURNED */ { unsigned char *data = NULL; /* working variable */ char line[MAX_SIZE]; /* input line from file */ int size; /* number of bytes of data */ char name_and_type[MAX_SIZE]; /* an input line */ char *type; /* for parsing */ int value; /* from an input line */ int version10p; /* boolean, old format */ int padding; /* to handle alignment */ int bytes_per_line; /* per scanline of data */ unsigned int ww = 0; /* width */ unsigned int hh = 0; /* height */ int hx = -1; /* x hotspot */ int hy = -1; /* y hotspot */ #ifndef Xmalloc #define Xmalloc(size) malloc(size) #endif /* first time initialization */ if (!hex_initialized) initHexTable(); /* error cleanup and return macro */ #define RETURN(code) { if (data) free (data); return code; } while (fgets(line, MAX_SIZE, fstream)) { if (strlen(line) == MAX_SIZE-1) { RETURN (BitmapFileInvalid); } if (sscanf(line,"#define %s %d",name_and_type,&value) == 2) { if (!(type = strrchr(name_and_type, '_'))) type = name_and_type; else type++; if (!strcmp("width", type)) ww = (unsigned int) value; if (!strcmp("height", type)) hh = (unsigned int) value; if (!strcmp("hot", type)) { if (type-- == name_and_type || type-- == name_and_type) continue; if (!strcmp("x_hot", type)) hx = value; if (!strcmp("y_hot", type)) hy = value; } continue; } if (sscanf(line, "static short %s = {", name_and_type) == 1) version10p = 1; else if (sscanf(line,"static unsigned char %s = {",name_and_type) == 1) version10p = 0; else if (sscanf(line, "static char %s = {", name_and_type) == 1) version10p = 0; else continue; if (!(type = strrchr(name_and_type, '_'))) type = name_and_type; else type++; if (strcmp("bits[]", type)) continue; if (!ww || !hh) RETURN (BitmapFileInvalid); if ((ww % 16) && ((ww % 16) < 9) && version10p) padding = 1; else padding = 0; bytes_per_line = (ww+7)/8 + padding; size = bytes_per_line * hh; data = (unsigned char *) Xmalloc ((unsigned int) size); if (!data) RETURN (BitmapNoMemory); if (version10p) { unsigned char *ptr; int bytes; for (bytes=0, ptr=data; bytes<size; (bytes += 2)) { if ((value = NextInt(fstream)) < 0) RETURN (BitmapFileInvalid); *(ptr++) = value; if (!padding || ((bytes+2) % bytes_per_line)) *(ptr++) = value >> 8; } } else { unsigned char *ptr; int bytes; for (bytes=0, ptr=data; bytes<size; bytes++, ptr++) { if ((value = NextInt(fstream)) < 0) RETURN (BitmapFileInvalid); *ptr=value; } } break; } /* end while */
static Image *ReadXTRNImage(const ImageInfo *image_info, ExceptionInfo *exception) { Image *image; ImageInfo *clone_info; void *param1, *param2, *param3; param1 = param2 = param3 = (void *) NULL; image = (Image *) NULL; clone_info=CloneImageInfo(image_info); if (clone_info->filename == NULL) { clone_info=DestroyImageInfo(clone_info); ThrowReaderException(FileOpenWarning,"No filename specified"); } if (LocaleCompare(image_info->magick,"XTRNFILE") == 0) { image=ReadImage(clone_info,exception); CatchException(exception); } else if (LocaleCompare(image_info->magick,"XTRNIMAGE") == 0) { Image **image_ptr; #ifdef ALL_IMAGEINFO ImageInfo **image_info_ptr; #endif (void) sscanf(clone_info->filename,"%lx,%lx",¶m1,¶m2); image_ptr=(Image **) param2; if (*image_ptr != (Image *) NULL) image=CloneImage(*image_ptr,0,0,MagickFalse,exception); #ifdef ALL_IMAGEINFO image_info_ptr=(ImageInfo **) param1; if (*image_info_ptr != (ImageInfo *) NULL) image_info=*image_info_ptr; #endif } else if (LocaleCompare(image_info->magick,"XTRNBLOB") == 0) { char **blob_data; size_t *blob_length; char filename[MagickPathExtent]; (void) sscanf(clone_info->filename,"%lx,%lx,%2048s",¶m1,¶m2, filename); blob_data=(char **) param1; blob_length=(size_t *) param2; image=BlobToImage(clone_info,*blob_data,*blob_length,exception); CatchException(exception); } else if (LocaleCompare(image_info->magick,"XTRNARRAY") == 0) { char *blob_data, filename[MagickPathExtent]; HRESULT hr; long lBoundl, lBoundu; SAFEARRAY *pSafeArray; size_t blob_length; *filename='\0'; (void) sscanf(clone_info->filename,"%lx,%2048s",¶m1,filename); hr=S_OK; pSafeArray=(SAFEARRAY *) param1; if (pSafeArray) { hr = SafeArrayGetLBound(pSafeArray, 1, &lBoundl); if (SUCCEEDED(hr)) { hr = SafeArrayGetUBound(pSafeArray, 1, &lBoundu); if (SUCCEEDED(hr)) { blob_length = lBoundu - lBoundl + 1; hr = SafeArrayAccessData(pSafeArray,(void**) &blob_data); if(SUCCEEDED(hr)) { *clone_info->filename='\0'; *clone_info->magick='\0'; if (*filename != '\0') (void) CopyMagickString(clone_info->filename,filename, MagickPathExtent); image=BlobToImage(clone_info,blob_data,blob_length, exception); hr=SafeArrayUnaccessData(pSafeArray); CatchException(exception); } } } } } clone_info=DestroyImageInfo(clone_info); return(image); }
unsigned int get_pid_by_name(const char *pro_name) { /* * search /proc/pid/status to find program's name * and then we can find the pid */ unsigned int pid = 1; // search start FILE *filp = NULL; char proc_status[20] = {0}; char status_info[100] = {0}; //file status information store in this char cur_name[100] = {0}; //program's name's max lenght unsigned int pid_max = get_sys_max_pid(); //max pid while (1) { /* * open 1 program's status file, then read data */ sprintf(proc_status, "/proc/%u/status", pid); #ifdef DEBUG printf("proc_status: %s, led: %d\n", proc_status, strlen(proc_status)); #endif filp = fopen(proc_status, "r"); if (!filp) { #ifdef DEBUG perror("fopen"); #endif if (pid >= pid_max) { fprintf(stderr, "Can not find pid of program %s\n", pro_name); break; } /* * current pid is no exist, go to search next */ pid++; continue; } /* * get one line to sparse by loop */ while ((!feof(filp)) && (fgets(status_info, 99, filp))) { if (sscanf(status_info, "Name: %s", cur_name) == 1) { /* * Run here means that we got current program's name, * next what we should do is to compare. */ if (!strcmp(cur_name, pro_name)) { fclose(filp); return pid; } /* * Not match, search next pid. */ bzero(cur_name, sizeof(cur_name)); break; } /* * Didn't scan target, scan next line. */ bzero(status_info, sizeof(status_info)); } /* end of one pid */ pid++; fclose(filp); bzero(status_info, sizeof(status_info)); } return 0; /* Haven't find the pid, return 0 */ }
/* Breakpoint command */ int cmd_bp() { char *str; int ret; eresi_Addr addr; char logbuf[BUFSIZ]; int idx; int index; elfsh_SAddr off = 0; char *name; elfshbp_t *cur; char **keys; int keynbr; PROFILER_IN(__FILE__, __FUNCTION__, __LINE__); /* build argc */ for (idx = 0; world.curjob->curcmd->param[idx] != NULL; idx++); str = revm_lookup_string(world.curjob->curcmd->param[0]); /* Select subcommand */ switch (idx) { /* List breakpoints */ case 0: e2dbg_output(" .:: Breakpoints ::.\n\n"); keys = hash_get_keys(&e2dbgworld.bp, &keynbr); for (index = 0; index < keynbr; index++) { cur = hash_get(&e2dbgworld.bp, keys[index]); name = revm_resolve(world.curjob->curfile, (eresi_Addr) cur->addr, &off); if (off) snprintf(logbuf, BUFSIZ, " %c [%02u] " XFMT " <%s + " UFMT ">\n", (e2dbg_is_watchpoint(cur) ? 'W' : 'B'), cur->id, cur->addr, name, off); else snprintf(logbuf, BUFSIZ, " %c [%02u] " XFMT " <%s>\n", (e2dbg_is_watchpoint(cur) ? 'W' : 'B'), cur->id, cur->addr, name); e2dbg_output(logbuf); } hash_free_keys(keys); if (!index) e2dbg_output(" [*] No breakpoints\n"); e2dbg_output("\n"); break; /* Supply a new breakpoint */ case 1: if (!elfsh_is_runtime_mode()) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Not in dynamic or debugger mode", -1); if (!str || !(*str)) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Invalid argument", -1); /* Break on a supplied virtual address */ if (IS_VADDR(str)) { if (sscanf(str + 2, AFMT, &addr) != 1) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Invalid virtual address requested", (-1)); } /* Resolve first a function name */ else { addr = e2dbg_breakpoint_find_addr(str); if (addr == 0) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Requested symbol address unknown", -1); } /* Add the breakpoint */ ret = e2dbg_breakpoint_add(addr); if (ret < 0) PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Breakpoint insertion failed\n", (-1)); if (ret >= 0) { name = revm_resolve(world.curjob->curfile, addr, &off); if (!off) snprintf(logbuf, BUFSIZ - 1, " [*] Breakpoint added at <%s> (" XFMT ")\n\n", name, addr); else snprintf(logbuf, BUFSIZ - 1, " [*] Breakpoint added at <%s + " UFMT "> (" XFMT ")\n\n", name, off, addr); e2dbg_output(logbuf); } break; /* Wrong command syntax */ default: PROFILER_ERR(__FILE__, __FUNCTION__, __LINE__, "Wrong arg number", (-1)); } PROFILER_ROUT(__FILE__, __FUNCTION__, __LINE__, (ret)); }