void __gnat_setenv (char *name, char *value) { #if defined (VMS) struct dsc$descriptor_s name_desc; $DESCRIPTOR (table_desc, "LNM$PROCESS"); char *host_pathspec = value; char *copy_pathspec; int num_dirs_in_pathspec = 1; char *ptr; long status; name_desc.dsc$w_length = strlen (name); name_desc.dsc$b_dtype = DSC$K_DTYPE_T; name_desc.dsc$b_class = DSC$K_CLASS_S; name_desc.dsc$a_pointer = name; /* ??? Danger, not 64bit safe. */ if (*host_pathspec == 0) /* deassign */ { status = LIB$DELETE_LOGICAL (&name_desc, &table_desc); /* no need to check status; if the logical name is not defined, that's fine. */ return; } ptr = host_pathspec; while (*ptr++) if (*ptr == ',') num_dirs_in_pathspec++; { int i, status; /* Alloca is guaranteed to be 32bit. */ ile_s *ile_array = alloca (sizeof (ile_s) * (num_dirs_in_pathspec + 1)); char *copy_pathspec = alloca (strlen (host_pathspec) + 1); char *curr, *next; strcpy (copy_pathspec, host_pathspec); curr = copy_pathspec; for (i = 0; i < num_dirs_in_pathspec; i++) { next = strchr (curr, ','); if (next == 0) next = strchr (curr, 0); *next = 0; ile_array[i].len = strlen (curr); /* Code 2 from lnmdef.h means it's a string. */ ile_array[i].code = 2; ile_array[i].adr = curr; /* retlen_adr is ignored. */ ile_array[i].retlen_adr = 0; curr = next + 1; } /* Terminating item must be zero. */ ile_array[i].len = 0; ile_array[i].code = 0; ile_array[i].adr = 0; ile_array[i].retlen_adr = 0; status = LIB$SET_LOGICAL (&name_desc, 0, &table_desc, 0, ile_array); if ((status & 1) != 1) LIB$SIGNAL (status); } #elif (defined (__vxworks) && defined (__RTP__)) \ || defined (__APPLE__) \ || defined (__OpenBSD__) setenv (name, value, 1); #else size_t size = strlen (name) + strlen (value) + 2; char *expression; expression = (char *) xmalloc (size * sizeof (char)); sprintf (expression, "%s=%s", name, value); putenv (expression); #if (defined (__FreeBSD__) && (__FreeBSD__ < 7)) \ || defined (__MINGW32__) \ ||(defined (__vxworks) && ! defined (__RTP__)) /* On some systems like FreeBSD 6.x and earlier, MacOS X and Windows, putenv is making a copy of the expression string so we can free it after the call to putenv */ free (expression); #endif #endif }
int update_phtable(presentity_t* presentity, str pres_uri, str body) { char* sphere= NULL; unsigned int hash_code; pres_entry_t* p; int ret= 0; str* xcap_doc= NULL; /* get new sphere */ sphere= extract_sphere(body); if(sphere==NULL) { LM_DBG("no sphere defined in new body\n"); return 0; } /* search for record in hash table */ hash_code= core_hash(&pres_uri, NULL, phtable_size); lock_get(&pres_htable[hash_code].lock); p= search_phtable(&pres_uri, presentity->event->evp->parsed, hash_code); if(p== NULL) { lock_release(&pres_htable[hash_code].lock); goto done; } if(p->sphere) { if(strcmp(p->sphere, sphere)!= 0) { /* new sphere definition */ shm_free(p->sphere); } else { /* no change in sphere definition */ lock_release(&pres_htable[hash_code].lock); pkg_free(sphere); return 0; } } p->sphere= (char*)shm_malloc(strlen(sphere)+ 1); if(p->sphere== NULL) { lock_release(&pres_htable[hash_code].lock); ret= -1; goto done; } strcpy(p->sphere, sphere); lock_release(&pres_htable[hash_code].lock); /* call for watchers status update */ if(presentity->event->get_rules_doc(&presentity->user, &presentity->domain, &xcap_doc)< 0) { LM_ERR("failed to retreive xcap document\n"); ret= -1; goto done; } update_watchers_status(pres_uri, presentity->event, xcap_doc); done: if(xcap_doc) { if(xcap_doc->s) pkg_free(xcap_doc->s); pkg_free(xcap_doc); } if(sphere) pkg_free(sphere); return ret; }
int main(int argc,char **argv){ int sockfd; char buffer[1024]; struct sockaddr_in server_addr; struct hostent *host; int portnumber,nbytes; char host_addr[256]; char host_file[256]; char local_file[256]; FILE *fp; char request[1024]; int send,totalsend; int i; char *pt; if(argc!=2){ fprintf(stderr,"Usage:%s web-address\a\n",argv[0]); exit (1); } printf("parameter.1 is: %s\n",argv[1]); ToLowerCase(argv[1]); printf("lowercase parameter.1 is: %s\n",argv[1]); GetHost(argv[1],host_addr,host_file,&portnumber); printf("webhost:%s\n",host_addr); printf("hostfile:%s\n",host_file); printf("portnumber:%d\n",portnumber); if((host=gethostbyname(host_addr))==NULL){ fprintf(stderr,"Gethostname error,%s\n",strerror(errno)); exit(1); } if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1){ fprintf(stderr,"SOcket Error:%s\a\n",strerror(errno)); exit(1); } bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_port=htons(portnumber); server_addr.sin_addr=*((struct in_addr *)host->h_addr); if(connect(sockfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1) { fprintf(stderr,"Connect Error:%s\a\n",strerror(errno)); exit(1); } sprintf(request,"GET /%s HTTP/1.1\r\nAccept:*/*\r\nAccept-language:zh-cn\r\n User-Agent:Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)\r\n Host:%s:%d\r\nConnection:Close\r\n\r\n",host_file,host_addr,portnumber); if(host_file && *host_file)pt = Rstrchr(host_file,'/'); else pt=0; memset(local_file,0,sizeof(local_file)); if(pt && *pt){ if((pt+1)&&*(pt+1))strcpy(local_file,pt+1); else memcpy(local_file,host_file,strlen(host_file)-1); } else if(host_file && *host_file)strcpy(local_file,host_file); else strcpy(local_file,"index.html"); printf("local filename to write:%s\n\n",local_file); send=0; totalsend=0; nbytes=strlen(request); while(totalsend<nbytes){ send=write(sockfd,request+totalsend,nbytes-totalsend); if(send==-1){ printf("send error!%s\n",strerror(errno)); exit(0); } totalsend+=send; printf("%d bytes send OK!\n",totalsend); } fp=fopen(local_file,"a"); if(!fp){ printf("create file error!%s\n",strerror(errno)); return 0; } printf("\nThe following is the response header:\n"); i=0; while((nbytes=read(sockfd,buffer,1))==1) if(i<4){ if(buffer[0]=='\r'||buffer[0]=='\n')i++; else i=0; printf("%c",buffer[0]); } else { fwrite(buffer,1,1,fp); i++; if(i%1024==0)fflush(fp); } fclose(fp); close(sockfd); exit(0); }
int main(int argc, char *argv[]) { pid_t sid; char upgfile[512]; int tPid; struct stat stat_buf; int use_storage_firmware = 0; if(argc < 2) { print_usage_exit(1); } /* FIX ME !!! * If we need further parameters for this procedure, then we should use * opt parser and formal parameters. * */ if(argv[1][0] == '-') { switch(argv[1][1]) { case 'b': strcpy(upgfile, "/tmp/mnt/USB/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no \"firmware.bin\" in USB or USB is not inserted\n"); print_usage_exit(1); } else { use_storage_firmware = 1; printf("Using \"firmware.bin\" in USB to upgrade.\n"); } strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin"); break; case 's': strcpy(upgfile, "/tmp/mnt/SD/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no \"firmware.bin\" in SD card or SD card is inserted\n"); print_usage_exit(1); } else { use_storage_firmware = 2; printf("Using \"firmware.bin\" in SD card to upgrade.\n"); } strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin"); break; case 'a': strcpy(upgfile, "/tmp/mnt/SD/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no \"firmware.bin\" in SD card or SD card is inserted\n"); strcpy(upgfile, "/tmp/mnt/USB/firmware.bin"); if(stat(upgfile, &stat_buf)) { printf("There is no \"firmware.bin\" in USB or USB is not inserted\n"); print_usage_exit(1); } else { use_storage_firmware = 1; printf("Using \"firmware.bin\" in USB to upgrade.\n"); strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/USB/firmware.bin"); } } else { use_storage_firmware = 2; printf("Using \"firmware.bin\" in SD card to upgrade.\n"); strcpy(upgfile, "/usr/sbin/ezpup /tmp/mnt/SD/firmware.bin"); } break; case 'u': if(argc == 3) { snprintf(upgfile, sizeof(upgfile), "wget %s -O /tmp/firmware 2>&1 | cat > /tmp/fw_log.txt", argv[2]); system(upgfile); if(!check_wget_ok("/tmp/fw_log.txt")) { printf("Unable to get URL %s\n", argv[2]); print_usage_exit(1); } snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup /tmp/firmware"); printf("Get firmware from %s successfully, using /tmp/firmware to upgrade.\n", argv[2]); } else { print_usage_exit(1); } break; } } else { snprintf(upgfile, sizeof(upgfile), "/usr/sbin/ezpup %s", argv[1]); } tPid = fork(); if(tPid < 0) { reboot(RB_AUTOBOOT); exit(1); // Error on fork } else if(tPid > 0) { exit(0); } else { FILE *fp; sid = setsid(); if (sid < 0) exit(EXIT_FAILURE); #if defined(PLATFORM_AXA) system("/usr/sbin/ezp-i2c gauge host booting"); #endif system("/sbin/stop_services.sh"); system("/sbin/reserve_link.sh"); system(upgfile); system("/tmp/ezp-i2c gauge upgrade finish"); fp = fopen("/tmp/fw_incorrect", "r"); if(fp) { printf("Upgrade failed, firmware incorrect\n"); fclose(fp); } else { printf("Upgrade successfully\n"); fp = fopen("/tmp/fw_correct", "w+"); if(fp) { fprintf(fp, "success\n"); fclose(fp); } } sleep(5); reboot(RB_AUTOBOOT); } return 0; }
int i_parseSequence(DCM_OBJECT ** object) { DCM_ELEMENT e; LST_HEAD *l; CONDITION cond; int index; SQ_TYPE type; SQ_REFRESULTSSOPINSTANCEUID *results; SQ_REQINTERPRETATIONAPPROVER *approver; SQ_REQPROCEDURECODE *diagnosis; void *pointer; static DCM_MAP_SQ sequences[] = { {DCM_IDREFERENCEDRESULTSSEQ, SQ_K_REFRESULTSSOPINSTANCEUID, HIS_K_INTRRSEQUENCE}, {DCM_RESINTERPAPPROVERSEQUENCE, SQ_K_REQINTERPRETATIONAPPROVER, HIS_K_INTIAPPSEQUENCE}, {DCM_RESDIAGNOSISCODESEQ, SQ_K_REQDIAGNOSISCODE, HIS_K_INTIDCSEQUENCE}, }; for (index = 0; index < (int) DIM_OF(sequences); index++) { e.tag = sequences[index].tag; cond = DCM_GetSequenceList(object, e.tag, &e.d.sq); if (cond != DCM_NORMAL) { if (cond != DCM_ELEMENTNOTFOUND) return -1; } else { cond = SQ_ParseSequence(&e, &type, &l); if (cond != SQ_NORMAL || type != sequences[index].type) return -2; p.Update_Flag |= sequences[index].his_field; pointer = LST_Head(&l); if (pointer != NULL) LST_Position(&l, pointer); while (pointer != NULL) { switch (sequences[index].tag) { case DCM_IDREFERENCEDRESULTSSEQ: strcpy(p.RRSequence[p.RRSequenceCount], ((SQ_REFRESULTSSOPINSTANCEUID *) pointer)->referencedSOPInstanceUID); p.RRSequenceCount++; break; case DCM_RESINTERPAPPROVERSEQUENCE: strcpy(p.IApprover[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->physiciansApproving); strcpy(p.IADates[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->approvalDates); strcpy(p.IATimes[p.IApprovalSequenceCount], ((SQ_REQINTERPRETATIONAPPROVER *) pointer)->approvalTimes); p.IApprovalSequenceCount++; break; case DCM_RESDIAGNOSISCODESEQ: strcpy(p.IDCSequence[p.IDCSequenceCount]. CodeValue, ((SQ_REQPROCEDURECODE *) pointer)->codeValue); strcpy(p.IDCSequence[p.IDCSequenceCount]. CodingSchemeDesignator, ((SQ_REQPROCEDURECODE *) pointer)->codingSchemeDesignator); strcpy(p.IDCSequence[p.IDCSequenceCount]. CodeMeaning, ((SQ_REQPROCEDURECODE *) pointer)->codeMeaning); p.IDCSequenceCount++; break; } pointer = LST_Next(&l); } } } return 0; /* e.tag = DCM_IDREFERENCEDRESULTSSEQ; cond = DCM_GetSequenceList(object, e.tag, &e.d.sq); if (cond == DCM_ELEMENTNOTFOUND) return 0; else if (cond != DCM_NORMAL) return -1; cond = SQ_ParseSequence(&e, &type, &l); if (cond != SQ_NORMAL) return -2; if (type == SQ_K_REFRESULTSSOPINSTANCEUID) { p.Update_Flag |= HIS_K_INTRRSEQUENCE; results = LST_Head(&l); if (results != NULL) LST_Position(&l, results); while (results != NULL) { strcpy(p.RRSequence[p.RRSequenceCount], results->referencedSOPInstanceUID); ++p.RRSequenceCount; results = LST_Next(&l); } } */ }
void funny_namreply(char *from, char **Args) { char *type, *channel; static char format[40]; static int last_width = -1; register char *ptr; register char *line; int user_count = 0; PasteArgs(Args, 2); type = Args[0]; channel = Args[1]; line = Args[2]; /* protocol violation by server */ if (!channel || !line) return; ptr = line; while (*ptr) { while (*ptr && (*ptr != ' ')) ptr++; user_count++; while (*ptr && (*ptr == ' ')) ptr++; } if (in_join_list(channel, from_server)) { set_display_target(channel, LOG_CRAP); if (do_hook(current_numeric, "%s %s %s %s", from, type, channel,line) && do_hook(NAMES_LIST, "%s %s", channel, line) && get_int_var(SHOW_CHANNEL_NAMES_VAR)) { put_it("%s", convert_output_format(fget_string_var(FORMAT_NAMES_FSET), "%s %s %d",update_clock(GET_TIME), channel, user_count)); print_funny_names(line); } if ((user_count == 1) && (*line == '@')) { ChannelList *chan; if ((chan = lookup_channel(channel, from_server, CHAN_NOUNLINK))) if ((ptr = get_cset_str_var(chan->csets, CHANMODE_CSET))) my_send_to_server(from_server, "MODE %s %s", channel, ptr); } got_info(channel, from_server, GOTNAMES); reset_display_target(); return; } if (last_width != get_int_var(CHANNEL_NAME_WIDTH_VAR)) { if ((last_width = get_int_var(CHANNEL_NAME_WIDTH_VAR)) != 0) sprintf(format, "%%s: %%-%u.%us %%s", (unsigned char) last_width, (unsigned char) last_width); else strcpy(format, "%s: %s\t%s"); } if (funny_min && (user_count < funny_min)) return; else if (funny_max && (user_count > funny_max)) return; if ((funny_flags & FUNNY_PRIVATE) && (*type == '=')) return; if ((funny_flags & FUNNY_PUBLIC) && ((*type == '*') || (*type == '@'))) return; if (type && channel) { if (match_str) { if (wild_match(match_str, channel) == 0) return; } if (do_hook(current_numeric, "%s %s %s %s", from, type, channel, line) && do_hook(NAMES_LIST, "%s %s", channel, line)) { set_display_target(channel, LOG_CRAP); if (fget_string_var(FORMAT_NAMES_FSET)) { put_it("%s", convert_output_format(fget_string_var(FORMAT_NAMES_FSET), "%s %s %d", update_clock(GET_TIME), channel, user_count)); print_funny_names(line); } else { switch (*type) { case '=': if (last_width &&(strlen(channel) > last_width)) { channel[last_width-1] = '>'; channel[last_width] = (char) 0; } put_it(format, "Pub", channel, line); break; case '*': put_it(format, "Prv", channel, line); break; case '@': put_it(format, "Sec", channel, line); break; } } reset_display_target(); } } }
int main(int ac, char **av) { int exp_eno; int lc; char *msg; char osname[OSNAMESZ]; int osnamelth, status; int name[] = { CTL_KERN, KERN_OSTYPE }; pid_t pid; struct passwd *ltpuser; if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) { tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg); } setup(); if ((tst_kvercmp(2, 6, 32)) <= 0) { exp_eno = EPERM; } else { /* ^^ Look above this warning. ^^ */ tst_resm(TWARN, "this test's results are based on potentially undocumented behavior in the kernel. read the NOTE in the source file for more details"); exp_eno = EACCES; exp_enos[0] = EACCES; } TEST_EXP_ENOS(exp_enos); for (lc = 0; TEST_LOOPING(lc); lc++) { /* reset Tst_count in case we are looping */ Tst_count = 0; strcpy(osname, "Linux"); osnamelth = SIZE(osname); TEST(sysctl(name, SIZE(name), 0, 0, osname, osnamelth)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "sysctl(2) succeeded unexpectedly"); } else { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == exp_eno) { tst_resm(TPASS | TTERRNO, "Got expected error"); } else if (errno == ENOSYS) { tst_resm(TCONF, "You may need to make CONFIG_SYSCTL_SYSCALL=y" " to your kernel config."); } else { tst_resm(TFAIL | TTERRNO, "Got unexpected error"); } } osnamelth = SIZE(osname); if ((ltpuser = getpwnam("nobody")) == NULL) { tst_brkm(TBROK, cleanup, "getpwnam() failed"); } /* set process ID to "ltpuser1" */ if (seteuid(ltpuser->pw_uid) == -1) { tst_brkm(TBROK, cleanup, "seteuid() failed, errno %d", errno); } if ((pid = FORK_OR_VFORK()) == -1) { tst_brkm(TBROK, cleanup, "fork() failed"); } if (pid == 0) { TEST(sysctl(name, SIZE(name), 0, 0, osname, osnamelth)); if (TEST_RETURN != -1) { tst_resm(TFAIL, "call succeeded unexpectedly"); } else { TEST_ERROR_LOG(TEST_ERRNO); if (TEST_ERRNO == exp_eno) { tst_resm(TPASS | TTERRNO, "Got expected error"); } else if (TEST_ERRNO == ENOSYS) { tst_resm(TCONF, "You may need to make CONFIG_SYSCTL_SYSCALL=y" " to your kernel config."); } else { tst_resm(TFAIL | TTERRNO, "Got unexpected error"); } } cleanup(); } else { /* wait for the child to finish */ wait(&status); } /* set process ID back to root */ if (seteuid(0) == -1) { tst_brkm(TBROK, cleanup, "seteuid() failed"); } } cleanup(); tst_exit(); }
/* 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; }
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); }
//=============================================================================================== //===== Функция IO Control //=============================================================================================== NTSTATUS IoCtlMyDriver(IN PDEVICE_OBJECT DeviceObject, IN PIRP Irp) { MegaDriverData *pdata; NTSTATUS status = STATUS_SUCCESS; ULONG BytesCount =0; // Число переданных/полученных байт (пока 0) PIO_STACK_LOCATION IrpStack=IoGetCurrentIrpStackLocation(Irp); UCHAR *buff;//for byte // Получаем указатель на расширение устройства PEXAMPLE_DEVICE_EXTENSION dx = (PEXAMPLE_DEVICE_EXTENSION)DeviceObject->DeviceExtension; // Выделяем из IRP значение IOCTL кода (причина вызова) ULONG ControlCode = IrpStack->Parameters.DeviceIoControl.IoControlCode; //лог DbgPrint(" >MegaDriver: IoCtlDriver - we are in"); //-------------------------------------------------------------------------------------------------------------- switch(ControlCode) { //тут нам прислали структурку с двумя строкаме case IOCTL_SEND_DATA_STRUCT: BytesCount = IrpStack->Parameters.DeviceIoControl.InputBufferLength; if(DataSize == BytesCount) { //=================================================================================================== //===== Получаем параметры //=================================================================================================== DbgPrint(" >MegaDriver: IoCtlDriver -> Check BufferIn Size - [ok]"); //проверяем параметр if(((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToFind == NULL) { DbgPrint(" >MegaDriver: IoCtlDriver -> Input Params == NULL"); break;//сваливаем нахер, ибо иначе может быть бсод... } //copy data strcpy(gData.procToFind, ((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToFind); strcpy(gData.procToOpen, ((MegaDriverData*)Irp->AssociatedIrp.SystemBuffer)->procToOpen); //show what we have DbgPrint(" >MegaDriver: IoCtlDriver -> Input Params:"); DbgPrint(" >MegaDriver: IoCtlDriver -> procToFind %s", gData.procToFind); DbgPrint(" >MegaDriver: IoCtlDriver -> procToOpen %s", gData.procToOpen); //if not BSOD =) gInited = TRUE; //Шикарно... тут мы приняли параметрЫ !!! //создаем нотифаер на создание нового процесса в системе PsSetCreateProcessNotifyRoutine(NotifyRoutine, FALSE); //=================================================================================================== //===== Чонить отсылаем обратно //=================================================================================================== pdata = (MegaDriverData*)Irp->AssociatedIrp.SystemBuffer; strcpy(gData.status, "all data accepted");//нипашет пока strcpy(pdata->procToFind, "11111111111"); strcpy(pdata->procToOpen, "22222222222"); if(FindProcess(FindBuffer)) { DbgPrint(" >MegaDriver: +++ PROCESS FOUND +++"); strcpy(pdata->status, "found"); } else { strcpy(pdata->status, "not found"); } Irp->IoStatus.Information = sizeof(gData); DbgPrint(" >MegaDriver: IoCtlDriver -> Status: %s", pdata->status); //осталось всеголишь найти нужный процесс))) //IoRequestDpc( //create DPC //IoInitializeDpcRequest //KeInsertQueueDpc //PsCreateSystemThread//IRQL_PASSIVE_LEVEL //WriteToFile("First test string from IoCtl \r\n"); //--------- } else DbgPrint(" >MegaDriver: IoCtlDriver -> Check BufferIn Size - [failed]"); break; case IOCTL_JUST_CHECK_STATUS: pdata = (MegaDriverData*)Irp->AssociatedIrp.SystemBuffer; strcpy(gData.status, "all data accepted");//нипашет пока strcpy(pdata->procToFind, "11111111111"); strcpy(pdata->procToOpen, "22222222222"); if(FindProcess(FindBuffer)) { DbgPrint(" >MegaDriver: +++ PROCESS FOUND +++"); strcpy(pdata->status, "found"); } else { strcpy(pdata->status, "not found"); } Irp->IoStatus.Information = sizeof(gData); DbgPrint(" >MegaDriver: IoCtlDriver -> Status: %s", pdata->status); break; default: DbgPrint(" >MegaDriver: IoCtlDriver -> UnKnown ControlCode"); } //-------------------------------------------------------------------------------------------------------------- IoCompleteRequest(Irp, IO_NO_INCREMENT);//завершаем обработку запроса return STATUS_SUCCESS; }
int main(int argc, char **argv) { float *Hydrograph = NULL; float ***MM5Input = NULL; float **PrecipLapseMap = NULL; float **PrismMap = NULL; unsigned char ***ShadowMap = NULL; float **SkyViewMap = NULL; float ***WindModel = NULL; int MaxStreamID, MaxRoadID; float SedDiams[NSEDSIZES]; /* Sediment particle diameters (mm) */ clock_t start, finish1; double runtime = 0.0; int t = 0; float roadarea; time_t tloc; int flag; int i; int j; int x; /* row counter */ int y; /* column counter */ int shade_offset; /* a fast way of handling arraay position given the number of mm5 input options */ int NStats; /* Number of meteorological stations */ uchar ***MetWeights = NULL; /* 3D array with weights for interpolating meteorological variables between the stations */ int NGraphics; /* number of graphics for X11 */ int *which_graphics; /* which graphics for X11 */ char buffer[32]; AGGREGATED Total = { /* Total or average value of a variable over the entire basin */ {0.0, NULL, NULL, NULL, NULL, 0.0}, /* EVAPPIX */ {0.0, 0.0, 0.0, 0.0, 0.0, NULL, NULL, 0.0, 0, 0.0}, /* PRECIPPIX */ {{0.0, 0.0}, {0.0, 0.0}, {0.0, 0.0}, 0.0, 0.0, 0.0}, /* PIXRAD */ {0.0, 0.0}, /* RADCLASSPIX */ {0.0, 0.0, 0, NULL, NULL, 0.0, 0, 0.0, 0.0, 0.0, 0.0, NULL, NULL, NULL, NULL, NULL, NULL, 0.0}, /* ROADSTRUCT*/ {0, 0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, /* SNOWPIX */ {0, 0.0, NULL, NULL, NULL, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, /*SOILPIX */ { 0.0, 0.0, 0.0, 0.0, 0.0}, /*SEDPIX */ { 0.0, 0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}, /*FINEPIX */ 0.0, 0.0, 0.0, 0.0, 0.0, 0l, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; CHANNEL ChannelData = {NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; DUMPSTRUCT Dump; EVAPPIX **EvapMap = NULL; INPUTFILES InFiles; LAYER Soil; LAYER Veg; LISTPTR Input = NULL; /* Linked list with input strings */ MAPSIZE Map; /* Size and location of model area */ MAPSIZE Radar; /* Size and location of area covered by precipitation radar */ MAPSIZE MM5Map; /* Size and location of area covered by MM5 input files */ METLOCATION *Stat = NULL; OPTIONSTRUCT Options; /* Structure with information which program options to follow */ PIXMET LocalMet; /* Meteorological conditions for current pixel */ FINEPIX ***FineMap = NULL; PRECIPPIX **PrecipMap = NULL; RADARPIX **RadarMap = NULL; RADCLASSPIX **RadMap = NULL; PIXRAD **RadiationMap = NULL; ROADSTRUCT **Network = NULL; /* 2D Array with channel information for each pixel */ SNOWPIX **SnowMap = NULL; MET_MAP_PIX **MetMap = NULL; SNOWTABLE *SnowAlbedo = NULL; SOILPIX **SoilMap = NULL; SEDPIX **SedMap = NULL; SOILTABLE *SType = NULL; SEDTABLE *SedType = NULL; SOLARGEOMETRY SolarGeo; /* Geometry of Sun-Earth system (needed for INLINE radiation calculations */ TIMESTRUCT Time; TOPOPIX **TopoMap = NULL; UNITHYDR **UnitHydrograph = NULL; UNITHYDRINFO HydrographInfo; /* Information about unit hydrograph */ VEGPIX **VegMap = NULL; VEGTABLE *VType = NULL; WATERBALANCE Mass = /* parameter for mass balance calculations */ { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 }; /***************************************************************************** Initialization Procedures *****************************************************************************/ if (argc != 2) { fprintf(stderr, "\nUsage: %s inputfile\n\n", argv[0]); fprintf(stderr, "DHSVM uses two output streams: \n"); fprintf(stderr, "Standard Out, for the majority of output \n"); fprintf(stderr, "Standard Error, for the final mass balance \n"); fprintf(stderr, "\nTo pipe output correctly to files: \n"); fprintf(stderr, "(cmd > f1) >& f2 \n"); fprintf(stderr, "where f1 is stdout_file and f2 is stderror_file\n"); exit(EXIT_FAILURE); } sprintf(commandline, "%s %s", argv[0], argv[1]); printf("%s \n", commandline); fprintf(stderr, "%s \n", commandline); strcpy(InFiles.Const, argv[1]); printf("\nRunning DHSVM %s\n", version); printf("\nSTARTING INITIALIZATION PROCEDURES\n\n"); /* Start recording time */ start = clock(); ReadInitFile(InFiles.Const, &Input); InitConstants(Input, &Options, &Map, &SolarGeo, &Time); InitFileIO(Options.FileFormat); InitTables(Time.NDaySteps, Input, &Options, &SType, &Soil, &VType, &Veg, &SnowAlbedo); InitTerrainMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &VegMap); CheckOut(Options.CanopyRadAtt, Veg, Soil, VType, SType, &Map, TopoMap, VegMap, SoilMap); if (Options.HasNetwork) InitChannel(Input, &Map, Time.Dt, &ChannelData, SoilMap, &MaxStreamID, &MaxRoadID, &Options); else if (Options.Extent != POINT) InitUnitHydrograph(Input, &Map, TopoMap, &UnitHydrograph, &Hydrograph, &HydrographInfo); InitNetwork(Map.NY, Map.NX, Map.DX, Map.DY, TopoMap, SoilMap, VegMap, VType, &Network, &ChannelData, Veg, &Options); InitMetSources(Input, &Options, &Map, Soil.MaxLayers, &Time, &InFiles, &NStats, &Stat, &Radar, &MM5Map); /* the following piece of code is for the UW PRISM project */ /* for real-time verification of SWE at Snotel sites */ /* Other users, set OPTION.SNOTEL to FALSE, or use TRUE with caution */ if (Options.Snotel == TRUE && Options.Outside == FALSE) { printf ("Warning: All met stations locations are being set to the vegetation class GLACIER\n"); printf ("Warning: This requires that you have such a vegetation class in your vegetation table\n"); printf("To disable this feature set Snotel OPTION to FALSE\n"); for (i = 0; i < NStats; i++) { printf("veg type for station %d is %d ", i, VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg); for (j = 0; j < Veg.NTypes; j++) { if (VType[j].Index == GLACIER) { VegMap[Stat[i].Loc.N][Stat[i].Loc.E].Veg = j; break; } } if (j == Veg.NTypes) { /* glacier class not found */ ReportError("MainDHSVM", 62); } printf("setting to glacier type (assumed bare class): %d\n", j); } } InitMetMaps(Time.NDaySteps, &Map, &Radar, &Options, InFiles.WindMapPath, InFiles.PrecipLapseFile, &PrecipLapseMap, &PrismMap, &ShadowMap, &SkyViewMap, &EvapMap, &PrecipMap, &RadarMap, &RadMap, SoilMap, &Soil, VegMap, &Veg, TopoMap, &MM5Input, &WindModel); InitInterpolationWeights(&Map, &Options, TopoMap, &MetWeights, Stat, NStats); InitDump(Input, &Options, &Map, Soil.MaxLayers, Veg.MaxLayers, Time.Dt, TopoMap, &Dump, &NGraphics, &which_graphics); if (Options.HasNetwork == TRUE) { InitChannelDump(&Options, &ChannelData, Dump.Path); ReadChannelState(Dump.InitStatePath, &(Time.Start), ChannelData.streams); if (Options.StreamTemp && Options.CanopyShading) InitChannelRVeg(&Time, ChannelData.streams); } InitSnowMap(&Map, &SnowMap); InitAggregated(Veg.MaxLayers, Soil.MaxLayers, &Total); InitModelState(&(Time.Start), &Map, &Options, PrecipMap, SnowMap, SoilMap, Soil, SType, VegMap, Veg, VType, Dump.InitStatePath, SnowAlbedo, TopoMap, Network, &HydrographInfo, Hydrograph); InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap, RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, Dump.InitStatePath); InitNewDay(Time.Current.JDay, &SolarGeo); if (NGraphics > 0) { printf("Initialzing X11 display and graphics \n"); InitXGraphics(argc, argv, Map.NY, Map.NX, NGraphics, &MetMap); } shade_offset = FALSE; if (Options.Shading == TRUE) shade_offset = TRUE; /* Done with initialization, delete the list with input strings */ DeleteList(Input); /***************************************************************************** Sediment Initialization Procedures *****************************************************************************/ if(Options.Sediment) { time (&tloc); srand (tloc); /* Randomize Random Generator */ /* Commenting the line above and uncommenting the line below allows for the comparison of scenarios. */ /* srand48 (0); */ printf("\nSTARTING SEDIMENT INITIALIZATION PROCEDURES\n\n"); ReadInitFile(Options.SedFile, &Input); InitParameters(Input, &Options, &Map, &Network, &ChannelData, TopoMap, &Time, SedDiams); InitSedimentTables(Time.NDaySteps, Input, &SedType, &SType, &VType, &Soil, &Veg); InitFineMaps(Input, &Options, &Map, &Soil, &TopoMap, &SoilMap, &FineMap); if (Options.HasNetwork){ printf("Initializing channel sediment\n\n"); InitChannelSedimentDump(&ChannelData, Dump.Path, Options.ChannelRouting); InitChannelSediment(ChannelData.streams, &Total); InitChannelSediment(ChannelData.roads, &Total); } InitSedMap( &Map, &SedMap); /* Done with initialization, delete the list with input strings */ DeleteList(Input); } /* setup for mass balance calculations */ Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap, RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap, &ChannelData, &roadarea); Mass.StartWaterStorage = Total.Soil.IExcess + Total.CanopyWater + Total.SoilWater + Total.Snow.Swq + Total.Soil.SatFlow; Mass.OldWaterStorage = Mass.StartWaterStorage; if (Options.Sediment) { Mass.StartChannelSedimentStorage = Total.ChannelSedimentStorage; Mass.LastChannelSedimentStorage = Mass.StartChannelSedimentStorage; } /* computes the number of grid cell contributing to one segment */ if (Options.StreamTemp) Init_segment_ncell(TopoMap, ChannelData.stream_map, Map.NY, Map.NX, ChannelData.streams); /***************************************************************************** Perform Calculations *****************************************************************************/ while (Before(&(Time.Current), &(Time.End)) || IsEqualTime(&(Time.Current), &(Time.End))) { ResetAggregate(&Soil, &Veg, &Total, &Options); if (IsNewMonth(&(Time.Current), Time.Dt)) InitNewMonth(&Time, &Options, &Map, TopoMap, PrismMap, ShadowMap, RadMap, &InFiles, Veg.NTypes, VType, NStats, Stat, Dump.InitStatePath); if (IsNewDay(Time.DayStep)) { InitNewDay(Time.Current.JDay, &SolarGeo); PrintDate(&(Time.Current), stdout); printf("\n"); } /* determine surface erosion and routing scheme */ SedimentFlag(&Options, &Time); InitNewStep(&InFiles, &Map, &Time, Soil.MaxLayers, &Options, NStats, Stat, InFiles.RadarFile, &Radar, RadarMap, &SolarGeo, TopoMap, RadMap, SoilMap, MM5Input, WindModel, &MM5Map); /* initialize channel/road networks for time step */ if (Options.HasNetwork) { channel_step_initialize_network(ChannelData.streams); channel_step_initialize_network(ChannelData.roads); } for (y = 0; y < Map.NY; y++) { for (x = 0; x < Map.NX; x++) { if (INBASIN(TopoMap[y][x].Mask)) { if (Options.Shading) LocalMet = MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats, Stat, MetWeights[y][x], TopoMap[y][x].Dem, &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar, RadarMap, PrismMap, &(SnowMap[y][x]), SnowAlbedo, MM5Input, WindModel, PrecipLapseMap, &MetMap, NGraphics, Time.Current.Month, SkyViewMap[y][x], ShadowMap[Time.DayStep][y][x], SolarGeo.SunMax, SolarGeo.SineSolarAltitude); else LocalMet = MakeLocalMetData(y, x, &Map, Time.DayStep, &Options, NStats, Stat, MetWeights[y][x], TopoMap[y][x].Dem, &(RadMap[y][x]), &(PrecipMap[y][x]), &Radar, RadarMap, PrismMap, &(SnowMap[y][x]), SnowAlbedo, MM5Input, WindModel, PrecipLapseMap, &MetMap, NGraphics, Time.Current.Month, 0.0, 0.0, SolarGeo.SunMax, SolarGeo.SineSolarAltitude); for (i = 0; i < Soil.MaxLayers; i++) { if (Options.HeatFlux == TRUE) { if (Options.MM5 == TRUE) SoilMap[y][x].Temp[i] = MM5Input[shade_offset + i + N_MM5_MAPS][y][x]; else SoilMap[y][x].Temp[i] = Stat[0].Data.Tsoil[i]; } else SoilMap[y][x].Temp[i] = LocalMet.Tair; } MassEnergyBalance(&Options, y, x, SolarGeo.SineSolarAltitude, Map.DX, Map.DY, Time.Dt, Options.HeatFlux, Options.CanopyRadAtt, Options.RoadRouting, Options.Infiltration, Veg.MaxLayers, &LocalMet, &(Network[y][x]), &(PrecipMap[y][x]), &(VType[VegMap[y][x].Veg-1]), &(VegMap[y][x]), &(SType[SoilMap[y][x].Soil-1]), &(SoilMap[y][x]), &(SnowMap[y][x]), &(EvapMap[y][x]), &(Total.Rad), &ChannelData, SkyViewMap); PrecipMap[y][x].SumPrecip += PrecipMap[y][x].Precip; } } } /* Average all RBM inputs over each segment */ if (Options.StreamTemp) { channel_grid_avg(ChannelData.streams); if (Options.CanopyShading) CalcCanopyShading(&Time, ChannelData.streams, &SolarGeo); } #ifndef SNOW_ONLY /* set sediment inflows to zero - they are incremented elsewhere */ if ((Options.HasNetwork) && (Options.Sediment)){ InitChannelSedInflow(ChannelData.streams); InitChannelSedInflow(ChannelData.roads); } RouteSubSurface(Time.Dt, &Map, TopoMap, VType, VegMap, Network, SType, SoilMap, &ChannelData, &Time, &Options, Dump.Path, SedMap, FineMap, SedType, MaxStreamID, SnowMap); if (Options.HasNetwork) RouteChannel(&ChannelData, &Time, &Map, TopoMap, SoilMap, &Total, &Options, Network, SType, PrecipMap, SedMap, LocalMet.Tair, LocalMet.Rh, SedDiams); /* Sediment Routing in Channel and output to sediment files */ if ((Options.HasNetwork) && (Options.Sediment)){ SPrintDate(&(Time.Current), buffer); flag = IsEqualTime(&(Time.Current), &(Time.Start)); if (Options.ChannelRouting){ if (ChannelData.roads != NULL) { RouteChannelSediment(ChannelData.roads, Time, &Dump, &Total, SedDiams); channel_save_sed_outflow_text(buffer, ChannelData.roads, ChannelData.sedroadout, ChannelData.sedroadflowout, flag); RouteCulvertSediment(&ChannelData, &Map, TopoMap, SedMap, &Total, SedDiams); } RouteChannelSediment(ChannelData.streams, Time, &Dump, &Total, SedDiams); channel_save_sed_outflow_text(buffer, ChannelData.streams, ChannelData.sedstreamout, ChannelData.sedstreamflowout, flag); } else { if (ChannelData.roads != NULL) { channel_save_sed_inflow_text(buffer, ChannelData.roads, ChannelData.sedroadinflow, SedDiams,flag); } channel_save_sed_inflow_text(buffer, ChannelData.streams, ChannelData.sedstreaminflow, SedDiams,flag); } SaveChannelSedInflow(ChannelData.roads, &Total); SaveChannelSedInflow(ChannelData.streams, &Total); } if (Options.Extent == BASIN) RouteSurface(&Map, &Time, TopoMap, SoilMap, &Options, UnitHydrograph, &HydrographInfo, Hydrograph, &Dump, VegMap, VType, SType, &ChannelData, SedMap, PrecipMap, SedType, LocalMet.Tair, LocalMet.Rh, SedDiams); #endif if (NGraphics > 0) draw(&(Time.Current), IsEqualTime(&(Time.Current), &(Time.Start)), Time.DayStep, &Map, NGraphics, which_graphics, VType, SType, SnowMap, SoilMap, SedMap, FineMap, VegMap, TopoMap, PrecipMap, PrismMap, SkyViewMap, ShadowMap, EvapMap, RadMap, MetMap, Network, &Options); Aggregate(&Map, &Options, TopoMap, &Soil, &Veg, VegMap, EvapMap, PrecipMap, RadMap, SnowMap, SoilMap, &Total, VType, Network, SedMap, FineMap, &ChannelData, &roadarea); MassBalance(&(Time.Current), &(Dump.Balance), &(Dump.SedBalance), &Total, &Mass, &Options); ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap, EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap, SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo,Hydrograph); IncreaseTime(&Time); t += 1; } ExecDump(&Map, &(Time.Current), &(Time.Start), &Options, &Dump, TopoMap, EvapMap, RadiationMap, PrecipMap, RadMap, SnowMap, MetMap, VegMap, &Veg, SoilMap, SedMap, Network, &ChannelData, FineMap, &Soil, &Total, &HydrographInfo, Hydrograph); FinalMassBalance(&(Dump.FinalBalance), &Total, &Mass, &Options, roadarea); /*printf("\nSTARTING CLEANUP\n\n"); cleanup(&Dump, &ChannelData, &Options);*/ printf("\nEND OF MODEL RUN\n\n"); /* record the run time at the end of each time loop */ finish1 = clock (); runtime = (finish1-start)/CLOCKS_PER_SEC; printf("***********************************************************************************"); printf("\nRuntime Summary:\n"); printf("%6.2f hours elapsed for the simulation period of %d hours (%.1f days) \n", runtime/3600, t*Time.Dt/3600, (float)t*Time.Dt/3600/24); return EXIT_SUCCESS; }
int main(int argc, char **argv) { options_t options; int doversion = 0; int dohelp = 0; int userclasses = 0; int ch; int option_index = 0; char prefix[IF_NAMESIZE + 3]; pid_t pid; const struct option longopts[] = { {"arp", no_argument, NULL, 'a'}, {"script",required_argument, NULL, 'c'}, {"debug", no_argument, NULL, 'd'}, {"hostname", required_argument, NULL, 'h'}, {"classid", required_argument, NULL, 'i'}, {"release", no_argument, NULL, 'k'}, {"leasetime", required_argument, NULL, 'l'}, {"metric", required_argument, NULL, 'm'}, {"renew", no_argument, NULL, 'n'}, {"persistent", no_argument, NULL, 'p'}, {"request", required_argument, NULL, 's'}, {"timeout", required_argument, NULL, 't'}, {"userclass", required_argument, NULL, 'u'}, {"fqdn", optional_argument, NULL, 'F'}, {"nogateway", no_argument, NULL, 'G'}, {"sethostname", no_argument, NULL, 'H'}, {"clientid", required_argument, NULL, 'I'}, {"nontp", no_argument, NULL, 'N'}, {"nodns", no_argument, NULL, 'R'}, {"nonis", no_argument, NULL, 'Y'}, {"help", no_argument, &dohelp, 1}, {"version", no_argument, &doversion, 1}, {NULL, 0, NULL, 0} }; /* Sanitize our fd's */ int zero; if ((zero = open (_PATH_DEVNULL, O_RDWR, 0)) >= 0) { while (zero < 3) zero = dup (zero); close(zero); } openlog (PACKAGE, LOG_PID, LOG_LOCAL0); memset (&options, 0, sizeof (options_t)); options.script = (char *) DEFAULT_SCRIPT; snprintf (options.classid, CLASS_ID_MAX_LEN, "%s %s", PACKAGE, VERSION); options.doarp = false; options.dodns = true; options.donis = true; options.dontp = true; options.dogateway = true; gethostname (options.hostname, sizeof (options.hostname)); if (strcmp (options.hostname, "(none)") == 0 || strcmp (options.hostname, "localhost") == 0) memset (options.hostname, 0, sizeof (options.hostname)); options.timeout = DEFAULT_TIMEOUT; while ((ch = getopt_long(argc, argv, "ac:dh:i:kl:m:nps:t:u:F:GHI:NRY", longopts, &option_index)) != -1) switch (ch) { case 0: if (longopts[option_index].flag) break; logger (LOG_ERR, "option `%s' should set a flag", longopts[option_index].name); exit (EXIT_FAILURE); break; case 'a': options.doarp = true; break; case 'c': options.script = optarg; break; case 'd': setloglevel(LOG_DEBUG); break; case 'h': if (strlen (optarg) > HOSTNAME_MAX_LEN) { logger(LOG_ERR, "`%s' too long for HostName string, max is %d", optarg, HOSTNAME_MAX_LEN); exit (EXIT_FAILURE); } else strcpy (options.hostname, optarg); break; case 'i': if (strlen(optarg) > CLASS_ID_MAX_LEN) { logger (LOG_ERR, "`%s' too long for ClassID string, max is %d", optarg, CLASS_ID_MAX_LEN); exit (EXIT_FAILURE); } else sprintf(options.classid, "%s", optarg); break; case 'k': options.signal = SIGHUP; break; case 'l': STRINGINT (optarg, options.leasetime); if (options.leasetime <= 0) { logger (LOG_ERR, "leasetime must be a positive value"); exit (EXIT_FAILURE); } break; case 'm': STRINGINT(optarg, options.metric); break; case 'n': options.signal = SIGALRM; break; case 'p': options.persistent = true; break; case 's': if (! inet_aton (optarg, &options.requestaddress)) { logger (LOG_ERR, "`%s' is not a valid IP address", optarg); exit (EXIT_FAILURE); } break; case 't': STRINGINT (optarg, options.timeout); if (options.timeout < 0) { logger (LOG_ERR, "timeout must be a positive value"); exit (EXIT_FAILURE); } break; case 'u': { int i; int offset = 0; for (i = 0; i < userclasses; i++) offset += (int) options.userclass[offset] + 1; if (offset + 1 + strlen (optarg) > USERCLASS_MAX_LEN) { logger (LOG_ERR, "userclass overrun, max is %d", USERCLASS_MAX_LEN); exit (EXIT_FAILURE); } userclasses++; memcpy (options.userclass + offset + 1 , optarg, strlen (optarg)); options.userclass[offset] = strlen (optarg); options.userclass_len += (strlen (optarg)) + 1; } break; case 'F': if (strcmp (optarg, "none") == 0) options.fqdn = FQDN_NONE; else if (strcmp (optarg, "ptr") == 0) options.fqdn = FQDN_PTR; else if (strcmp (optarg, "both") == 0) options.fqdn = FQDN_BOTH; else { logger (LOG_ERR, "invalid value `%s' for FQDN", optarg); exit (EXIT_FAILURE); } break; case 'G': options.dogateway = false; break; case 'H': options.dohostname = true; break; case 'I': if (strlen (optarg) > CLIENT_ID_MAX_LEN) { logger (LOG_ERR, "`%s' is too long for ClientID, max is %d", optarg, CLIENT_ID_MAX_LEN); exit (EXIT_FAILURE); } else sprintf(options.clientid, "%s", optarg); break; case 'N': options.dontp = false; break; case 'R': options.dodns = false; break; case 'Y': options.donis = false; break; case '?': usage (); exit (EXIT_FAILURE); default: usage (); exit (EXIT_FAILURE); } if (doversion) printf (""PACKAGE" "VERSION"\n"); if (dohelp) usage (); if (optind < argc) { if (strlen (argv[optind]) > IF_NAMESIZE) { logger (LOG_ERR, "`%s' is too long for an interface name (max=%d)", argv[optind], IF_NAMESIZE); exit (EXIT_FAILURE); } strcpy (options.interface, argv[optind]); } else { /* If only version was requested then exit now */ if (doversion || dohelp) exit (EXIT_SUCCESS); logger (LOG_ERR, "no interface specified", options.interface); exit (EXIT_FAILURE); } if (geteuid ()) { logger (LOG_ERR, "you need to be root to run "PACKAGE); exit (EXIT_FAILURE); } snprintf (prefix, IF_NAMESIZE, "%s: ", options.interface); setlogprefix (prefix); snprintf (options.pidfile, sizeof (options.pidfile), PIDFILE, options.interface); if (options.signal != 0) { int killed = -1; pid = read_pid (options.pidfile); if (pid != 0) logger (LOG_INFO, "sending signal %d to pid %d", options.signal, pid); if (! pid || (killed = kill (pid, options.signal))) logger (options.signal == SIGALRM ? LOG_INFO : LOG_ERR, ""PACKAGE" not running"); if (pid != 0 && (options.signal != SIGALRM || killed != 0)) unlink (options.pidfile); if (killed == 0) exit (EXIT_SUCCESS); if (options.signal != SIGALRM) exit (EXIT_FAILURE); } umask (022); if (mkdir (CONFIGDIR, S_IRUSR |S_IWUSR |S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST ) { logger (LOG_ERR, "mkdir(\"%s\",0): %s\n", CONFIGDIR, strerror (errno)); exit (EXIT_FAILURE); } if (mkdir (ETCDIR, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST ) { logger (LOG_ERR, "mkdir(\"%s\",0): %s\n", ETCDIR, strerror (errno)); exit (EXIT_FAILURE); } if ((pid = read_pid (options.pidfile)) > 0 && kill (pid, 0) == 0) { logger (LOG_ERR, ""PACKAGE" already running (%s)", options.pidfile); exit (EXIT_FAILURE); } make_pid (options.pidfile); logger (LOG_INFO, PACKAGE " " VERSION " starting"); if (dhcp_run (&options)) { unlink (options.pidfile); exit (EXIT_FAILURE); } exit (EXIT_SUCCESS); }
/*----------------------------------------------------------------------*/ static long dsetRead_devAiAsyncSerial(aiRecord *pai) { CONTEXT *p_myContext; char p_writeBuffer[BUFLEN]; char p_readBuffer[BUFLEN]; int myPortNumber; char p_myCommand[BUFLEN]; #ifdef DEBUG1 printf( __FILE__ "[%d] -> %s\n", __LINE__, __func__); #endif p_myContext = (CONTEXT *)pai->dpvt; myPortNumber=p_myContext->portNumber; strcpy(p_myCommand,p_myContext->p_command); /* Get the lock or callback */ if (lockSerialPort2(myPortNumber,LOCK, pai->name)<=ERROR) { #ifdef DEBUG2 printf( __FILE__ "[%d] Error: Couldn't lock %s\n", __LINE__, getSerialPortName2(myPortNumber)); printf( __FILE__ "[%d] lockOwner is %s\n", __LINE__, getSerialPortLockOwner2(myPortNumber)); #endif pai->pact=TRUE; callbackRequestDelayed(p_myContext->p_callback,SLEEPTIME_CALLBACK); return(NO_CONVERSION); } /* end_of_if */ /* construct request for the pressure */ /* strcat(p_writeBuffer,"P"); sprintf(str,"%d",p_myContext->secondaryAddress); */ strcpy(p_writeBuffer,p_myCommand); strcat(p_writeBuffer,TERMINATOR); #ifdef DEBUG2 printf( __FILE__ "[%d] Writing >%s< for %s on %s\n", __LINE__, p_writeBuffer, pai->name, getSerialPortName2(myPortNumber)); #endif if (writeSerialPort2(myPortNumber, p_writeBuffer)<= ERROR) { printf( __FILE__ "[%d] Error: Couldn't write >%s< to %s\n", __LINE__, p_writeBuffer, pai->name); sleep(SLEEPTIME_ERROR); return(ERROR); } usleep(USLEEPTIME_WRITE); if (readSerialPort2(myPortNumber, p_readBuffer,BUFLEN)<=ERROR) { printf( __FILE__ "[%d] Error: Couldn't Read %s\n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } #ifdef DEBUG2 printf( __FILE__ "[%d] %s read >%s<\n", __LINE__, pai->name, p_readBuffer); #endif usleep(USLEEPTIME_READ); if (lockSerialPort2(myPortNumber, UNLOCK, pai->name) <=ERROR) { printf( __FILE__ "[%d] Error: Couldn't unlock %s\n", __LINE__, getSerialPortName2(myPortNumber)); sleep(SLEEPTIME_ERROR); return(ERROR); } if ( (strncmp(p_readBuffer,"HV_OFF!",7)==0) || (strncmp(p_readBuffer,"WAIT",4)==0) || (strncmp(p_readBuffer,"CONTROL!",8)==0) || (strncmp(p_readBuffer,"PROTECT!",8)==0) || (strncmp(p_readBuffer,"NOGAUGE!",8)==0)) { printf( __FILE__ "[%d] Error: Check the probe\n", __LINE__); printf( __FILE__ "[%d] Error: Check the hardware\n", __LINE__); pai->udf = TRUE; } else { pai->val = atof(p_readBuffer); pai->udf = FALSE; } pai->pact = FALSE; #ifdef DEBUG2 printf( __FILE__ "[%d] <- %s\n", __LINE__, __func__); #endif return(NO_CONVERSION); }
/* 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() */
void find_wireless_nic(void) { static int found = 0; FILE *file; int sock; struct ifreq ifr; struct ethtool_value ethtool; struct ethtool_drvinfo driver; int ret; if (found++) return; wireless_nic[0] = 0; rfkill_path[0] = 0; powersave_path[0] = 0; strcpy(wireless_nic, "wlan0"); file = popen("/sbin/iwpriv -a 2> /dev/null", "r"); if (!file) return; while (!feof(file)) { char line[1024]; memset(line, 0, 1024); if (fgets(line, 1023, file)==NULL) break; if (strstr(line, "get_power:Power save level")) { char *c; c = strchr(line, ' '); if (c) *c = 0; strcpy(wireless_nic, line); } if (strstr(line, "wlan0:")) strcpy(wireless_nic, "wlan0"); } pclose(file); if (strlen(wireless_nic)==0) return; memset(&ifr, 0, sizeof(struct ifreq)); memset(ðtool, 0, sizeof(struct ethtool_value)); sock = socket(AF_INET, SOCK_DGRAM, 0); if (sock<0) return; strcpy(ifr.ifr_name, wireless_nic); /* Check if the interface is up */ ret = ioctl(sock, SIOCGIFFLAGS, &ifr); if (ret<0) { close(sock); return; } memset(&driver, 0, sizeof(driver)); driver.cmd = ETHTOOL_GDRVINFO; ifr.ifr_data = (void*) &driver; ret = ioctl(sock, SIOCETHTOOL, &ifr); sprintf(rfkill_path,"/sys/bus/pci/devices/%s/rfkill/rfkill0/state", driver.bus_info); sprintf(powersave_path,"/sys/bus/pci/devices/%s/power_level", driver.bus_info); close(sock); }
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 UDPServer::send(const std::string &s) { char buf[BUF_SIZE]; strcpy(buf, s.c_str()); socklen_t len = sizeof(_cliaddr); sendto(_sockfd, buf, strlen(buf), 0, (SA *)&_cliaddr, len); }
char* menu_requestfile(char* file, char *title, char* path, char *exts){ char *dir; int allocmem = file == NULL; int tmplen = 0; char parent_dir_str[5]; #ifdef DINGOO_NATIVE static char dingoo_default_path[]="A:\\"; #endif /* DINGOO_NATIVE */ /* TODO clear all the dyanamic memory allocations in this routine and require caller to pre-allocate */ if (allocmem) file = malloc(PATH_MAX); #ifdef DEBUG_ALWAYS_RETURN_ADJUSTRIS_GB strcpy(file, "adjustris.gb"); return file; #endif /* DEBUG_ALWAYS_RETURN_ADJUSTRIS_GB */ if(path) { strcpy(file, path); tmplen = strlen(file); if (tmplen >=1) { if (file[tmplen-1] != DIRSEP_CHAR) strcat(file, DIRSEP); /* this is very fragile, e.g. what if dir was specified but does not exist */ } } else strcpy(file, ""); snprintf(parent_dir_str, sizeof(parent_dir_str), "..%s", DIRSEP); while(dir = menu_browsedir(file, file+strlen(file),title,exts)){ if (!strcmp(dir, parent_dir_str)) { /* need to go up a directory */ dir--; if (dir > file) { *dir = '\0'; while (dir >= file && *dir != DIRSEP_CHAR) { *dir = '\0'; dir--; } } if (strlen(file) == 0) { #ifdef DINGOO_NATIVE if (dingoo_default_path[0] == 'A') dingoo_default_path[0] = 'B'; else dingoo_default_path[0] = 'A'; sprintf(file, "%s", dingoo_default_path); /* ** If there is no MiniSD card in B: ** then an empty list is displayed ** click the parent directory to ** toggle back to A: */ #else sprintf(file, ".%s", DIRSEP); #endif /* DINGOO_NATIVE */ dir = file + strlen(file)+1; *dir = '\0'; } } /* ** Check to see if we have a file name, ** or a new directory name to scan ** Directory name will have trailing path sep character ** FIXME check for "../" and dirname the dir */ tmplen = strlen(dir); if (tmplen >=1) if (dir[tmplen-1] != DIRSEP_CHAR) { if (allocmem) file = realloc(file, strlen(file)+1); break; } } if(!dir) file = NULL; /* FIXME what it file was not null when function was called, what about free'ing this is we allocated it? */ return file; }
static void __init offb_init_fb(const char *name, const char *full_name, int width, int height, int depth, int pitch, unsigned long address, int foreign_endian, struct device_node *dp) { unsigned long res_size = pitch * height * (depth + 7) / 8; struct offb_par *par = &default_par; unsigned long res_start = address; struct fb_fix_screeninfo *fix; struct fb_var_screeninfo *var; struct fb_info *info; if (!request_mem_region(res_start, res_size, "offb")) return; printk(KERN_INFO "Using unsupported %dx%d %s at %lx, depth=%d, pitch=%d\n", width, height, name, address, depth, pitch); if (depth != 8 && depth != 15 && depth != 16 && depth != 32) { printk(KERN_ERR "%s: can't use depth = %d\n", full_name, depth); release_mem_region(res_start, res_size); return; } info = framebuffer_alloc(sizeof(u32) * 16, NULL); if (info == 0) { release_mem_region(res_start, res_size); return; } fix = &info->fix; var = &info->var; info->par = par; strcpy(fix->id, "OFfb "); strncat(fix->id, name, sizeof(fix->id) - sizeof("OFfb ")); fix->id[sizeof(fix->id) - 1] = '\0'; var->xres = var->xres_virtual = width; var->yres = var->yres_virtual = height; fix->line_length = pitch; fix->smem_start = address; fix->smem_len = pitch * height; fix->type = FB_TYPE_PACKED_PIXELS; fix->type_aux = 0; par->cmap_type = cmap_unknown; if (depth == 8) offb_init_palette_hacks(info, dp, name, address); else fix->visual = FB_VISUAL_TRUECOLOR; var->xoffset = var->yoffset = 0; switch (depth) { case 8: var->bits_per_pixel = 8; var->red.offset = 0; var->red.length = 8; var->green.offset = 0; var->green.length = 8; var->blue.offset = 0; var->blue.length = 8; var->transp.offset = 0; var->transp.length = 0; break; case 15: /* RGB 555 */ var->bits_per_pixel = 16; var->red.offset = 10; var->red.length = 5; var->green.offset = 5; var->green.length = 5; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; break; case 16: /* RGB 565 */ var->bits_per_pixel = 16; var->red.offset = 11; var->red.length = 5; var->green.offset = 5; var->green.length = 6; var->blue.offset = 0; var->blue.length = 5; var->transp.offset = 0; var->transp.length = 0; break; case 32: /* RGB 888 */ var->bits_per_pixel = 32; var->red.offset = 16; var->red.length = 8; var->green.offset = 8; var->green.length = 8; var->blue.offset = 0; var->blue.length = 8; var->transp.offset = 24; var->transp.length = 8; break; } var->red.msb_right = var->green.msb_right = var->blue.msb_right = var->transp.msb_right = 0; var->grayscale = 0; var->nonstd = 0; var->activate = 0; var->height = var->width = -1; var->pixclock = 10000; var->left_margin = var->right_margin = 16; var->upper_margin = var->lower_margin = 16; var->hsync_len = var->vsync_len = 8; var->sync = 0; var->vmode = FB_VMODE_NONINTERLACED; /* set offb aperture size for generic probing */ info->apertures = alloc_apertures(1); if (!info->apertures) goto out_aper; info->apertures->ranges[0].base = address; info->apertures->ranges[0].size = fix->smem_len; info->fbops = &offb_ops; info->screen_base = ioremap(address, fix->smem_len); info->pseudo_palette = (void *) (info + 1); info->flags = FBINFO_DEFAULT | FBINFO_MISC_FIRMWARE | foreign_endian; fb_alloc_cmap(&info->cmap, 256, 0); if (register_framebuffer(info) < 0) goto out_err; printk(KERN_INFO "fb%d: Open Firmware frame buffer device on %s\n", info->node, full_name); return; out_err: iounmap(info->screen_base); out_aper: iounmap(par->cmap_adr); par->cmap_adr = NULL; framebuffer_release(info); release_mem_region(res_start, res_size); }
char *menu_requestdir(const char *title, const char *path){ char *dir=NULL, **ldirs; int ldirsz, ldirn=0, ret, l; DIR *cd; struct dirent *d; #ifndef DT_DIR struct stat s; #endif /* DT_DIR */ char *cdpath; //#ifndef DT_DIR char tmpfname[PATH_MAX]; char *tmpfname_end; //#endif /* DT_DIR */ cdpath = malloc(PATH_MAX); strcpy(cdpath, path); //#ifndef DT_DIR strcpy(tmpfname, path); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname); //#endif /* DT_DIR */ while(!dir){ cd = opendir(cdpath); dialog_begin(title, cdpath); dialog_text("[Select This Directory]",NULL,FIELD_SELECTABLE); dialog_text("/.. Parent Directory",NULL,FIELD_SELECTABLE); ldirsz = 16; ldirs = malloc(sizeof(char*)*ldirsz); d = readdir(cd); if(d && !strcmp(d->d_name,".")) d = readdir(cd); if(d && !strcmp(d->d_name,"..")) d = readdir(cd); while(d){ if(ldirn >= ldirsz){ ldirsz += 16; ldirs = realloc(ldirs,ldirsz*sizeof(char*)); } #ifndef DT_DIR /* can not lookup type from search result have to stat filename*/ strcpy(tmpfname_end, d->d_name); stat(tmpfname, &s); if(S_ISDIR (s.st_mode)) #else if ((d->d_type & DT_DIR) == DT_DIR) #endif /* DT_DIR */ { l = strlen(d->d_name); ldirs[ldirn] = malloc(l+2); strcpy(ldirs[ldirn], d->d_name); ldirs[ldirn][l] = DIRSEP_CHAR; ldirs[ldirn][l+1] = '\0'; dialog_text(ldirs[ldirn],NULL,FIELD_SELECTABLE); ldirn++; } d = readdir(cd); } closedir(cd); switch(ret=dialog_end()){ case 0: dir = (char*)-1; break; case 1: dir = strdup(cdpath); break; case 2: { /* need to go up a directory */ char *tmp_str=NULL; tmp_str=cdpath; tmp_str+=strlen(tmp_str)-1; tmp_str--; if (tmp_str > cdpath) { *tmp_str = '\0'; while (tmp_str >= cdpath && *tmp_str != DIRSEP_CHAR) { *tmp_str = '\0'; tmp_str--; } } if (strlen(cdpath) == 0) { sprintf(cdpath, ".%s", DIRSEP); tmp_str = cdpath + strlen(cdpath)+1; *tmp_str = '\0'; } strcpy(tmpfname, cdpath); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname); } break; default: strcpy(tmpfname_end, ldirs[ret-3]); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname); strcpy(cdpath, tmpfname); break; } while(ldirn) free(ldirs[--ldirn]); free(ldirs); } if(dir==(char*)-1) dir = NULL; free(cdpath); return dir; }
// / Converts a matrix composed of complex numbers into a FITS file void mat2fits(Matrix < Complex > &m, char *filename) // TBD: fix row major vs colum major { int status = 0; fitsfile *fptr; long fpixel = 1, naxis = 2, nelements; long naxes[2]; // Initialise storage naxes[0] = (long)m.GetRows(); naxes[1] = (long)m.GetCols(); nelements = naxes[0] * naxes[1]; // Filenames char fitsreal[100]; char fitsimag[100]; for (int i = 0; i < 100; i++) { fitsreal[i] = '\0'; fitsimag[i] = '\0'; } strcpy(fitsreal, filename); strcpy(fitsimag, filename); strcat(fitsreal, "_r"); strcat(fitsimag, "_i"); double *ptrimgreal = (double *)malloc(nelements * sizeof(double)); for (int ii = 0; ii < naxes[0]; ii++) for (int jj = 0; jj < naxes[1]; jj++) ptrimgreal[ii + jj * naxes[0]] = m[naxes[0] - ii - 1][jj].real(); // Create new file, write image, then close file if (status == 0) fits_create_file(&fptr, fitsreal, &status); if (status == 0) fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); if (status == 0) fits_write_img(fptr, TDOUBLE, fpixel, nelements, &ptrimgreal[0], &status); if (status == 0) fits_close_file(fptr, &status); free(ptrimgreal); double *ptrimgimag = (double *)malloc(nelements * sizeof(double)); for (int ii = 0; ii < naxes[0]; ii++) for (int jj = 0; jj < naxes[1]; jj++) ptrimgimag[ii + jj * naxes[0]] = m[ii][jj].imag(); // Create new file, write image, then close file if (status == 0) fits_create_file(&fptr, fitsimag, &status); if (status == 0) fits_create_img(fptr, DOUBLE_IMG, naxis, naxes, &status); if (status == 0) fits_write_img(fptr, TDOUBLE, fpixel, nelements, &ptrimgimag[0], &status); if (status == 0) fits_close_file(fptr, &status); free(ptrimgimag); fits_report_error(stderr, status); }
int menu_state(int save){ char **statebody=NULL; char* name; int i, flags,ret, del=0,l; #ifndef OHBOY_FILE_STAT_NOT_AVAILABLE /* Not all platforms implement stat()/fstat() */ struct stat fstat; time_t time; char *tstr; #endif char *savedir; char *savename; char *saveprefix; FILE *f; int sizeof_slots=0; while (slots[sizeof_slots] != NULL) sizeof_slots++; statebody = malloc(sizeof_slots * sizeof(char*)); /* FIXME check for NULL return from malloc */ savedir = rc_getstr("savedir"); savename = rc_getstr("savename"); saveprefix = malloc(strlen(savedir) + strlen(savename) + 2); sprintf(saveprefix, "%s%s%s", savedir, DIRSEP, savename); dialog_begin(save?"Save State":"Load State",rom.name); for(i=0; i<sizeof_slots; i++){ name = malloc(strlen(saveprefix) + 5); sprintf(name, "%s.%03d", saveprefix, i); #ifndef OHBOY_FILE_STAT_NOT_AVAILABLE /* if the file exists lookup the timestamp */ if(!stat(name,&fstat)){ time = fstat.st_mtime; tstr = ctime(&time); l = strlen(tstr); statebody[i] = malloc(l); strcpy(statebody[i],tstr); statebody[i][l-1]=0; #else /* check if the file exists */ if(f=fopen(name,"rb")){ fclose(f); statebody[i] = (char*)not_emptyslot; #endif /* OHBOY_FILE_STAT_NOT_AVAILABLE */ flags = FIELD_SELECTABLE; } else { statebody[i] = (char*)emptyslot; flags = save ? FIELD_SELECTABLE : 0; } dialog_text(slots[i],statebody[i],flags); free(name); } if(ret=dialog_end()){ name = malloc(strlen(saveprefix) + 5); sprintf(name, "%s.%03d", saveprefix, ret-1); if(save){ if(f=fopen(name,"wb")){ savestate(f); fclose(f); } }else{ if(f=fopen(name,"rb")){ loadstate(f); fclose(f); vram_dirty(); pal_dirty(); sound_dirty(); mem_updatemap(); } } free(name); } for(i=0; i<sizeof_slots; i++) if(statebody[i] != emptyslot && statebody[i] != not_emptyslot) free(statebody[i]); free(saveprefix); return ret; } #define GBPAL_COUNT 27 struct pal_s{ char name[16]; unsigned int dmg_bgp[4]; unsigned int dmg_wndp[4]; unsigned int dmg_obp0[4]; unsigned int dmg_obp1[4]; }gbpal[GBPAL_COUNT] = { { .name = "Default", .dmg_bgp = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C}, .dmg_wndp = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C}, .dmg_obp0 = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C}, .dmg_obp1 = {0X98D0E0,0X68A0B0,0X60707C,0X2C3C3C} },{//Grey Palette .name = "Grey", .dmg_bgp = { 0xFFFFFF, 0xAAAAAA, 0x555555, 0x000000 }, //BG .dmg_wndp = { 0xFFFFFF, 0xAAAAAA, 0x555555, 0x000000 }, //WIN .dmg_obp0 = { 0xFFFFFF, 0xAAAAAA, 0x555555, 0x000000 }, //OB0 .dmg_obp1 = { 0xFFFFFF, 0xAAAAAA, 0x555555, 0x000000 } //OB1 },{//Realistic Palette .name = "DMG",
int main( int argc, char *argv[]) { extern int optind; extern int opterr; extern char *optarg; int c; FILE *fp; #ifdef __hpux setlocale(LC_CTYPE,""); #endif #ifdef MDEBUG malloc_debug(2) ; /* helps find malloc/free errors on Sun */ #endif /* MDEBUG */ opterr = 1; /* print error message if bad option */ progname = ubasename(argv[0]); cdlname = "-"; c_flag = 0; fortran_flag = 0; netcdf_flag = 0; cmode_modifier = 0; nofill_flag = 0; #if _CRAYMPP && 0 /* initialize CRAY MPP parallel-I/O library */ (void) par_io_init(32, 32); #endif while ((c = getopt(argc, argv, "bcfk:l:no:v:x")) != EOF) switch(c) { case 'c': /* for c output, old version of "-lc" */ c_flag = 1; break; case 'f': /* for fortran output, old version of "-lf" */ fortran_flag = 1; break; case 'b': /* for binary netcdf output, ".nc" extension */ netcdf_flag = 1; break; case 'l': /* specify language, instead of using -c or -f */ { char *lang_name = (char *) emalloc(strlen(optarg)+1); if (! lang_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(lang_name, optarg); if (strcmp(lang_name, "c") == 0 || strcmp(lang_name, "C") == 0) { c_flag = 1; } else if (strcmp(lang_name, "f77") == 0 || strcmp(lang_name, "fortran77") == 0 || strcmp(lang_name, "Fortran77") == 0) { fortran_flag = 1; } else { /* Fortran90, Java, C++, Perl, Python, Ruby, ... */ derror("%s: output language %s not implemented", progname, lang_name); return(1); } } break; case 'n': /* old version of -b, uses ".cdf" extension */ netcdf_flag = -1; break; case 'o': /* to explicitly specify output name */ netcdf_flag = 1; netcdf_name = (char *) emalloc(strlen(optarg)+1); if (! netcdf_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(netcdf_name,optarg); break; case 'x': /* set nofill mode to speed up creation of large files */ nofill_flag = 1; break; case 'v': /* a deprecated alias for "kind" option */ /*FALLTHRU*/ case 'k': /* for specifying variant of netCDF format to be generated */ { char *kind_name = (char *) emalloc(strlen(optarg)+1); if (! kind_name) { derror ("%s: out of memory", progname); return(1); } (void)strcpy(kind_name, optarg); /* The default kind is kind 1, with 32-bit offsets */ if (strcmp(kind_name, "1") == 0 || strcmp(kind_name, "classic") == 0) { cmode_modifier = 0; } /* The 64-bit offset kind (2) should only be used if actually needed */ else if (strcmp(kind_name, "2") == 0 || strcmp(kind_name, "64-bit-offset") == 0) { cmode_modifier |= NC_64BIT_OFFSET; } #ifdef USE_NETCDF4 /* NetCDF-4 HDF5 format*/ else if (strcmp(kind_name, "3") == 0 || strcmp(kind_name, "hdf5") == 0) { cmode_modifier |= NC_NETCDF4; } /* NetCDF-4 HDF5 format, but using only nc3 data model */ else if (strcmp(kind_name, "4") == 0 || strcmp(kind_name, "hdf5-nc3") == 0) { cmode_modifier |= NC_NETCDF4 | NC_CLASSIC_MODEL; } #endif else { derror("Invalid format, try classic, 64-bit-offset, hdf5, or hdf5-nc3"); return 2; } } break; case '?': usage(); return(8); } if (fortran_flag && c_flag) { derror("Only one of -c or -f may be specified"); return(8); } argc -= optind; argv += optind; if (argc > 1) { derror ("%s: only one input file argument permitted",progname); return(6); } fp = stdin; if (argc > 0 && strcmp(argv[0], "-") != 0) { if ((fp = fopen(argv[0], "r")) == NULL) { derror ("can't open file %s for reading: ", argv[0]); perror(""); return(7); } cdlname = argv[0]; } yyin = fp; return (yyparse()); }
char* menu_browsedir(char* fpathname, char* file, char *title, char *exts){ /* this routine has side effects with fpathname and file, FIXME */ DIR *dir; struct dirent *d; int n=0, i, j; char *files[1<<16]; /* 256Kb */ #ifndef DT_DIR struct stat s; char tmpfname[PATH_MAX]; char *tmpfname_end; #endif /* DT_DIR */ if(!(dir = opendir(fpathname))) return NULL; /* FIXME try parent(s) until out of paths */ /* TODO FIXME add root directory check (to avoid adding .. as a menu option when at "/" or "x:\") */ files[n] = malloc(4); strcpy(files[n], ".."); strcat(files[n], DIRSEP); n++; d = readdir(dir); if(d && !strcmp(d->d_name,".")) d = readdir(dir); if(d && !strcmp(d->d_name,"..")) d = readdir(dir); #ifndef DT_DIR strcpy(tmpfname, fpathname); tmpfname_end = &tmpfname[0]; tmpfname_end += strlen(tmpfname); #endif /* DT_DIR */ while(d){ #ifndef DT_DIR /* can not lookup type from search result have to stat filename*/ strcpy(tmpfname_end, d->d_name); stat(tmpfname, &s); if(S_ISDIR (s.st_mode)) #else if ((d->d_type & DT_DIR) == DT_DIR) #endif /* DT_DIR */ { files[n] = malloc(strlen(d->d_name)+2); strcpy(files[n], d->d_name); strcat(files[n], DIRSEP); n++; } else if(filterfile(d->d_name,exts)){ files[n] = malloc(strlen(d->d_name)+1); strcpy(files[n], d->d_name); n++; } d = readdir(dir); } closedir (dir); qsort(files+1,n-1,sizeof(char*),fcompare); dialog_begin(title, fpathname); for(i=0; i<n; i++){ dialog_text(files[i],"",FIELD_SELECTABLE); } if(j = dialog_end()){ if(file) { strcpy(file,files[j-1]); } else { file = files[j-1]; files[j-1] = NULL; } } for(i=0; i<n; i++){ free(files[i]); } return j ? file : NULL; }
char *__find_lib_name( char *dsn, char *lib_name, char *driver_name ) { char driver[ INI_MAX_PROPERTY_VALUE + 1 ]; char driver_lib[ INI_MAX_PROPERTY_VALUE + 1 ]; SQLSetConfigMode( ODBC_USER_DSN ); /* * GET DRIVER FROM ODBC.INI */ SQLGetPrivateProfileString( dsn, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBC.INI" ); if ( driver_lib[ 0 ] == 0 ) { /* * if not found look in system DSN */ SQLSetConfigMode( ODBC_SYSTEM_DSN ); SQLGetPrivateProfileString( dsn, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBC.INI" ); SQLSetConfigMode( ODBC_BOTH_DSN ); if ( driver_lib[ 0 ] == 0 ) return NULL; } /* * GET DRIVER FROM ODBCINST.INI IF ODBC.INI HAD USER FRIENDLY NAME */ strcpy( driver_name, "" ); if ( driver_lib[ 0 ] != '/' ) { strcpy( driver, driver_lib ); /* * allow the use of "User odbcinst files */ #ifdef PLATFORM64 SQLGetPrivateProfileString( driver, "Driver64", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" ); if ( driver_lib[ 0 ] == '\0' ) { SQLGetPrivateProfileString( driver, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" ); } #else SQLGetPrivateProfileString( driver, "Driver", "", driver_lib, sizeof( driver_lib ), "ODBCINST.INI" ); #endif strcpy( driver_name, driver ); if ( driver_lib[ 0 ] == 0 ) { return NULL; } } strcpy( lib_name, driver_lib ); return lib_name; }
// subm is submission idx, or -1 for nowplaying // returns number of bytes added, or -1 static int lfm_format_uri (int subm, DB_playItem_t *song, char *out, int outl, time_t started_timestamp, float playtime) { if (subm > 50) { trace ("lastfm: it's only allowed to send up to 50 submissions at once (got idx=%d)\n", subm); return -1; } int sz = outl; char a[META_FIELD_SIZE]; // artist char t[META_FIELD_SIZE]; // title char b[META_FIELD_SIZE]; // album float l; // duration char n[META_FIELD_SIZE]; // tracknum char m[META_FIELD_SIZE]; // muzicbrainz id char ka[6] = "a"; char kt[6] = "t"; char kb[6] = "b"; char kl[6] = "l"; char kn[6] = "n"; char km[6] = "m"; if (subm >= 0) { snprintf (ka+1, 5, "[%d]", subm); strcpy (kt+1, ka+1); strcpy (kb+1, ka+1); strcpy (kl+1, ka+1); strcpy (kn+1, ka+1); strcpy (km+1, ka+1); } if (lfm_fetch_song_info (song, playtime, a, t, b, &l, n, m) == 0) { // trace ("playtime: %f\nartist: %s\ntitle: %s\nalbum: %s\nduration: %f\ntracknum: %s\n---\n", song->playtime, a, t, b, l, n); } else { // trace ("file %s doesn't have enough tags to submit to last.fm\n", song->fname); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, ka, a) < 0) { // trace ("failed to add %s=%s\n", ka, a); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kt, t) < 0) { // trace ("failed to add %s=%s\n", kt, t); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kb, b) < 0) { // trace ("failed to add %s=%s\n", kb, b); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, kn, n) < 0) { // trace ("failed to add %s=%s\n", kn, n); return -1; } if (lfm_add_keyvalue_uri_encoded (&out, &outl, km, m) < 0) { // trace ("failed to add %s=%s\n", km, m); return -1; } int processed; processed = snprintf (out, outl, "%s=%d&", kl, (int)l); if (processed > outl) { // trace ("failed to add %s=%d\n", kl, (int)l); return -1; } out += processed; outl -= processed; if (subm >= 0) { processed = snprintf (out, outl, "i[%d]=%d&o[%d]=P&r[%d]=&", subm, (int)started_timestamp, subm, subm); if (processed > outl) { // trace ("failed to add i[%d]=%d&o[%d]=P&r[%d]=&\n", subm, (int)song->started_timestamp, subm, subm); return -1; } out += processed; outl -= processed; } return sz - outl; }
/************************************************************** * * hashCreate - Creates an empty hash table * * * This routine creates am empty hash table of size <size> * and initializes it. Memory for the buffer is allocated from * the system memory partition. * * * RETURNS: * ID of the hash table , or NULL if memory cannot be allocated. * * Author Greg Brissey 8/5/93 */ HASH_ID hashCreate(int size,PFL hashf, PFI cmpf, char* idstr) /* int size; size of hash table */ /* PFL hashf; pointer to user defined hashing function */ /* PFI cmpf; pointer to user defined comparison function */ /* char* idstr; Identifing string for user */ { HASH_ID pHashTbl; HASH_ENTRY *pHashAry; register long i; char tmpstr[80]; pHashTbl = (HASH_ID) malloc(sizeof(HASH_TABLE)); /* create structure */ if (pHashTbl == NULL) return (NULL); if (idstr == NULL) { sprintf(tmpstr,"%s %d\n",HashIDStr,++HIdCnt); pHashTbl->pHashIdStr = (char *) malloc(strlen(tmpstr)+2); } else { pHashTbl->pHashIdStr = (char *) malloc(strlen(idstr)+2); } if (pHashTbl->pHashIdStr == NULL) { free(pHashTbl); return(NULL); } if (idstr == NULL) { strcpy(pHashTbl->pHashIdStr,tmpstr); } else { strcpy(pHashTbl->pHashIdStr,idstr); } /* create space for all table entries */ pHashTbl->pHashEntries = (HASH_ENTRY *) malloc( (size * sizeof(HASH_ENTRY)) ); if (pHashTbl->pHashEntries == NULL) { free(pHashTbl->pHashIdStr); free(pHashTbl); return (NULL); } pHashTbl->numEntries =(long) 0; pHashTbl->maxEntries = size; pHashTbl->collisions = (long) 0; if (hashf == NULL) pHashTbl->pHashFunc = strhash; /* if users func is NULL use default hash */ else pHashTbl->pHashFunc = hashf; /* set up users hash function */ if (cmpf == NULL) pHashTbl->pCmpFunc = cmpstrs; /* if users func is NULL use default hash */ else pHashTbl->pCmpFunc = cmpf; /* set up users hash function */ pHashAry = pHashTbl->pHashEntries; /* initialize hash table */ for(i=0;i<size;i++) { pHashAry[i].hashKey = NULL; pHashAry[i].refAddr= NULL; } return( pHashTbl ); }
int auth_v2 (void) { if (lfm_sess[0]) { return 0; } char msg[4096]; char sigstr[4096]; uint8_t sig[16]; snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getToken%s", LASTFM_API_KEY, LASTFM_API_SECRET); deadbeef->md5 (sig, sigstr, strlen (sigstr)); deadbeef->md5_to_str (sigstr, sig); snprintf (msg, sizeof (msg), "%s/?api_key=%s&method=auth.getToken&api_sig=%s", SCROBBLER_URL, LASTFM_API_KEY, sigstr); // get token char lfm_token[33] = ""; int status = curl_req_send (msg, NULL); if (!status) { // parse output if (strstr (lfm_reply, "<lfm status=\"ok\">")) { char *token = strstr (lfm_reply, "<token>"); if (token) { token += 7; char *end = strstr (token, "</token>"); if (end) { *end = 0; snprintf (msg, sizeof (msg), "http://www.last.fm/api/auth/?api_key=%s&token=%s", LASTFM_API_KEY, token); trace ("Dear user. Please visit this URL and authenticate deadbeef. Thanks.\n"); trace ("%s\n", msg); strncpy (lfm_token, token, 32); lfm_token[32] = 0; } } } } curl_req_cleanup (); if (!lfm_token[0]) { // total fail, give up return -1; } // get session snprintf (sigstr, sizeof (sigstr), "api_key%smethodauth.getSessiontoken%s%s", LASTFM_API_KEY, lfm_token, LASTFM_API_SECRET); deadbeef->md5 (sig, sigstr, strlen (sigstr)); deadbeef->md5_to_str (sigstr, sig); snprintf (msg, sizeof (msg), "method=auth.getSession&token=%s&api_key=%s&api_sig=%s", lfm_token, LASTFM_API_KEY, sigstr); for (;;) { status = curl_req_send (SCROBBLER_URL, msg); if (!status) { char *sess = strstr (lfm_reply, "<key>"); if (sess) { sess += 5; char *end = strstr (sess, "</key>"); if (end) { *end = 0; char config[1024]; snprintf (config, sizeof (config), "%s/.config/deadbeef/lastfmv2", getenv ("HOME")); trace ("got session key %s\n", sess); FILE *fp = fopen (config, "w+b"); if (!fp) { trace ("lastfm: failed to write config file %s\n", config); curl_req_cleanup (); return -1; } if (fwrite (sess, 1, 32, fp) != 32) { fclose (fp); trace ("lastfm: failed to write config file %s\n", config); curl_req_cleanup (); return -1; } fclose (fp); strcpy (lfm_sess, sess); } } // trace ("reply: %s\n", lfm_reply); } curl_req_cleanup (); if (lfm_sess[0]) { break; } sleep (5); } return 0; }
static void *do_resolve(void *hostname) { slogi("do_resolve hostname[%s]",hostname); #if 0 /* [/home/st/toffaletti/armhf/key.c_114__st_thread_cleanup]key [110876] key_max[0] do_resolve hostname[www.baidu.com] after strcpy strcpy(host,hostname)[www.baidu.com] hostname[www.baidu.com] [/home/st/toffaletti/armhf/event.c_421__st_select_fd_new]_st_select_fd_new osfd[7] ok [/home/st/toffaletti/armhf/io.c_749_st_sendto]sendto get n [31] [/home/st/toffaletti/armhf/io.c_730_st_recvfrom]recvfrom get n [90] [/home/st/toffaletti/armhf/examples/res.c_278_dns_getaddr]query_domain return 0 [/home/st/toffaletti/armhf/io.c_212_st_netfd_close]JUST TEST st_netfd_close Program received signal SIGSEGV, Segmentation fault. 0x00000000 in ?? () (gdb) bt #0 0x00000000 in ?? () #1 0x0000b06e in dns_getaddr ( host=<error reading variable: Cannot access memory at address 0xc>, addr=<error reading variable: Cannot access memory at address 0x8>, timeout=<error reading variable: Cannot access memory at address 0x0>) at /home/st/toffaletti/armhf/examples/res.c:281 Backtrace stopped: previous frame inner to this frame (corrupt stack?) (gdb) */ char host[128]; memset(host,0,128); //strcpy(host,hostname); slogi("after strcpy strcpy(host,hostname)[%s] hostname[%s]",strcpy(host,hostname),hostname); #else char *host=malloc(128); memset(host,0,128); slogi("sizeof(hostname)[%d] strlen(hostname)[%d]",sizeof(hostname),strlen(hostname)); memcpy(host,hostname,strlen(hostname)+1); slogi("host is [%s]",host); #endif struct in_addr addr; #if 1 /* Use dns_getaddr() instead of gethostbyname(3) to get IP address */ #if 1 int ret=-99; dns_getaddr(host, &addr, TIMEOUT); LOGD("dns_getaddr RET"); if ( ret< 0) { #else if ( dns_getaddr(host, &addr, TIMEOUT)< 0) { #endif // #endif /*PCÉÏ»áÊä³öСÓÚ0£¬tvboxÉÏɶ¶¼Ã»ÓÐÊä³ö°¡*/ fprintf(stderr, "dns_getaddr: can't resolve %s: ", (char *)host); if (h_errno == NETDB_INTERNAL) perror(""); else herror(""); } else /*ÕâÖÖÇé¿ö¾ÍÊÇÕÒµ½ÁË*/ printf("%-40s %s\n", (char *)host, inet_ntoa(addr)); #else //Ö±½Ó²âÊÔÏ̺߳¯Êý /* http://m.blog.chinaunix.net/uid-28595538-id-4923606.html inet_ntoa º¯Êý API ÃèÊö #include #include char * inet_ntoa( struct in_addr_in ) ; ²ÎÊý£º in : ¸Ã²ÎÊý´æ·ÅÓÃÀ´×ª»»µÄ16½øÖÆÍøÂç˳ÐòµÄIPµØÖ·½á¹¹Ìå ·µ»ØÖµ£º Èç¹ûº¯Êý Inet_ntoa ³É¹¦½« 16½øÖÆÍøÂç˳ÐòµÄ IPµØַת»»Îª×Ö·û´®ÀàÐ͵ĵã·ÖIP µØÖ·£¬ Ôò½«¸Ã×Ö·û´®×÷Ϊ·µ»ØÖµ·µ»Ø£¬×ª»»Ê§°Ü£¬·µ»Ø NULL */ int count=20; while(count--) { LOGD("just for test thread func ...."); //ÕâÀïÊä³öµÄaddrÊÇ´íÎóµÄ printf("%-40s %s\n", (char *)host, inet_ntoa(addr)); } #endif //20150923 free(host); return NULL; } /* * Asynchronous DNS host name resolution. This program creates one * ST thread for each host name (specified as command line arguments). * All threads do host name resolution concurrently. */ int main(int argc, char *argv[]) { slogi("argc[%d]",argc); int i; if (argc < 2) { fprintf(stderr, "Usage: %s <hostname1> [<hostname2>] ...\n", argv[0]); exit(1); } if (st_init() < 0) { perror("st_init"); exit(1); } slogi("---before for--argc[%d]",argc); for (i = 1; i < argc; i++) { slogi("====%d=[%s]=",i,argv[i]); /* Create a separate thread for each host name */ if (st_thread_create(do_resolve, argv[i], 0, 0) == NULL) { perror("st_thread_create"); exit(1); } } st_thread_exit(NULL); //Ôõôֱ½Óµ½ÁËÕâÀïÄØ /* NOTREACHED ÍøÂç²»¿É´ïå */ return 1; //òËÆÕâÀïÊdzɹ¦? }
// *TODO: deprecate void LLUUID::toString(char *out) const { std::string buffer; toString(buffer); strcpy(out,buffer.c_str()); /* Flawfinder: ignore */ }