int main(int argc, char *argv[]) { char *pname; Acr_File *afpin, *afpout; Acr_Status status; Server_state state; int acr_command; Acr_Group group_list; Acr_Message input_message, output_message; int exit_status; char exit_string[256]; char **file_list; Data_Object_Info **file_info_list; int num_files, num_files_alloc; static char file_prefix_string[L_tmpnam+1] = "dicomserver"; char *file_prefix = file_prefix_string; //Added by Leili char *file_prefix2 = "/usr/local/dicom_keep/"; char *temp_dir; int continue_looping; FILE *fptemp; char last_file_name[256]; char *project_name = NULL; char logfilename[256]; int pdu_type; int process_files, have_extra_file; Acr_byte_order byte_order; Acr_VR_encoding_type vr_encoding; int pres_context_id; long maximum_length; pid_t server_pid, child_pid; int statptr; /* added by rhoge */ int ix; int UseArgDir = 0; char OutDir[128]; /* Get server process id */ server_pid = getpid(); /*************************/ /* Change to tmp directory - note that this will be default file destination if no aetitle or command-line specification are received (rhoge) */ /* commented out by leili */ //(void) chdir(P_tmpdir); /* added by leili */ /* change to tmp directory */ if (run_dir != NULL) { (void) chdir(run_dir); } /*****************************/ /* Create minc history string */ { char *string; string = "dicomserver"; minc_history = time_stamp(1, &string); } /* read in all the input pars and file names */ for (ix = 1; ix<argc; ix++) { if (!strncmp(argv[ix],"-destdir",8)) { ix++; UseArgDir = 1; strcpy(OutDir,argv[ix]); (void) strcat(OutDir, "/"); /* make sure path ends with slash */ } else if (!strncmp(argv[ix],"-log",4)) { ix++; Do_logging = atoi(argv[ix]); } else if (!strncmp(argv[ix],"-fork",5)) { Fork = TRUE; } else if (!strncmp(argv[ix],"-keep_dcm",9)) { Keep_files = TRUE; } else if (!strncmp(argv[ix],"-help",9)) { (void) fprintf(stderr,"Usage: dicomserver [<options>]\nOptions:\n\t-log <n>\n\t-fork\n\t-keep_dcm\n\t-help\n"); exit(EXIT_SUCCESS); } else { (void) fprintf(stderr,"Usage: dicomserver [<options>]\nOptions:\n\t-log <n>\n\t-fork\n\t-keep_dcm\n\t-help\n"); exit(EXIT_FAILURE); } } /* Re-open stderr if we are logging */ if (Do_logging > NO_LOGGING) { (void) sprintf(logfilename, "/data/fmri/transfer/logs/dicomserver-%d.log", (int) getpid()); (void) freopen(logfilename, "w", stderr); setbuf(stderr, NULL); } else { (void) sprintf(logfilename, "/dev/null"); (void) freopen(logfilename, "w", stderr); setbuf(stderr, NULL); } // set up type of connection (Syngo?) file_type = N4DCM; // default N4_OFFSET = 0; /* Print message at start */ pname = argv[0]; if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "%s: Started dicom server.\n", pname); } /* Make connection */ open_connection(argc, argv, &afpin, &afpout); /* Check that the connection was made */ if ((afpin == NULL) || (afpout == NULL)) { (void) fprintf(stderr, "%s: Error opening connection.\n", pname); exit(EXIT_FAILURE); } /* Print connection message */ if (Do_logging >= HIGH_LOGGING) { (void) fprintf(stderr, "%s: Connection accepted.\n", pname); } #ifdef DO_INPUT_TRACING /* Enable input tracing */ acr_dicom_enable_trace(afpin); acr_dicom_enable_trace(afpout); #endif /* Create file prefix. Create the temporary file to avoid file name clashes */ /*****************************/ /* Commented out by leili */ //temp_dir = NULL; //if ( !Keep_files) { // (void) tmpnam(file_prefix); // if (mkdir(file_prefix, (mode_t) 0777)) { // (void) fprintf(stderr, // "%s: Unable to create directory for temporary files.\n", // pname); // perror(pname); // exit(EXIT_FAILURE); // } // temp_dir = strdup(file_prefix); // (void) strcat(file_prefix, "/dicom"); //} // else { // file_prefix=strdup(OutDir); // if (mkdir(file_prefix, (mode_t) 0777)) { // (void) fprintf(stderr, // "Directory %s exists...\n",file_prefix); // } // temp_dir = strdup(file_prefix); // (void) strcat(file_prefix, "/dicom"); // } /****************************/ /* Added by Leili */ temp_dir = NULL; if (! Keep_files){ //temp_dir = tempnam(run_dir, NULL); temp_dir = tempnam(run_dir, NULL); if(mkdir(temp_dir, (mode_t) 0777)){ (void) fprintf(stderr, "%s: Unable to create directory for temporary files.\n", pname); perror(pname); exit(EXIT_FAILURE); } (void)strcpy(file_prefix, temp_dir); (void) strcat(file_prefix, "/"); //(void) strcat(file_prefix, "/dicom"); } /*****************************/ (void) fprintf(stderr, "About to begin the space allocation \n"); /* Leili */ /* Get space for file lists */ num_files_alloc = FILE_ALLOC_INCREMENT; file_list = MALLOC((size_t) num_files_alloc * sizeof(*file_list)); file_info_list = MALLOC(num_files_alloc * sizeof(*file_info_list)); /* Loop while reading messages */ state = WAITING_FOR_ASSOCIATION; continue_looping = TRUE; num_files = 0; (void) fprintf(stderr, "About to start reading a message \n"); /* Leili */ while (continue_looping) { /* Wait for any children that have finished */ while ((child_pid=wait3(&statptr, WNOHANG, NULL)) > 0) {} /* If there are children, slow down the processing */ (void) fprintf(stderr, "If we have children, slow down \n"); /* Leili */ if (child_pid == 0) { (void) sleep((unsigned int) SERVER_SLEEP_TIME); } (void) fprintf(stderr, "Start reading the message\n"); /* Leili */ /* Read in the message */ Alarmed_afp = afpin; (void) signal(SIGALRM, timeout_handler); (void) alarm(CONNECTION_TIMEOUT); if (Do_logging > HIGH_LOGGING) fprintf(stderr,"\nWaiting for dicom message...\n"); /* rhoge */ /* chokes here at end of asynchronous transfer */ status=acr_input_dicom_message(afpin, &input_message); (void) fprintf(stderr, "The status of the message is: %s \n", acr_status_string(status)); /* Leili */ if (Do_logging > HIGH_LOGGING) { /* rhoge */ fprintf(stderr,"\nGot message.\n"); fprintf(stderr,"\nCalling `alarm'...\n"); } (void) alarm(0); if (Do_logging > HIGH_LOGGING) fprintf(stderr,"\nAlarm called.\n"); /* rhoge */ (void) fprintf(stderr,"Checking for an error \n"); /* Leili */ /* Check for error */ if (status != ACR_OK) { continue_looping = FALSE; state = TERMINATING; break; } /* Set flags indicating whether we should do anything with the files and whether the file lists contain an extra file */ process_files = FALSE; have_extra_file = FALSE; /* Get group list */ group_list = acr_get_message_group_list(input_message); /* Get PDU type. Default is data transfer */ pdu_type = acr_find_short(group_list, DCM_PDU_Type, ACR_PDU_DATA_TF); (void) fprintf(stderr,"We got the pdu and it is: %d\n", pdu_type); /* Leili */ /* Deal with PDU state */ switch (pdu_type) { /* Associate request */ case ACR_PDU_ASSOC_RQ: if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\n Associate request is ACR_PDU_ASSOC_RQ\n"); if (state != WAITING_FOR_ASSOCIATION) { status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } /* Work out reply and get connection info */ (void) fprintf(stderr,"About to go to reply program\n"); /* Leili */ output_message = associate_reply(input_message, &project_name, &pres_context_id, &byte_order, &vr_encoding, &maximum_length); (void) fprintf(stderr,"We finished with the reply program\n"); /* Leili */ /* Modify the input and output streams according to the connection info */ acr_set_byte_order(afpin, byte_order); acr_set_vr_encoding(afpin, vr_encoding); acr_set_byte_order(afpout, byte_order); acr_set_vr_encoding(afpout, vr_encoding); acr_set_dicom_pres_context_id(afpout, pres_context_id); acr_set_dicom_maximum_length(afpout, maximum_length); /* Get ready for files */ num_files = 0; state = WAITING_FOR_DATA; break; /* Release */ case ACR_PDU_REL_RQ: if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\nAssociate request is ACR_PDU_REL_RQ\n"); if (state != WAITING_FOR_DATA) { status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } output_message = release_reply(input_message); state = TERMINATING; process_files = TRUE; if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\nReceived release request; process flag set.\n"); break; /* Abort */ case ACR_PDU_ABORT_RQ: if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\nAssociate request is ACR_PDU_ABORT_RQ\n"); output_message = abort_reply(input_message); state = TERMINATING; break; /* Data transfer */ case ACR_PDU_DATA_TF: if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\nAssociate request is ACR_PDU_DATA_TF\n"); /* Check state */ if (state != WAITING_FOR_DATA) { status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } /* Check command and compose a reply */ acr_command = acr_find_short(group_list, ACR_Command, -1); switch (acr_command) { case ACR_C_STORE_RQ: case ACR_C_ECHO_RQ: output_message = data_reply(input_message); break; default: status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } /* Carry on only if we have a store command */ if (acr_command != ACR_C_STORE_RQ) break; /* Get rid of the command groups */ group_list = skip_command_groups(group_list); /* Was the data attached to the command? If not, read in the next message - it should contain the data */ if (group_list == NULL) { /* Delete the previous message */ if (input_message != NULL) acr_delete_message(input_message); /* Read the data and check the status */ Alarmed_afp = afpin; (void) signal(SIGALRM, timeout_handler); (void) alarm(CONNECTION_TIMEOUT); status=acr_input_dicom_message(afpin, &input_message); (void) alarm(0); if (status != ACR_OK) { state = DISCONNECTING; break; } /* Check that we have a data PDU */ group_list = acr_get_message_group_list(input_message); if (acr_find_short(group_list, DCM_PDU_Type, ACR_PDU_DATA_TF) != ACR_PDU_DATA_TF) { status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } /* Skip command groups and check for no data */ group_list = skip_command_groups(group_list); if (group_list == NULL) break; } (void) fprintf(stderr,"End of while loop, we are out of the loop \n"); /* Leili */ /* Extend file list if necessary */ if (num_files >= num_files_alloc) { num_files_alloc = num_files + FILE_ALLOC_INCREMENT; file_list = REALLOC(file_list, num_files_alloc * sizeof(*file_list)); file_info_list = REALLOC(file_info_list, num_files_alloc * sizeof(*file_info_list)); } file_list[num_files] = NULL; file_info_list[num_files] = MALLOC(sizeof(*file_info_list[num_files])); /* Save the object */ //save_transferred_object(group_list, // file_prefix, &file_list[num_files], // file_info_list[num_files]); /* Added by leili */ save_transferred_object(group_list, file_prefix2, &file_list[num_files], file_info_list[num_files]); (void) fprintf(stderr,"Finished saving transfered object number %d \n", (num_files)+1); /* Leili */ num_files++; if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, " Copied %s\n", file_list[num_files-1]); } (void) fprintf(stderr,"Number of files are: %d \n", num_files); /* Leili */ if (Do_logging > HIGH_LOGGING) { /* rhoge */ fprintf(stderr, "About to check if we're done file group\n"); fprintf(stderr,"\nnum_files: \t%d",num_files); fprintf(stderr,"\nfile_info_list[num_files-1]->study_id: \t%.6f", file_info_list[num_files-1]->study_id); fprintf(stderr,"\nfile_info_list[0]->study_id: \t%.6f", file_info_list[0]->study_id); fprintf(stderr,"\nfile_info_list[num_files-1]->acq_id: \t%d", file_info_list[num_files-1]->acq_id); fprintf(stderr,"\nfile_info_list[0]->acq_id: \t%d", file_info_list[0]->acq_id); } /* Check whether we have reached the end of a group of files */ if (num_files > 1) { if ((file_info_list[num_files-1]->study_id != file_info_list[0]->study_id) || (file_info_list[num_files-1]->acq_id != file_info_list[0]->acq_id)) { process_files = TRUE; have_extra_file = TRUE; if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\nend of file group detected, process flag set.\n"); } } if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\ndone checking for end of file group\n"); break; /* Unknown command */ default: if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\nAssociate request is default (an error)\n"); status = ACR_HIGH_LEVEL_ERROR; state = DISCONNECTING; break; } /* End of switch on pdu_type */ (void) fprintf(stderr,"We break and came out since we didn't have the store command\n"); /* Leili */ /* Delete input message */ if (input_message != NULL) acr_delete_message(input_message); /* Use the files if we have a complete acquisition */ if (process_files) { if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr,"\nEntered the `process files' block...\n"); /* Log the fact */ if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "\nCopied one acquisition.\n"); } /* Check for file from next acquisition */ if (have_extra_file) num_files--; /* uncomment to prevent forking */ /* #define NO_FORK */ if (Fork) { /* Fork child to process the files */ child_pid = fork(); } else { child_pid = 0; } if (child_pid > 0) { /* Parent process */ if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "Forked process to create minc files.\n"); } } /* Error forking */ else if (child_pid < 0) { (void) fprintf(stderr, "Error forking child to create minc file\n"); return; } else { /* Child process */ /*******************************************/ /* Added by Leili */ /* Close file descriptors to avoid buffering problems. STDERR is sometimes left open, therefore this command maybe needed */ if(Fork){ int fd; for(fd=getdtablesize()-1; fd>= 0; fd--) { if(fd != 2){ (void) close(fd); } } } /******************************************/ /* Do something with the files */ (void) fprintf(stderr, "We are about to do something with the files.\n"); /* Leili */ (void) fprintf(stderr, "The project name is:%s\n", project_name); /* Leili */ (void) fprintf(stderr, "The pname is:%s\n", pname); /* Leili */ use_the_files(project_name, num_files, file_list, file_info_list,UseArgDir,OutDir); /* Remove the temporary files */ cleanup_files(num_files, file_list); /* Remove the temporary directory if the server has finished */ /* (this does not seem to work all the time) */ if ((temp_dir != NULL) && (kill(server_pid, 0) != 0)) { cleanup_files(1, &temp_dir); } /* Print message about child finishing */ if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "Minc creation process finished.\n"); } if (Fork) { /* Exit from child */ exit(EXIT_SUCCESS); } } /* End of child process */ /* Put blank line in log file */ if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "\n"); } /* Reset the lists */ free_list(num_files, file_list, file_info_list); if (have_extra_file) { file_list[0] = file_list[num_files]; file_info_list[0] = file_info_list[num_files]; file_list[num_files] = NULL; file_info_list[num_files] = NULL; } num_files = (have_extra_file ? 1 : 0); } // end of if(process files) if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\n just passed `process files' loop\n"); /* Check for disconnection */ if (state == DISCONNECTING) { continue_looping = FALSE; break; } /* Send reply */ Alarmed_afp = afpout; (void) signal(SIGALRM, timeout_handler); (void) alarm(CONNECTION_TIMEOUT); status = acr_output_dicom_message(afpout, output_message); (void) alarm(0); /* Delete output message */ if (output_message != NULL) acr_delete_message(output_message); if (status != ACR_OK) { state = TERMINATING; break; } if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\nbottom of loop over messages\n"); } /* End of loop over messages */ if (Do_logging > HIGH_LOGGING) /* rhoge */ fprintf(stderr, "\njust out of loop over messages\n"); /* Free the input and output streams */ acr_close_dicom_file(afpin); acr_close_dicom_file(afpout); /* Save name of first file in last set transferred */ if ((num_files > 0) && (file_list[0] != NULL)) { last_file_name[sizeof(last_file_name) - 1] = '\0'; (void) strncpy(last_file_name, file_list[0], sizeof(last_file_name)-1); } else { last_file_name[0] = '\0'; } /* Clean up files, if needed */ if (num_files > 0) { cleanup_files(num_files, file_list); free_list(num_files, file_list, file_info_list); num_files = 0; } FREE(file_list); FREE(file_info_list); /* Remove the file prefix directory (this only happens if it is empty). */ cleanup_files(1, &temp_dir); FREE(temp_dir); /* Check for connection timeout */ if (Connection_timeout) { (void) fprintf(stderr, "Connection timed out.\n"); } /* Print final message */ if ((status == ACR_OK) || (status == ACR_END_OF_INPUT)) { (void) sprintf(exit_string, "Finished transfer."); exit_status = EXIT_SUCCESS; } else { (void) sprintf(exit_string, "%s. Disconnecting.", acr_status_string(status)); exit_status = EXIT_FAILURE; } (void) fprintf(stderr, "The logging set to be %d\n", Do_logging); /* Leili */ (void) fprintf(stderr, "The status of the message is: %s \n", acr_status_string(status)); /* Leili */ if (Do_logging >= LOW_LOGGING) { (void) fprintf(stderr, "\n%s: %s\n", pname, exit_string); } if ((status != ACR_OK) && (status != ACR_END_OF_INPUT)) { if (SYSTEM_LOG != NULL) { if ((fptemp = fopen(SYSTEM_LOG, "w")) != NULL) { if ((int) strlen(last_file_name) > 0) { (void) fprintf(fptemp, "%s: File \"%s\"\n", pname, last_file_name); } (void) fprintf(fptemp, "%s: %s\n", pname, exit_string); (void) fclose(fptemp); } } } /* Free the project_name string */ if (project_name != NULL) FREE(project_name); exit(exit_status); }
static int do_emit_mimepart_body(FILE *fp_dest, SEND_BODYPART *part) { char *fname_tmp, *fname_sel, cmd_buf[SLEN], *s; int rc, i; FILE *fp_src; rc = -1; fp_src = NULL; switch (mime_encoding_type(part->content_header[BP_CONT_ENCODING])) { case ENCODING_QUOTED: if ((fname_tmp = tempnam(temp_dir, "emm.")) == NULL) { show_error("Cannot make temp file name."); return -1; } MIME_ENCODE_CMD_QUOTED(cmd_buf, part->fname, fname_tmp); break; case ENCODING_BASE64: if ((fname_tmp = tempnam(temp_dir, "emm.")) == NULL) { show_error("Cannot make temp file name."); return -1; } MIME_ENCODE_CMD_BASE64(cmd_buf, part->fname, fname_tmp); break; case ENCODING_UUENCODE: if ((fname_tmp = tempnam(temp_dir, "emm.")) == NULL) { show_error("Cannot make temp file name."); return -1; } MIME_ENCODE_CMD_UUENCODE(cmd_buf, part->fname, fname_tmp); break; default: /* encoding not needed */ fname_tmp = NULL; break; } if (fname_tmp == NULL) { fname_sel = part->fname; } else if ((i = system_call(cmd_buf, 0)) == 0) { fname_sel = fname_tmp; } else { for (s = cmd_buf ; *s != '\0' && !isspace(*s) ; ++s) ; *s = '\0'; s = (cmd_buf[0] != '\0' ? basename(cmd_buf) : "encoder"); show_error("Cannot encode \"%s\". (\"%s\" exit status %d)", basename(part->fname), s, i); goto done; } if ((fp_src = file_open(fname_sel, "r")) == NULL) goto done; if (file_copy(fp_src, fp_dest, fname_sel, "message body") < 0) goto done; if (file_close(fp_src, fname_sel) < 0) goto done; else fp_src = NULL; rc = 0; done: if (fp_src != NULL) (void) fclose(fp_src); if (fname_tmp != NULL) { (void) unlink(fname_tmp); free((malloc_t)fname_tmp); } return rc; }
bool ThemeLoader::extract( const string &fileName ) { bool result = true; char *tmpdir = tempnam( NULL, "vlt" ); string tempPath = sFromLocale( tmpdir ); free( tmpdir ); // Extract the file in a temporary directory if( ! extractTarGz( fileName, tempPath ) && ! extractZip( fileName, tempPath ) ) { deleteTempFiles( tempPath ); return false; } string path; string xmlFile; OSFactory *pOsFactory = OSFactory::instance( getIntf() ); // Find the XML file in the theme if( findFile( tempPath, DEFAULT_XML_FILE, xmlFile ) ) { path = getFilePath( xmlFile ); } else { // No XML file, check if it is a winamp2 skin string mainBmp; if( findFile( tempPath, "main.bmp", mainBmp ) ) { msg_Dbg( getIntf(), "trying to load a winamp2 skin" ); path = getFilePath( mainBmp ); // Look for winamp2.xml in the resource path list<string> resPath = pOsFactory->getResourcePath(); list<string>::const_iterator it; for( it = resPath.begin(); it != resPath.end(); ++it ) { if( findFile( *it, WINAMP2_XML_FILE, xmlFile ) ) break; } } } if( !xmlFile.empty() ) { // Parse the XML file if (! parse( path, xmlFile ) ) { msg_Err( getIntf(), "error while parsing %s", xmlFile.c_str() ); result = false; } } else { msg_Err( getIntf(), "no XML found in theme %s", fileName.c_str() ); result = false; } // Clean-up deleteTempFiles( tempPath ); return result; }
size_t memchk (const void *addr, size_t nbytes) { static int fd = -1; if (-1 == fd) { // writing to /dev/null need not reliably detect invalid // address ranges if the operating system optimizes the // operation away (as SunOS does, for instance) // fd = open ("/dev/null", O_WRONLY); #ifdef _WIN32 char* const fname = tempnam (P_tmpdir, ".rwmemchk.tmp"); if (!fname) return size_t (-1); // create a temporary file and have Win32 delete it when // the last file descriptor that refers to it is closed fd = open (fname, O_RDWR | O_CREAT | _O_TEMPORARY, 0666); // free storage allocated by tempnam() free (fname); if (fd < 0) { // error: unable to check addr return size_t (-1); } #else // !_WIN32 # define TMP_TEMPLATE P_tmpdir "/rwmemchk-XXXXXX" char fname_buf [] = TMP_TEMPLATE; fd = mkstemp (fname_buf); if (fd < 0) { // error: unable to check addr return size_t (-1); } unlink (fname_buf); #endif // _WIN32 } lseek (fd, 0, SEEK_SET); size_t size = size_t (-1); // error const int errno_save = errno; errno = 0; if (size_t (-1) == nbytes) { // size not specified, check that addr points // to a valid NUL-terminated byte string (NTBS) // get the virtual page size static const size_t pgsz = page_size (); // compute the positive offset from the closest page boundary const size_t pgoff = size_t (addr) % pgsz; // compute the number of bytes from addr to the end of the page nbytes = pgsz - pgoff; // go through memory pointed to by `addr' one page // at a time looking for the terminating NUL for (const char *pc = static_cast<const char*>(addr); ; ) { // try to write a page of memory (or what's left of it) const size_t nwrote = write (fd, pc, nbytes); if (nwrote == nbytes) { // on success, look for the NUL character const void* const pnull = memchr (pc, 0, nbytes); if (pnull) { // return the offset of the NUL character from `addr' size = static_cast<const char*>(pnull) - static_cast<const char*>(addr) + 1; break; } pc += nbytes; nbytes = pgsz; } else if (size_t (-1) == nwrote && EINTR == errno) { // retry the interrupted system call errno = 0; } else if (nwrote < nbytes) { // retry after a partial write errno = 0; pc += nwrote; nbytes -= nwrote; } else { // error: `addr' doesn't point to a valid NTBS break; } } } else { const size_t nwrote = write (fd, addr, nbytes); if (nwrote == nbytes) size = nbytes; } errno = errno_save; return size_t (size); }
int ncat_connect(void) { nsock_pool mypool; int rc; /* Unless explicitely asked not to do so, ncat uses the * fallback nsock engine to maximize compatibility between * operating systems and the different use cases. */ if (!o.nsock_engine) nsock_set_default_engine("select"); /* Create an nsock pool */ if ((mypool = nsp_new(NULL)) == NULL) bye("Failed to create nsock_pool."); if (o.debug >= 6) nsock_set_loglevel(mypool, NSOCK_LOG_DBG_ALL); else if (o.debug >= 3) nsock_set_loglevel(mypool, NSOCK_LOG_DBG); else if (o.debug >= 1) nsock_set_loglevel(mypool, NSOCK_LOG_INFO); else nsock_set_loglevel(mypool, NSOCK_LOG_ERROR); /* Allow connections to broadcast addresses. */ nsp_setbroadcast(mypool, 1); #ifdef HAVE_OPENSSL set_ssl_ctx_options((SSL_CTX *) nsp_ssl_init(mypool)); #endif if (httpconnect.storage.ss_family == AF_UNSPEC && socksconnect.storage.ss_family == AF_UNSPEC) { /* A non-proxy connection. Create an iod for a new socket. */ cs.sock_nsi = nsi_new(mypool, NULL); if (cs.sock_nsi == NULL) bye("Failed to create nsock_iod."); if (nsi_set_hostname(cs.sock_nsi, o.target) == -1) bye("Failed to set hostname on iod."); #if HAVE_SYS_UN_H /* For DGRAM UNIX socket we have to use source socket */ if (o.af == AF_UNIX && o.proto == IPPROTO_UDP) { if (srcaddr.storage.ss_family != AF_UNIX) { char *tmp_name = NULL; /* If no source socket was specified, we have to create temporary one. */ if ((tmp_name = tempnam(NULL, "ncat.")) == NULL) bye("Failed to create name for temporary DGRAM source Unix domain socket (tempnam)."); srcaddr.un.sun_family = AF_UNIX; strncpy(srcaddr.un.sun_path, tmp_name, sizeof(srcaddr.un.sun_path)); free (tmp_name); } nsi_set_localaddr(cs.sock_nsi, &srcaddr.storage, SUN_LEN((struct sockaddr_un *)&srcaddr.storage)); if (o.verbose) loguser("[%s] used as source DGRAM Unix domain socket.\n", srcaddr.un.sun_path); } else #endif if (srcaddr.storage.ss_family != AF_UNSPEC) nsi_set_localaddr(cs.sock_nsi, &srcaddr.storage, sizeof(srcaddr.storage)); if (o.numsrcrtes) { unsigned char *ipopts = NULL; size_t ipoptslen = 0; if (o.af != AF_INET) bye("Sorry, -g can only currently be used with IPv4."); ipopts = buildsrcrte(targetss.in.sin_addr, o.srcrtes, o.numsrcrtes, o.srcrteptr, &ipoptslen); nsi_set_ipoptions(cs.sock_nsi, ipopts, ipoptslen); free(ipopts); /* Nsock has its own copy */ } #if HAVE_SYS_UN_H if (o.af == AF_UNIX) { if (o.proto == IPPROTO_UDP) { nsock_connect_unixsock_datagram(mypool, cs.sock_nsi, connect_handler, NULL, &targetss.sockaddr, SUN_LEN((struct sockaddr_un *)&targetss.sockaddr)); } else { nsock_connect_unixsock_stream(mypool, cs.sock_nsi, connect_handler, o.conntimeout, NULL, &targetss.sockaddr, SUN_LEN((struct sockaddr_un *)&targetss.sockaddr)); } } else #endif if (o.proto == IPPROTO_UDP) { nsock_connect_udp(mypool, cs.sock_nsi, connect_handler, NULL, &targetss.sockaddr, targetsslen, inet_port(&targetss)); } #ifdef HAVE_OPENSSL else if (o.proto == IPPROTO_SCTP && o.ssl) { nsock_connect_ssl(mypool, cs.sock_nsi, connect_handler, o.conntimeout, NULL, &targetss.sockaddr, targetsslen, IPPROTO_SCTP, inet_port(&targetss), NULL); } #endif else if (o.proto == IPPROTO_SCTP) { nsock_connect_sctp(mypool, cs.sock_nsi, connect_handler, o.conntimeout, NULL, &targetss.sockaddr, targetsslen, inet_port(&targetss)); } #ifdef HAVE_OPENSSL else if (o.ssl) { nsock_connect_ssl(mypool, cs.sock_nsi, connect_handler, o.conntimeout, NULL, &targetss.sockaddr, targetsslen, IPPROTO_TCP, inet_port(&targetss), NULL); } #endif else { nsock_connect_tcp(mypool, cs.sock_nsi, connect_handler, o.conntimeout, NULL, &targetss.sockaddr, targetsslen, inet_port(&targetss)); } } else { /* A proxy connection. */ static int connect_socket; int len; char *line; size_t n; if (httpconnect.storage.ss_family != AF_UNSPEC) { connect_socket = do_proxy_http(); if (connect_socket == -1) return 1; } else if (socksconnect.storage.ss_family != AF_UNSPEC) { struct socket_buffer stateful_buf; struct socks4_data socks4msg; char socksbuf[8]; connect_socket = do_connect(SOCK_STREAM); if (connect_socket == -1) { loguser("Proxy connection failed: %s.\n", socket_strerror(socket_errno())); return 1; } socket_buffer_init(&stateful_buf, connect_socket); if (o.verbose) { loguser("Connected to proxy %s:%hu\n", inet_socktop(&targetss), inet_port(&targetss)); } /* Fill the socks4_data struct */ zmem(&socks4msg, sizeof(socks4msg)); socks4msg.version = SOCKS4_VERSION; socks4msg.type = SOCKS_CONNECT; socks4msg.port = socksconnect.in.sin_port; socks4msg.address = socksconnect.in.sin_addr.s_addr; if (o.proxy_auth) Strncpy(socks4msg.username, (char *) o.proxy_auth, sizeof(socks4msg.username)); len = 8 + strlen(socks4msg.username) + 1; if (send(connect_socket, (char *) &socks4msg, len, 0) < 0) { loguser("Error sending proxy request: %s.\n", socket_strerror(socket_errno())); return 1; } /* The size of the socks4 response is 8 bytes. So read exactly 8 bytes from the buffer */ if (socket_buffer_readcount(&stateful_buf, socksbuf, 8) < 0) { loguser("Error: short reponse from proxy.\n"); return 1; } if (socksbuf[1] != 90) { loguser("Proxy connection failed.\n"); return 1; } /* Clear out whatever is left in the socket buffer which may be already sent by proxy server along with http response headers. */ line = socket_buffer_remainder(&stateful_buf, &n); /* Write the leftover data to stdout. */ Write(STDOUT_FILENO, line, n); } /* Once the proxy negotiation is done, Nsock takes control of the socket. */ cs.sock_nsi = nsi_new2(mypool, connect_socket, NULL); /* Create IOD for nsp->stdin */ if ((cs.stdin_nsi = nsi_new2(mypool, 0, NULL)) == NULL) bye("Failed to create stdin nsiod."); post_connect(mypool, cs.sock_nsi); } /* connect */ rc = nsock_loop(mypool, -1); if (o.verbose) { struct timeval end_time; double time; gettimeofday(&end_time, NULL); time = TIMEVAL_MSEC_SUBTRACT(end_time, start_time) / 1000.0; loguser("%lu bytes sent, %lu bytes received in %.2f seconds.\n", nsi_get_write_count(cs.sock_nsi), nsi_get_read_count(cs.sock_nsi), time); } #if HAVE_SYS_UN_H if (o.af == AF_UNIX && o.proto == IPPROTO_UDP) { if (o.verbose) loguser("Deleting source DGRAM Unix domain socket. [%s]\n", srcaddr.un.sun_path); unlink(srcaddr.un.sun_path); } #endif nsp_delete(mypool); return rc == NSOCK_LOOP_ERROR ? 1 : 0; }
void ShellCompiler::init(const Dict& opts) { // Base class CompilerInternal::init(opts); // Default options string compiler = "gcc"; string compiler_setup = "-fPIC -shared"; vector<string> flags; // Read options for (auto&& op : opts) { if (op.first=="compiler") { compiler = op.second.to_string(); } else if (op.first=="compiler_setup") { compiler_setup = op.second.to_string(); } else if (op.first=="flags") { flags = op.second; } } // Construct the compiler command stringstream cmd; cmd << compiler << " " << compiler_setup; for (vector<string>::const_iterator i=flags.begin(); i!=flags.end(); ++i) { cmd << " " << *i; } // C/C++ source file cmd << " " << name_; // Name of temporary file #ifdef HAVE_MKSTEMPS // Preferred solution char bin_name[] = "tmp_casadi_compiler_shell_XXXXXX.so"; if (mkstemps(bin_name, 3) == -1) { casadi_error("Failed to create a temporary file name"); } bin_name_ = bin_name; #else // Fallback, may result in deprecation warnings char* bin_name = tempnam(0, "ca.so"); bin_name_ = bin_name; free(bin_name); #endif // Have relative paths start with ./ if (bin_name_.at(0)!='/') { bin_name_ = "./" + bin_name_; } // Temporary file cmd << " -o " << bin_name_; // Compile into a shared library if (system(cmd.str().c_str())) { casadi_error("Compilation failed. Tried \"" + cmd.str() + "\""); } // Load shared library handle_ = dlopen(bin_name_.c_str(), RTLD_LAZY); casadi_assert_message(handle_!=0, "CommonExternal: Cannot open function: " << bin_name_ << ". error code: "<< dlerror()); // reset error dlerror(); }
glio_arena_t * _glio_arena_create( glio_group_t *gg, /* group of processes to share access */ size_t asize) /* arena size (bytes per process) */ { char *fname, *fncpy; int fd; int groupsz; int namelen; int myrank; size_t arena_size; glio_arena_t *arp; shmem_group_t shg; void *aret; MPI_Comm comm; MPI_Status mpistatus; groupsz = gg->groupsz; myrank = gg->myrank; arp = malloc(sizeof(*arp)); if (arp == NULL) { fprintf(stderr,"%s:\n\ _glio_arena_create(a) could not allocate a memory object of size %lld bytes\n", GLOBERRMSG, (long long)sizeof(*arp)); abort(); } bzero(arp, sizeof(*arp)); arp->grp = *gg; /* copy it */ gg = &arp->grp; /* point to the new copy */ /* * Process with rank 0 finds a unique new file name to use as * a memory mapped file. */ if (myrank == 0) { fname = NULL; do { if (fname != NULL) free(fname); fname = tempnam(NULL, "glio_arena"); assert(fname != NULL); fd = open(fname, O_CREAT | O_EXCL | O_RDWR, 0700); } while (fd == -1 && errno == EEXIST); } /* * Trivial groups of size 1 can be handled trivially. */ if (groupsz == 1) goto past_file_name_send; _glio_barrier(arp); /* * Initialization */ switch (gg->grtype) { case GR_SHMEM: if ( _shmem_group_inquire != NULL) { _shmem_group_inquire(arp->grp.u.shmem.group, &shg); } else { /* Special case for pre-release versions of MPT 1.2 */ static int *world_plist; static int *world_racom; /* if pre-release version of MPT 1.2 is used, then all */ /* PEs are in the group */ assert (groupsz == _num_pes()); if (world_plist == NULL) { register short ipe; world_plist = malloc(_num_pes() * sizeof(int)); if (world_plist == NULL) { fprintf(stderr,"%s:\n\ _glio_arena_create(b) could not allocate a memory object of size %lld bytes\n", GLOBERRMSG, (long long)(_num_pes() * sizeof(int))); abort(); } world_racom = shmalloc(SHMEM_GROUP_COM_SIZE * sizeof(int)); assert(world_racom != NULL); bzero(world_racom, 10*sizeof(int)); for (ipe = 0; ipe < _num_pes(); ipe++) world_plist[ipe] = ipe; } shg.groupsz = _num_pes(); shg.myrank = _my_pe(); shg.plist = world_plist; shg.racom = world_racom; } break; case GR_MPI: comm = arp->grp.u.MPI.comm; break; default: break; } /* * Process 0 now must communicate the file name to all other * processes in the group. */ switch (gg->grtype) { case GR_SHMEM: if (myrank == 0) { void *vp; fncpy = _sma_global_heap_alloc(strlen(fname)+1); assert(fncpy != NULL); strcpy(fncpy, fname); vp = fncpy; /* racom[1] gets string length */ shg.racom[1] = strlen(fname); /* racom[2] and racom[3] get the pointer */ /* to the string. */ memcpy(&shg.racom[2], &vp, sizeof(vp)); } _glio_barrier(arp); /* * Other processes now get the file name. */ if (myrank != 0) { void *vp; namelen = _shmem_int_g( &shg.racom[1], shg.plist[0]); assert(namelen > 0); /* get pointer to the string */ _shmem_getmem(&vp, &shg.racom[2], sizeof(vp), shg.plist[0]); fname = malloc(namelen + 1); if (fname == NULL) { fprintf(stderr,"%s:\n\ _glio_arena_create(c) could not allocate a memory object of size %lld bytes\n", GLOBERRMSG, (long long)(namelen + 1)); abort(); } /* copy the string */ _shmem_getmem(fname, vp, namelen, shg.plist[0]); fname[namelen] = '\0'; } _glio_barrier(arp); if (myrank == 0) { _sma_global_heap_free(fncpy); } break; case GR_MPI: if (myrank == 0) { register int rank; namelen = strlen(fname); for (rank = 1; rank < groupsz; rank++) { ckMPIerr( MPI_Send(&namelen, 1, MPI_INT, rank, 1, comm) ); } for (rank = 1; rank < groupsz; rank++) { ckMPIerr( MPI_Send(fname, namelen, MPI_CHAR, rank, 2, comm) ); } } else { ckMPIerr( MPI_Recv(&namelen, 1, MPI_INT, 0, 1, comm, &mpistatus) ); fname = malloc(namelen + 1); if (fname == NULL) { fprintf(stderr,"%s:\n\ _glio_arena_create(d) could not allocate a memory object of size %lld bytes\n", GLOBERRMSG, (long long)(namelen + 1)); abort(); } ckMPIerr( MPI_Recv(fname, namelen, MPI_CHAR, 0, 2, comm, &mpistatus) ); fname[namelen] = '\0'; } break; default: assert(0); } _glio_barrier(arp); /* * Non-rank-0 processes now open the file. */ if (myrank != 0) { fd = open(fname, O_RDWR, 0700); if (fd == -1) { fprintf(stderr, "%s:\n\ Global I/O failed to open mapped file. Errno is %d\n", GLOBERRMSG, errno); abort(); } } _glio_barrier(arp); past_file_name_send: /* * All processes have opened the file, so rank 0 may now unlink it. */ if (myrank == 0) { unlink(fname); } _glio_barrier(arp); /* * After the barrier process 0 may initialize the mapped * file and unlink it because we know that all processes in the * group have now opened this file. */ arena_size = groupsz * CEILING(asize, 1024); if (myrank == 0) { ssize_t wret; wret = pwrite(fd, " ", 1, arena_size - 1); assert(wret != -1L); } _glio_barrier(arp); /* * A barrier assures us that the file has been initialized * to the right size. Now map the file into every process' * address space. */ aret = mmap64(NULL, arena_size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (aret == MAP_FAILED) { fprintf(stderr,"%s:\n\ Cannot map internal file %s\n\ for shared memory arena. Error = %d\n", GLOBERRMSG, fname, errno); abort(); }
FILE * os_popen(const char *command, char *mode ) { FILE *current; char *name; int cur; char curmode[4]; #if defined(__MINGW32__) || (defined(_MSC_VER) && defined(WIN32)) char *cmd; #endif #if defined(OS2) && (_MSC_VER != 510) if (_osmode == OS2_MODE) return(popen(command, mode)); #endif if (*mode != 'r' && *mode != 'w') return NULL; strncpy(curmode, mode, 3); curmode[3] = '\0'; #if defined(__MINGW32__) || (defined(_MSC_VER) && defined(WIN32)) current = popen(cmd = scriptify(command), mode); cur = fileno(current); strcpy(pipes[cur].pmode, curmode); pipes[cur].command = cmd; return(current); #endif /* ** get a name to use. */ if((name = tempnam(".","pip"))==NULL) return NULL; /* ** If we're reading, just call system to get a file filled with ** output. */ if (*curmode == 'r') { FILE *fp; if ((cur = dup(fileno(stdout))) == -1) return NULL; *curmode = 'w'; if ((current = freopen(name, curmode, stdout)) == NULL) return NULL; os_system(command); if (dup2(cur, fileno(stdout)) == -1) return NULL; close(cur); *curmode = 'r'; if ((current = fopen(name, curmode)) == NULL) return NULL; } else { if ((current = fopen(name, curmode)) == NULL) return NULL; } cur = fileno(current); pipes[cur].name = name; strcpy(pipes[cur].pmode, curmode); pipes[cur].command = strdup(command); return current; }
integer f_open (olist * a) { unit *b; integer rv; char buf[256], *s, *env; cllist x; int ufmt; FILE *tf; int fd, len; #ifndef NON_UNIX_STDIO int n; #endif if (f__init != 1) f_init (); f__external = 1; if (a->ounit >= MXUNIT || a->ounit < 0) err (a->oerr, 101, "open"); f__curunit = b = &f__units[a->ounit]; if (b->ufd) { if (a->ofnm == 0) { same:if (a->oblnk) b->ublnk = *a->oblnk == 'z' || *a->oblnk == 'Z'; return (0); } #ifdef NON_UNIX_STDIO if (b->ufnm && strlen (b->ufnm) == a->ofnmlen && !strncmp (b->ufnm, a->ofnm, (unsigned) a->ofnmlen)) goto same; #else g_char (a->ofnm, a->ofnmlen, buf); if (f__inode (buf, &n) == b->uinode && n == b->udev) goto same; #endif x.cunit = a->ounit; x.csta = 0; x.cerr = a->oerr; if ((rv = f_clos (&x)) != 0) return rv; } b->url = (int) a->orl; b->ublnk = a->oblnk && (*a->oblnk == 'z' || *a->oblnk == 'Z'); if (a->ofm == 0) if ((a->oacc) && (*a->oacc == 'D' || *a->oacc == 'd')) b->ufmt = 0; else b->ufmt = 1; else if (*a->ofm == 'f' || *a->ofm == 'F') b->ufmt = 1; else b->ufmt = 0; ufmt = b->ufmt; #ifdef url_Adjust if (b->url && !ufmt) url_Adjust (b->url); #endif if (a->ofnm) { g_char (a->ofnm, a->ofnmlen, buf); if (!buf[0]) opnerr (a->oerr, 107, "open"); } else sprintf (buf, "fort.%ld", (long) a->ounit); b->uscrtch = 0; b->uend = 0; b->uwrt = 0; b->ufd = 0; b->urw = 3; switch (a->osta ? *a->osta : 'u') { case 'o': case 'O': #ifdef NON_POSIX_STDIO if (!(tf = fopen (buf, "r"))) opnerr (a->oerr, errno, "open"); fclose (tf); #else if (access (buf, 0)) opnerr (a->oerr, errno, "open"); #endif break; case 's': case 'S': b->uscrtch = 1; #ifdef HAVE_MKSTEMP /* Allow use of TMPDIR preferentially. */ env = getenv ("TMPDIR"); if (!env) env = getenv ("TEMP"); if (!env) env = "/tmp"; len = strlen (env); if (len > 256 - (int) sizeof ("/tmp.FXXXXXX")) err (a->oerr, 132, "open"); strcpy (buf, env); strcat (buf, "/tmp.FXXXXXX"); fd = mkstemp (buf); if (fd == -1 || close (fd)) err (a->oerr, 132, "open"); #else /* ! defined (HAVE_MKSTEMP) */ #ifdef HAVE_TEMPNAM /* Allow use of TMPDIR preferentially. */ s = tempnam (0, buf); if (strlen (s) >= sizeof (buf)) err (a->oerr, 132, "open"); (void) strcpy (buf, s); free (s); #else /* ! defined (HAVE_TEMPNAM) */ #ifdef HAVE_TMPNAM tmpnam (buf); #else (void) strcpy (buf, "tmp.FXXXXXX"); (void) mktemp (buf); #endif #endif /* ! defined (HAVE_TEMPNAM) */ #endif /* ! defined (HAVE_MKSTEMP) */ goto replace; case 'n': case 'N': #ifdef NON_POSIX_STDIO if ((tf = fopen (buf, "r")) || (tf = fopen (buf, "a"))) { fclose (tf); opnerr (a->oerr, 128, "open"); } #else if (!access (buf, 0)) opnerr (a->oerr, 128, "open"); #endif /* no break */ case 'r': /* Fortran 90 replace option */ case 'R': replace: if ((tf = fopen (buf, f__w_mode[0]))) fclose (tf); } b->ufnm = (char *) malloc ((unsigned int) (strlen (buf) + 1)); if (b->ufnm == NULL) opnerr (a->oerr, 113, "no space"); (void) strcpy (b->ufnm, buf); if ((s = a->oacc) && b->url) ufmt = 0; if (!(tf = fopen (buf, f__w_mode[ufmt | 2]))) { if ((tf = fopen (buf, f__r_mode[ufmt]))) b->urw = 1; else if ((tf = fopen (buf, f__w_mode[ufmt]))) { b->uwrt = 1; b->urw = 2; } else err (a->oerr, errno, "open"); } b->useek = f__canseek (b->ufd = tf); #ifndef NON_UNIX_STDIO if ((b->uinode = f__inode (buf, &b->udev)) == -1) opnerr (a->oerr, 108, "open"); #endif if (b->useek) { if (a->orl) FSEEK (b->ufd, 0, SEEK_SET); else if ((s = a->oacc) && (*s == 'a' || *s == 'A') && FSEEK (b->ufd, 0, SEEK_END)) opnerr (a->oerr, 129, "open"); } return (0); }
static int Retrieve( addons_finder_t *p_finder, addon_entry_t *p_entry ) { vlc_mutex_lock( &p_entry->lock ); if ( !p_entry->psz_archive_uri ) { vlc_mutex_unlock( &p_entry->lock ); return VLC_EGENERIC; } char *psz_archive_uri = strdup( p_entry->psz_archive_uri ); vlc_mutex_unlock( &p_entry->lock ); if ( !psz_archive_uri ) return VLC_ENOMEM; /* get archive and parse manifest */ stream_t *p_stream; if ( psz_archive_uri[0] == '/' ) { /* Relative path */ char *psz_uri; if ( ! asprintf( &psz_uri, ADDONS_REPO_SCHEMEHOST"%s", psz_archive_uri ) ) { free( psz_archive_uri ); return VLC_ENOMEM; } p_stream = stream_UrlNew( p_finder, psz_uri ); free( psz_uri ); } else { p_stream = stream_UrlNew( p_finder, psz_archive_uri ); } msg_Dbg( p_finder, "downloading archive %s", psz_archive_uri ); free ( psz_archive_uri ); if ( !p_stream ) return VLC_EGENERIC; /* In case of pf_ reuse */ if ( p_finder->p_sys->psz_tempfile ) { vlc_unlink( p_finder->p_sys->psz_tempfile ); FREENULL( p_finder->p_sys->psz_tempfile ); } p_finder->p_sys->psz_tempfile = tempnam( NULL, "vlp" ); if ( !p_finder->p_sys->psz_tempfile ) { msg_Err( p_finder, "Can't create temp storage file" ); stream_Delete( p_stream ); return VLC_EGENERIC; } FILE *p_destfile = vlc_fopen( p_finder->p_sys->psz_tempfile, "w" ); if( !p_destfile ) { msg_Err( p_finder, "Failed to open addon temp storage file" ); FREENULL(p_finder->p_sys->psz_tempfile); stream_Delete( p_stream ); return VLC_EGENERIC; } char buffer[1<<10]; int i_read = 0; while ( ( i_read = stream_Read( p_stream, &buffer, 1<<10 ) ) > 0 ) { if ( fwrite( &buffer, i_read, 1, p_destfile ) < 1 ) { msg_Err( p_finder, "Failed to write to Addon file" ); fclose( p_destfile ); stream_Delete( p_stream ); return VLC_EGENERIC; } } fclose( p_destfile ); stream_Delete( p_stream ); msg_Dbg( p_finder, "Reading manifest from %s", p_finder->p_sys->psz_tempfile ); char *psz_tempfileuri = vlc_path2uri( p_finder->p_sys->psz_tempfile, "unzip" ); if ( !psz_tempfileuri ) return VLC_ENOMEM; char *psz_manifest_uri; if ( asprintf( &psz_manifest_uri, "%s!/manifest.xml", psz_tempfileuri ) < 1 ) { free( psz_tempfileuri ); return VLC_ENOMEM; } p_stream = stream_UrlNew( p_finder, psz_manifest_uri ); free( psz_manifest_uri ); if ( !p_stream ) { free( psz_tempfileuri ); return VLC_EGENERIC; } vlc_mutex_lock( &p_entry->lock ); int i_ret = ( ParseManifest( p_finder, p_entry, psz_tempfileuri, p_stream ) > 0 ) ? VLC_SUCCESS : VLC_EGENERIC; vlc_mutex_unlock( &p_entry->lock ); free( psz_tempfileuri ); stream_Delete( p_stream ); return i_ret; }
int main(int argc, char *argv[]) { int i,n; int opt, r=0, fuse_ret=0; int tmp_mntpoint=0; //FILE *tranche_ofp = stdout; char **fuse_args; int persist_flag = 0; tranche_ofp = stdout; fuse_args = (char **)malloc(sizeof(char*)*3); fuse_args[0] = strdup(argv[0]); fuse_args[1] = NULL; fuse_args[2] = strdup("-f"); tranche_start = 0; tranche_size = -1; tranche_mountpoint=NULL; tranche_exposed_fn=NULL; tranche_ifn=NULL; tranche_ifd=-1; memset(&tranche_stbuf, 0, sizeof(struct stat)); while ((opt=getopt(argc, argv, "b:s:f:m:qhpD"))!=-1) switch(opt) { case 'b': tranche_start = atoi(optarg); break; case 's': tranche_size = atoi(optarg); break; case 'f': tranche_ifn = strdup(optarg); break; case 'm': tranche_mountpoint = strdup(optarg); break; case 'q': quiet_flag = 1; break; case 'h': help_flag = 1; break; case 'p': persist_flag = 1; break; case 'D': g_debug = 1; break; default: break; } if (help_flag) { show_help(); exit(1); } if (!tranche_ifn) { fprintf(stderr, "Provide input filename (-f)\n"); show_help(); exit(1); } // Create mount point and construct exposed filename // if (!tranche_mountpoint) { tranche_mountpoint = strdup("/tmp/tranchemntXXXXXX"); mkdtemp(tranche_mountpoint); tmp_mntpoint=1; } tranche_exposed_fn = tempnam(tranche_mountpoint, NULL); fuse_args[1] = strdup(tranche_mountpoint); // Open the underlying file and get stats for it // tranche_ifd = open(tranche_ifn, O_RDONLY); if (tranche_ifd<0) { perror("error: "); exit(errno); } r = fstat(tranche_ifd, &tranche_stbuf); if (r<0) { perror("error:"); return r; } if ((tranche_size<0) || ((tranche_stbuf.st_size-tranche_start) < tranche_size)) { tranche_size = tranche_stbuf.st_size-tranche_start; } if (tranche_size<=0) { tranche_size=0; } n = strlen(tranche_exposed_fn); for (i=n-1; i>=0; i--) { if (tranche_exposed_fn[i]=='/') { break; } } if (i<0) { i=0; } tranche_mount_path = strdup(tranche_exposed_fn+i); // Start fuse server. // // The fuse server is running in the foreground (the '-f' // option in fuse_args) and will block until it's done. // fuse_ret = fuse_main(2+persist_flag, fuse_args, &tranche_oper, NULL); // Fuse serverhas been stopped, close our underlying file // close(tranche_ifd); // Cleanup the mount point // if (tmp_mntpoint) { r = rmdir(tranche_mountpoint); if (r<0) { perror(""); } } free(fuse_args[0]); free(fuse_args[1]); free(fuse_args[2]); free(fuse_args); free(tranche_ifn); free(tranche_mountpoint); return fuse_ret; }
// pre-process input file, creating a tmp file // In order to get the return code of the C pre-processor, I'm // spawing a batch file that invokes CL, and creates a signal file // if it is successful. VOID NEAR DoPreProcess ( ) { char szBuffer[255]; HANDLE hInstCpp; TASKENTRY taskentry; FILE * hFile; CHAR * szTempBatch; CHAR * szTempSig; CHAR * szTempRoot; ERR err = ERR_CPP; // assume error int cbTempFilenames; char * szComSpec; // figure out the names of the temp files // (note: uses OEM char set) szTempRoot = tempnam(".", "~mkt"); // get base name for temp files hFile = fopen(szTempRoot, "w"); // create the file now, to if (hFile == NULL) // reserve this set of names ParseError(ERR_CPP); fclose(hFile); cbTempFilenames = strlen(szTempRoot)+1+3+1; // base name + ext + null szTempBatch = malloc(cbTempFilenames); // for .BAT file strcpy(szTempBatch, szTempRoot); strcat(szTempBatch, ".bat"); szTempSig = malloc(cbTempFilenames); // for .SIG file strcpy(szTempSig, szTempRoot); strcat(szTempSig, ".sig"); szTempFile = malloc(cbTempFilenames); // for pre-processed oupput strcpy(szTempFile, szTempRoot); strcat(szTempFile, ".inp"); // CONSIDER: Check for existence of any of these files, if any exist, then // CONSIDER: try a different base name for the files. // open the temp .BAT file hFile = fopen(szTempBatch, "w"); if (hFile == NULL) goto cleanup2; // all errors after this point should go to 'cleanup' if (fputs(szBatchStart, hFile) < 0) // write the first part goto cleanup; sprintf(szBuffer, "%s %s%s %s>", szCppExe, szCppOpts, szCppDefs, szInputFile); // convert this string to the OEM char set AnsiToOem(szBuffer, szBuffer); // append szTempFile strcat(szBuffer, szTempFile); strcat(szBuffer, "\n"); if (fputs(szBuffer, hFile) < 0) // write the CPP command goto cleanup; sprintf(szBuffer, szBatchEnd, szTempSig); if (fputs(szBuffer, hFile) < 0) // write the error check code goto cleanup; fclose(hFile); hFile = NULL; // file no longer open szComSpec = getenv("COMSPEC"); if (szComSpec == NULL) szComSpec = "command.com"; sprintf(szBuffer, "%s /c %s", szComSpec, szTempBatch); hInstCpp = WinExec(szBuffer, SW_SHOWMINIMIZED); // shell the pre-processor if (hInstCpp < 32) // if error spawning pre-processor goto cleanup; Yield(); // give it a chance to start // find task associated with this instance. In extreme cases it may have // finished even before we're executing this code. taskentry.dwSize = sizeof(TASKENTRY); if (TaskFirst(&taskentry) == 0) { goto taskdone; } while (taskentry.hInst != hInstCpp) { if (TaskNext(&taskentry) == 0) { goto taskdone; } } hTaskCpp = taskentry.hTask; while (IsTask(hTaskCpp)) { SideAssert(TaskFindHandle(&taskentry, hTaskCpp) != 0); if (taskentry.hInst != hInstCpp) { // different hInst associated with this htask, // so the app must have terminated break; } Yield(); // wait until it's done } taskdone: // If signal file doesn't exist, then there was a problem pre-processing // the input file. If it exists, then it worked. if (!MyRemove(szTempSig)) err = ERR_NONE; // it worked! cleanup: if (hFile) // close tmp batch file if fclose(hFile); // error during write SideAssert(MyRemove(szTempBatch) == 0); // delete tmp batch file cleanup2: SideAssert(MyRemove(szTempRoot) == 0); // delete placeholder file if (err != ERR_NONE) // report any error ParseError(err); }
// created this from the WIN32 docs, using info on WinExec and CreateProcess // WARNING: the example given in the WIN32 docs on CreateProcess is bogus. VOID NEAR DoPreProcess ( ) { char szBuffer[512]; BOOL fSuccess; STARTUPINFO si; PROCESS_INFORMATION pi; SECURITY_ATTRIBUTES sa; DWORD dw; DWORD dwExitCode; HANDLE hProcess; HANDLE hOutput; memset (&si, 0, sizeof(si)); memset (&pi, 0, sizeof(pi)); memset (&sa, 0, sizeof(sa)); szTempFile = strdup(tempnam(".", "~mki")); // for pre-processed output sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; hOutput = CreateFile(szTempFile, GENERIC_WRITE, 0, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0); if (hOutput == INVALID_HANDLE_VALUE) ParseError(ERR_CPP); sprintf(szBuffer, "%s %s%s %s", szCppExe, szCppOpts, szCppDefs, szInputFile); // init si structure si.cb = sizeof(si); si.lpTitle = "MkTypLib: C pre-processor"; //si.dwX = 100; // just guessing... //si.dwY = 100; //si.dwXSize = 1000; //si.dwYSize = 1000; si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.hStdOutput = hOutput; //si.hStdError = hOutputError; // CONSIDER: show this to the user? //si.wShowWindow = SW_SHOWMINIMIZED; si.wShowWindow = SW_HIDE; // Setting the Inherit Handles flag to TRUE so that it works when // run under nmake with our output redirected. fSuccess = CreateProcess(NULL, szBuffer, NULL, NULL, TRUE, // this gives us a window'ed CL //DETACHED_PROCESS, 0, NULL, NULL, &si, &pi); if (!fSuccess) { CloseHandle(hOutput); ParseError(ERR_CPP); } // if we were successful, now wait for it to be done hProcess = pi.hProcess; // wait for the process to complete (120 second timeoout) dw = WaitForSingleObject(pi.hProcess, 120000L); #ifndef STATUS_SUCCESS #define STATUS_SUCCESS 0 #endif if (dw == STATUS_SUCCESS) fSuccess = GetExitCodeProcess(pi.hProcess, &dwExitCode); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(hOutput); // report any error if (dw != STATUS_SUCCESS || !fSuccess || dwExitCode != 0) ParseError(ERR_CPP); }
//--------------------------------------- // Arguments: // inFile: input file name. NULL if STDIN is used // outFile: output file name, NULL if STDOUT is used // Returns: // 0: successful // errCode: if failed //--------------------------------------- int VnFileConvert(int inCharset, int outCharset, const char *inFile, const char *outFile) { FILE *inf = NULL; FILE *outf = NULL; int ret = 0; char *tmpName; if (inFile == NULL) { inf = stdin; #if defined(_WIN32) _setmode( _fileno(stdin), _O_BINARY); #endif } else { inf = fopen(inFile, "rb"); if (inf == NULL) { ret = VNCONV_ERR_INPUT_FILE; goto end; } } if (outFile == NULL) outf = stdout; else { // setup temporary output file (because real output file may be the same as input file char outDir[256]; strcpy(outDir, outFile); #if defined(_WIN32) char *p = strrchr(outDir, '\\'); #else char *p = strrchr(outDir, '/'); #endif if (p == NULL) outDir[0] = 0; else *p = 0; tmpName = tempnam(outDir, NULL); if (tmpName == NULL) { fclose(inf); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } outf = fopen(tmpName, "wb"); if (outf == NULL) { fclose(inf); free(tmpName); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } } ret = vnFileStreamConvert(inCharset, outCharset, inf, outf); if (inf != stdin) fclose(inf); if (outf != stdout) { fclose(outf); // delete output file if exisits if (ret == 0) { remove(outFile); #if !defined(_WIN32) char cmd[256]; sprintf(cmd, "mv %s %s", tmpName, outFile); system(cmd); #else if (rename(tmpName, outFile) != 0) { remove(tmpName); free(tmpName); ret = VNCONV_ERR_OUTPUT_FILE; goto end; } #endif } else remove(tmpName); free(tmpName); } end: #if defined(_WIN32) if (inf == stdin) { _setmode( _fileno(stdin), _O_BINARY); } #endif return ret; }
frefid_t glk_fileref_create_temp(glui32 usage, glui32 rock) { char *name = tempnam(NULL, "glknew"); return glk_fileref_create_by_name(usage, name, rock); }
/* * This is the function that actually installs one volume (usually that's * all there is). Upon entry, the extlist is entirely correct: * * 1. It contains only those files which are to be installed * from all volumes. * 2. The mode bits in the ainfo structure for each file are set * correctly in accordance with administrative defaults. * 3. mstat.setuid/setgid reflect what the status *was* before * pkgdbmerg() processed compliance. */ void instvol(struct cfextra **extlist, char *srcinst, int part, int nparts, VFP_T **a_cfVfp, VFP_T **a_cfTmpVfp, char **r_updated, char **r_skipped, char *a_zoneName) { FILE *listfp; char *updated = (char *)NULL; char *skipped = (char *)NULL; char *anyPathLocal = (char *)NULL; char *relocpath = (char *)NULL; char *dstp; char *listfile; char *srcp; char *pspool_loc; char scrpt_dst[PATH_MAX]; int count; int entryidx; /* array of current package objects */ int n; int nc = 0; int pass; /* pass count through the for loop. */ int tcount; struct cfent *ept; struct cfextra *ext; struct mergstat *mstat; struct reg_files *rfp = NULL; /* * r_updated and r_skipped are optional parameters that can be passed in * by the caller if the caller wants to know if any objects are either * updated or skipped. Do not initialize either r_updated or r_skipped; * the call to instvol could be cumulative and any previous update or * skipped indication must not be disturbed - these flags are only set, * they must never be reset. These flags are "char *" pointers so that * the object that was skipped or updated can be displayed in debugging * output. */ if (part == 1) { pkgvolume(&pkgdev, srcinst, part, nparts); } tcount = 0; nc = cl_getn(); /* * For each class in this volume, install those files. * * NOTE : This loop index may be decremented by code below forcing a * second trip through for the same class. This happens only when a * class is split between an archive and the tree. Examples would be * old WOS packages and the occasional class containing dynamic * libraries which require special treatment. */ if (is_depend_pkginfo_DB() == B_FALSE) { int classidx; /* the current class */ for (classidx = 0; classidx < nc; classidx++) { int pass_relative = 0; int rel_init = 0; eocflag = count = pass = 0; listfp = (FILE *)0; listfile = NULL; /* Now what do we pass to the class action script */ if (cl_pthrel(classidx) == REL_2_CAS) { pass_relative = 1; } for (;;) { if (!tcount++) { /* first file to install */ if (a_zoneName == (char *)NULL) { echo(MSG_INS_N_N, part, nparts); } else { echo(MSG_INS_N_N_LZ, part, nparts, a_zoneName); } } /* * If there's an install class action script and no * list file has been created yet, create that file * and provide the pointer in listfp. */ if (cl_iscript(classidx) && !listfp) { /* create list file */ putparam("TMPDIR", tmpdir); listfile = tempnam(tmpdir, "list"); if ((listfp = fopen(listfile, "w")) == NULL) { progerr(ERR_WTMPFILE, listfile); quit(99); } } /* * The following function goes through the package * object list returning the array index of the next * regular file. If it encounters a directory, * symlink, named pipe or device, it just creates it. */ entryidx = domerg(extlist, (pass++ ? 0 : part), nparts, classidx, &srcp, &dstp, &updated, &skipped, &anyPathLocal); /* Evaluate the return code */ if (entryidx == DMRG_DONE) { /* * Set ept to the first entry in extlist * which is guaranteed to exist so * later checks against ept->ftype are * not compared to NULL. */ ext = extlist[0]; ept = &(ext->cf_ent); break; /* no more entries to process */ } ext = extlist[entryidx]; ept = &(ext->cf_ent); mstat = &(ext->mstat); /* * If not installing from a partially spooled package * (the "save/pspool" area), and the file contents can * be changed (type is 'e' or 'v'), and the class is not * "none": copy the file from the package (in pristine * state with no actions performed) into the appropriate * location in the packages destination "save/pspool" * area. */ if ((!is_partial_inst()) && ((ept->ftype == 'e') || (ept->ftype == 'v')) && (strcmp(ept->pkg_class, "none") != 0)) { if (absolutepath(ext->map_path) == B_TRUE && parametricpath(ext->cf_ent.ainfo.local, &relocpath) == B_FALSE) { pspool_loc = ROOT; } else { pspool_loc = RELOC; } n = snprintf(scrpt_dst, PATH_MAX, "%s/%s/%s", saveSpoolInstallDir, pspool_loc, relocpath ? relocpath : ext->map_path); if (n >= PATH_MAX) { progerr(ERR_CREATE_PATH_2, saveSpoolInstallDir, ext->map_path); quit(99); } /* copy, preserve source file mode */ if (cppath(MODE_SRC, srcp, scrpt_dst, 0644)) { warnflag++; } } /* * If this isn't writeable anyway, it's not going * into the list file. Only count it if it's going * into the list file. */ if (is_fs_writeable(ext->cf_ent.path, &(ext->fsys_value))) count++; pkgvolume(&pkgdev, srcinst, part, nparts); /* * If source verification is OK for this class, make * sure the source we're passing to the class action * script is useable. */ if (cl_svfy(classidx) != NOVERIFY) { if (cl_iscript(classidx) || ((ept->ftype == 'e') || (ept->ftype == 'n'))) { if (ck_efile(srcp, ept)) { progerr(ERR_CORRUPT, srcp); logerr(getErrbufAddr()); warnflag++; continue; } } } /* * If there's a class action script for this class, * just collect names in a temporary file * that will be used as the stdin when the * class action script is invoked. */ if ((cl_iscript(classidx)) && ((is_fs_writeable(ept->path, &(ext->fsys_value))))) { if (pass_relative) { if (!rel_init) { (void) fputs(instdir, listfp); (void) putc('\n', listfp); rel_init++; } (void) fputs(ext->map_path, listfp); (void) putc('\n', listfp); } else { (void) fputs(srcp ? srcp : "/dev/null", listfp); (void) putc(' ', listfp); (void) fputs(dstp, listfp); (void) putc('\n', listfp); } /* * Note which entries in extlist are regular * files to be installed via the class action * script. */ if (regfiles_head == NULL) { assert(rfp == NULL); regfiles_head = malloc(sizeof (struct reg_files)); if (regfiles_head == NULL) { progerr(ERR_MEMORY, errno); quit(99); } regfiles_head->next = NULL; regfiles_head->val = entryidx; rfp = regfiles_head; } else { assert(rfp != NULL); rfp->next = malloc(sizeof (struct reg_files)); if (rfp->next == NULL) { progerr(ERR_MEMORY, errno); quit(99); } rfp = rfp->next; rfp->next = NULL; rfp->val = entryidx; } /* * A warning message about unwritable targets * in a class may be appropriate here. */ continue; } /* * If not installing from a partially spooled package * (the "save/pspool" area), and the file contents can * be changed (type is 'e' or 'v') and the class * identifier is not "none": copy the file from the * package (in pristine state with no actions performed) * into the appropriate location in the packages * destination "save/pspool" area. */ if ((!is_partial_inst()) && ((ept->ftype == 'e') || (ept->ftype == 'v') && (strcmp(ept->pkg_class, "none") != 0))) { if (absolutepath(ext->map_path) == B_TRUE && parametricpath(ext->cf_ent.ainfo.local, &relocpath) == B_FALSE) { pspool_loc = ROOT; } else { pspool_loc = RELOC; } n = snprintf(scrpt_dst, PATH_MAX, "%s/%s/%s", saveSpoolInstallDir, pspool_loc, relocpath ? relocpath : ext->map_path); if (n >= PATH_MAX) { progerr(ERR_CREATE_PATH_2, saveSpoolInstallDir, ext->map_path); quit(99); } /* copy, preserve source file mode */ if (cppath(MODE_SRC, srcp, scrpt_dst, 0644)) { warnflag++; } } /* * There are several tests here to determine * how we're going to deal with objects * intended for remote read-only filesystems. * We don't use is_served() because this may be * a server. We're actually interested in if * it's *really* remote and *really* not * writeable. */ n = is_remote_fs(ept->path, &(ext->fsys_value)); if ((n != 0) && !is_fs_writeable(ept->path, &(ext->fsys_value))) { /* * Don't change the file, we can't write * to it anyway. */ mstat->attrchg = 0; mstat->contchg = 0; /* * If it's currently mounted, we can * at least test it for existence. */ if (is_mounted(ept->path, &(ext->fsys_value))) { if (!isfile(NULL, dstp)) { echo(MSG_IS_PRESENT, dstp); } else { echo(WRN_INSTVOL_NONE, dstp); } } else { char *server_host; server_host = get_server_host( ext->fsys_value); /* If not, we're just stuck. */ echo(WRN_INSTVOL_NOVERIFY, dstp, server_host); } continue; } /* echo output destination name */ echo("%s", dstp); /* * if no source then no need to copy/verify */ if (srcp == (char *)NULL) { continue; } /* * If doing a partial installation (creating a * non-global zone), extra steps need to be taken: * * 1) if the file is not type 'e' and not type 'v' and * the class is "none": then the file must already * exist (as a result of the initial non-global zone * installation which caused all non-e/v files to be * copied from the global zone to the non-global * zone). If this is the case, verify that the file * exists and has the correct attributes. * * 2) if the file is not type 'e' and not type 'v' * and the class is NOT "none", *OR* if the file is * type 'e' or type 'v': then check to see if the * file is located in an area inherited from the * global zone. If so, then there is no ability to * change the file since inherited file systems are * "read only" - just verify that the file exists and * verify attributes only if not 'e' or 'v'. */ if (is_partial_inst() != 0) { /* * determine if the destination package is in an * area inherited from the global zone */ n = pkgMatchInherited(srcp, dstp, get_inst_root(), ept->ainfo.mode, ept->cinfo.modtime, ept->ftype, ept->cinfo.cksum); echoDebug(DBG_INSTVOL_PARTIAL_INST, srcp ? srcp : "", dstp ? dstp: "", ((get_inst_root()) && (strcmp(get_inst_root(), "/") != 0)) ? get_inst_root() : "", ept->ainfo.mode, ept->cinfo.modtime, ept->ftype, ept->cinfo.cksum, n); /* * if not type 'e|v' and class 'none', then the * file must already exist. */ if ((ept->ftype != 'e') && (ept->ftype != 'v') && (strcmp(cl_nam(ept->pkg_class_idx), "none") == 0)) { /* * if the file is in a space inherited * from the global zone, and if the * contents or attributes are incorrect, * then generate a warning that the * global zone file contents and/or file * attributes have been modified and * that the modifications are extended * to the non-global zone (inherited * from the global zone). */ if (n == 0) { /* is file changed? */ n = finalck(ept, 1, 1, B_TRUE); /* no - ok - continue */ if (n == 0) { continue; } /* output warning message */ logerr(NOTE_INSTVOL_FINALCKFAIL, pkginst, ext->map_path, a_zoneName, ept->path); continue; } else if (!finalck(ept, 1, 1, B_FALSE)) { /* * non-e/v file of class "none" * not inherited from the global * zone: verify file already * exists:everything checks here */ mstat->attrchg = 0; mstat->contchg = 0; } continue; } /* * non-e/v file with class action script, or * e/v file: if the file is in an area inherited * from the global zone, then no need (or the * ability) to update just accept the file as is */ if (n == B_TRUE) { /* * the object is in an area inherited * from the global zone and the objects * attributes are verified */ mstat->attrchg = 0; mstat->contchg = 0; /* NOTE: package object skipped */ if (skipped == (char *)NULL) { skipped = dstp; echoDebug(DBG_INSTVOL_OBJ_SKIPPED, skipped); } continue; } } /* * Copy from source media to target path and fix file * mode and permission now in case installation halted. */ if (z_path_is_inherited(dstp, ept->ftype, get_inst_root()) == B_FALSE) { n = cppath(MODE_SET|DIR_DISPLAY, srcp, dstp, ept->ainfo.mode); if (n != 0) { warnflag++; } else if (!finalck(ept, 1, 1, B_FALSE)) { /* * everything checks here */ mstat->attrchg = 0; mstat->contchg = 0; } } /* NOTE: a package object was updated */ if (updated == (char *)NULL) { echoDebug(DBG_INSTVOL_OBJ_UPDATED, dstp); updated = dstp; } } /* * We have now completed processing of all pathnames * associated with this volume and class. */ if (cl_iscript(classidx)) { /* * Execute appropriate class action script * with list of source/destination pathnames * as the input to the script. */ if (chdir(pkgbin)) { progerr(ERR_CHGDIR, pkgbin); quit(99); } if (listfp) { (void) fclose(listfp); } /* * if the object associated with the class action script * is in an area inherited from the global zone, then * there is no need to run the class action script - * assume that anything the script would do has already * been done in the area shared from the global zone. */ /* nothing updated, nothing skipped */ echoDebug(DBG_INSTVOL_CAS_INFO, is_partial_inst(), updated ? updated : "", skipped ? skipped : "", anyPathLocal ? anyPathLocal : ""); if ((is_partial_inst() != 0) && (updated == (char *)NULL) && (anyPathLocal == (char *)NULL)) { /* * installing in non-global zone, and no object * has been updated (installed/verified in non- * inherited area), and no path delivered by the * package is in an area not inherited from the * global zone (all paths delivered are in * areas inherited from the global zone): do not * run the class action script because the only * affected areas are inherited (read only). */ echoDebug(DBG_INSTVOL_NOT_RUNNING_CAS, a_zoneName ? a_zoneName : "?", eocflag ? "ENDOFCLASS" : cl_iscript(classidx), cl_nam(classidx), cl_iscript(classidx)); if ((r_skipped != (char **)NULL) && (*r_skipped == (char *)NULL) && (skipped == (char *)NULL)) { skipped = "postinstall"; echoDebug(DBG_INSTVOL_OBJ_SKIPPED, skipped); } } else { /* run the class action script */ echoDebug(DBG_INSTVOL_RUNNING_CAS, a_zoneName ? a_zoneName : "?", eocflag ? "ENDOFCLASS" : cl_iscript(classidx), cl_nam(classidx), cl_iscript(classidx)); /* Use ULIMIT if supplied. */ set_ulimit(cl_iscript(classidx), ERR_CASFAIL); if (eocflag) { /* * end of class detected. * Since there are no more volumes which * contain pathnames associated with * this class, execute class action * script with the ENDOFCLASS argument; * we do this even if none of the path * names associated with this class and * volume needed installation to * guarantee the class action script is * executed at least once during package * installation. */ if (pkgverbose) { n = pkgexecl((listfp ? listfile : CAS_STDIN), CAS_STDOUT, CAS_USER, CAS_GRP, SHELL, "-x", cl_iscript(classidx), "ENDOFCLASS", NULL); } else { n = pkgexecl( (listfp ? listfile : CAS_STDIN), CAS_STDOUT, CAS_USER, CAS_GRP, SHELL, cl_iscript(classidx), "ENDOFCLASS", NULL); } ckreturn(n, ERR_CASFAIL); } else if (count) { /* execute class action script */ if (pkgverbose) { n = pkgexecl(listfile, CAS_STDOUT, CAS_USER, CAS_GRP, SHELL, "-x", cl_iscript(classidx), NULL); } else { n = pkgexecl(listfile, CAS_STDOUT, CAS_USER, CAS_GRP, SHELL, cl_iscript(classidx), NULL); } ckreturn(n, ERR_CASFAIL); } /* * Ensure the mod times on disk match those * in the pkgmap. In this case, call cverify * with checksumming disabled, since the only * action that needs to be done is to verify * that the attributes are correct. */ if ((rfp = regfiles_head) != NULL) { while (rfp != NULL) { ept = &(extlist[rfp->val]->cf_ent); cverify(1, &ept->ftype, ept->path, &ept->cinfo, 0); rfp = rfp->next; } regfiles_free(); } clr_ulimit(); if ((r_updated != (char **)NULL) && (*r_updated == (char *)NULL) && (updated == (char *)NULL)) { updated = "postinstall"; echoDebug(DBG_INSTVOL_OBJ_UPDATED, updated); } } if (listfile) { (void) remove(listfile); } } if (eocflag && (!is_partial_inst() || (is_partial_inst() && strcmp(cl_nam(classidx), "none") != 0))) { if (cl_dvfy(classidx) == QKVERIFY && !repl_permitted) { /* * The quick verify just fixes everything. * If it returns 0, all is well. If it * returns 1, then the class installation * was incomplete and we retry on the * stuff that failed in the conventional * way (without a CAS). this is primarily * to accomodate old archives such as are * found in pre-2.5 WOS; but, it is also * used when a critical dynamic library * is not archived with its class. */ if (!fix_attributes(extlist, classidx)) { /* * Reset the CAS pointer. If the * function returns 0 then there * was no script there in the first * place and we'll just have to * call this a miss. */ if (cl_deliscript(classidx)) /* * Decrement classidx for * next pass. */ classidx--; } } else { /* * Finalize merge. This checks to make sure * file attributes are correct and any links * specified are created. */ (void) endofclass(extlist, classidx, (cl_iscript(classidx) ? 0 : 1), a_cfVfp, a_cfTmpVfp); } } } } /* * Instead of creating links back to the GZ files the logic is * to let zdo recreate the files from the GZ then invoke pkgadd to * install the editable files and skip over any 'f'type files. * The commented out block is to create the links which should be * removed once the current code is tested to be correct. */ /* * Go through extlist creating links for 'f'type files * if we're in a global zone. Note that this code lies * here instead of in the main loop to support CAF packages. * In a CAF package the files are installed by the i.none script * and don't exist until all files are done being processed, thus * the additional loop through extlist. */ /* * output appropriate completion message */ if (is_depend_pkginfo_DB() == B_TRUE) { /* updating database only (hollow package) */ if (a_zoneName == (char *)NULL) { echo(MSG_DBUPD_N_N, part, nparts); } else { echo(MSG_DBUPD_N_N_LZ, part, nparts, a_zoneName); } } else if (tcount == 0) { /* updating package (non-hollow package) */ if (a_zoneName == (char *)NULL) { echo(MSG_INST_N_N, part, nparts); } else { echo(MSG_INST_N_N_LZ, part, nparts, a_zoneName); } } /* * if any package objects were updated (not inherited from the * global zone or otherwise already in existence), set the updated * flag as appropriate */ if (updated != (char *)NULL) { echoDebug(DBG_INSTVOL_OBJ_UPDATED, updated); if (r_updated != (char **)NULL) { *r_updated = updated; } } /* * if any package objects were skipped (verified inherited from the * global zone), set the skipped flag as appropriate */ if (skipped != (char *)NULL) { echoDebug(DBG_INSTVOL_OBJ_SKIPPED, skipped); if (r_skipped != (char **)NULL) { *r_skipped = skipped; } } }
bool ScriptablePluginObject::Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) /* name : method name args : arguments argCount : number of arguments result : return value */ { NPIdentifier test_id = NPN_GetStringIdentifier("test"); if (name == test_id) { printf("temp = %s\n",getTemporaryPath()); printf("home = %s\n",getHomePath()); printf("firefox = %s\n",getFirefoxPath()); printf("conf = %s\n",getConfPath()); printf("classpath = %s\n",getClassPath()); printf("spawn = %s\n",getSpawnPath()); VOID_TO_NPVARIANT(*result); return true; } NPError err; if (!this->HasMethod(name)) return false; VOID_TO_NPVARIANT(*result); //login.jsp test NPIdentifier doSignature_id = NPN_GetStringIdentifier("doSignature"); NPIdentifier getPublicKeyContent_id = NPN_GetStringIdentifier("getPublicKeyContent"); NPObject* sWindowNPObj; if ((err = NPN_GetValue(mNpp, NPNVWindowNPObject, &sWindowNPObj)) != NPERR_NO_ERROR) { printf("Error in getting NPNVWindowNPObject: %d\n",err); return false; } const char *tmpdir = getTemporaryPath(); const char *classpath = getClassPath(); const char *spawnpath = getSpawnPath(); if (name == doSignature_id) { if ((argCount == 2) && (NPVARIANT_IS_STRING(args[0])) && (NPVARIANT_IS_STRING(args[1]))) { char *randomStr = NULL; char *tpmPass = NULL; NPString n_randomStr = NPVARIANT_TO_STRING(args[0]); NPString n_tpmPass = NPVARIANT_TO_STRING(args[1]); m_strFromNP(&randomStr,n_randomStr); m_strFromNP(&tpmPass,n_tpmPass); printf("input = %s, %s",randomStr, tpmPass); char* ret = NULL; char *fname = tempnam(tmpdir,"jni"); if (fname == NULL) fname = "tmp"; char* margs[12]; margs[0] = (char*) spawn_file; margs[1] = "--file"; margs[2] = fname; margs[3] = "--method"; margs[4] = "doSignature"; margs[5] = "--classpath"; margs[6] = (char*) classpath; margs[7] = "--args"; margs[8] = "2"; margs[9] = randomStr; margs[10] = tpmPass; margs[11] = NULL; // in windows use registry to find Firefox directory // in other OS, use path _spawnvp int rval = _spawnv(_P_WAIT,spawnpath,margs); if (rval) { fprintf(stderr,"error = %d\n",rval); } else { ret = getFileContent(fname); if (ret) { STRINGZ_TO_NPVARIANT(ret,*result); } else { fprintf(stderr,"cannot read output file"); } unlink(fname); } free(fname); } else { NPString str; str.UTF8Characters = "alert('usage: doSignature(String, String)');"; str.UTF8Length = strlen(str.UTF8Characters); NPN_Evaluate(this->mNpp, sWindowNPObj, &str, NULL); } } else if (name == getPublicKeyContent_id) { if (argCount == 0) { char *ret = NULL; char *fname = tempnam(tmpdir,"jni"); if (fname == NULL) fname = "tmp"; char* margs[8]; margs[0] = (char*) spawn_file; margs[1] = "--file"; margs[2] = fname; margs[3] = "--method"; margs[4] = "getPublicKeyContent"; margs[5] = "--classpath"; margs[6] = (char*) classpath; margs[7] = NULL; int rval = _spawnv(_P_WAIT,spawnpath,margs); if (rval) { fprintf(stderr,"error = %d\n",rval); } else { ret = getFileContent(fname); if (ret) { STRINGZ_TO_NPVARIANT(ret,*result); } else { fprintf(stderr,"cannot read output file"); } unlink(fname); } free(fname); } else { NPString str; str.UTF8Characters = "alert('usage: getPublicKeyContent()');"; str.UTF8Length = strlen(str.UTF8Characters); NPN_Evaluate(this->mNpp, sWindowNPObj, &str, NULL); } } NPN_ReleaseObject(sWindowNPObj); return true; }
CError CModuleManager::load_from_integra_file( const string &integra_file, guid_set &new_embedded_modules ) { unzFile unzip_file; unz_file_info file_info; char file_name[ CStringHelper::string_buffer_length ]; char *temporary_file_name; FILE *temporary_file; string::size_type implementation_directory_length; unsigned char *copy_buffer; int bytes_read; int total_bytes_read; int bytes_remaining; GUID loaded_module_id; CError CError = CError::SUCCESS; new_embedded_modules.clear(); unzip_file = unzOpen( integra_file.c_str() ); if( !unzip_file ) { INTEGRA_TRACE_ERROR << "Couldn't open zip file: " << integra_file; return CError::FAILED; } implementation_directory_length = CFileIO::implementation_directory_name.length(); if( unzGoToFirstFile( unzip_file ) != UNZ_OK ) { INTEGRA_TRACE_ERROR << "Couldn't iterate contents: " << integra_file; unzClose( unzip_file ); return CError::FAILED; } copy_buffer = new unsigned char[ CFileIO::data_copy_buffer_size ]; do { temporary_file_name = NULL; temporary_file = NULL; if( unzGetCurrentFileInfo( unzip_file, &file_info, file_name, CStringHelper::string_buffer_length, NULL, 0, NULL, 0 ) != UNZ_OK ) { INTEGRA_TRACE_ERROR << "Couldn't extract file info: " << integra_file; continue; } if( strlen( file_name ) <= implementation_directory_length || string( file_name ).substr( 0, implementation_directory_length ) != CFileIO::implementation_directory_name ) { /* skip file not in node directory */ continue; } temporary_file_name = tempnam( m_server.get_scratch_directory().c_str(), "embedded_module" ); if( !temporary_file_name ) { INTEGRA_TRACE_ERROR << "couldn't generate temporary filename"; CError = CError::FAILED; continue; } temporary_file = fopen( temporary_file_name, "wb" ); if( !temporary_file ) { INTEGRA_TRACE_ERROR << "couldn't open temporary file: " << temporary_file_name; CError = CError::FAILED; goto CLEANUP; } if( unzOpenCurrentFile( unzip_file ) != UNZ_OK ) { INTEGRA_TRACE_ERROR << "couldn't open zip contents: " << file_name; CError = CError::FAILED; goto CLEANUP; } total_bytes_read = 0; while( total_bytes_read < file_info.uncompressed_size ) { bytes_remaining = file_info.uncompressed_size - total_bytes_read; assert( bytes_remaining > 0 ); bytes_read = unzReadCurrentFile( unzip_file, copy_buffer, MIN( CFileIO::data_copy_buffer_size, bytes_remaining ) ); if( bytes_read <= 0 ) { INTEGRA_TRACE_ERROR << "Error decompressing file"; CError = CError::FAILED; goto CLEANUP; } fwrite( copy_buffer, 1, bytes_read, temporary_file ); total_bytes_read += bytes_read; } fclose( temporary_file ); temporary_file = NULL; if( load_module( temporary_file_name, CInterfaceDefinition::MODULE_EMBEDDED, loaded_module_id ) ) { new_embedded_modules.insert( loaded_module_id ); store_module( loaded_module_id ); } CLEANUP: if( temporary_file ) { fclose( temporary_file ); } if( temporary_file_name ) { CFileHelper::delete_file( temporary_file_name ); delete[] temporary_file_name; } unzCloseCurrentFile( unzip_file ); } while( unzGoToNextFile( unzip_file ) != UNZ_END_OF_LIST_OF_FILE ); unzClose( unzip_file ); delete[] copy_buffer; return CError; }
void GetTempFileName(const char * lpTempFolderPath, const char * lpFileName, DWORD something, char * szLFName) { strcpy(szLFName, tempnam(lpTempFolderPath, lpFileName)); }
File create_temp_file(char *to, const char *dir, const char *prefix, int mode __attribute__((unused)), myf MyFlags __attribute__((unused))) { File file= -1; DBUG_ENTER("create_temp_file"); #if defined(_MSC_VER) { char temp[FN_REFLEN],*end,*res,**old_env,*temp_env[1]; old_env=environ; if (dir) { end=strend(dir)-1; if (!dir[0]) { /* Change empty string to current dir */ to[0]= FN_CURLIB; to[1]= 0; dir=to; } else if (*end == FN_DEVCHAR) { /* Get current dir for drive */ _fullpath(temp,dir,FN_REFLEN); dir=to; } else if (*end == FN_LIBCHAR && dir < end && end[-1] != FN_DEVCHAR) { strmake(to,dir,(uint) (end-dir)); /* Copy and remove last '\' */ dir=to; } environ=temp_env; /* Force use of dir (dir not checked) */ temp_env[0]=0; } if ((res=tempnam((char*) dir,(char *) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to,0, mode, MyFlags); } environ=old_env; } #elif defined(_ZTC__) if (!dir) dir=getenv("TMPDIR"); if ((res=tempnam((char*) dir,(char *) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to, 0, mode, MyFlags); } #elif defined(HAVE_MKSTEMP) { char prefix_buff[30]; uint pfx_len; File org_file; pfx_len=(strmov(strnmov(prefix_buff, prefix ? prefix : "tmp.", sizeof(prefix_buff)-7),"XXXXXX") - prefix_buff); if (!dir && ! (dir =getenv("TMPDIR"))) dir=P_tmpdir; if (strlen(dir)+ pfx_len > FN_REFLEN-2) { errno=my_errno= ENAMETOOLONG; return 1; } strmov(to,dir); strmov(convert_dirname(to),prefix_buff); org_file=mkstemp(to); file=my_register_filename(org_file, to, FILE_BY_MKSTEMP, EE_CANTCREATEFILE, MyFlags); /* If we didn't manage to register the name, remove the temp file */ if (org_file >= 0 && file < 0) { int tmp=my_errno; (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); my_errno=tmp; } } #elif defined(HAVE_TEMPNAM) { char *res,**old_env,*temp_env[1]; if (dir && !dir[0]) { /* Change empty string to current dir */ to[0]= FN_CURLIB; to[1]= 0; dir=to; } #ifdef OS2 // changing environ variable doesn't work with VACPP char buffer[256]; sprintf( buffer, "TMP=%s", dir); // remove ending backslash if (buffer[strlen(buffer)-1] == '\\') buffer[strlen(buffer)-1] = '\0'; putenv( buffer); #else old_env= (char**) environ; if (dir) { /* Don't use TMPDIR if dir is given */ environ=(const char**) temp_env; temp_env[0]=0; } #endif if ((res=tempnam((char*) dir, (char*) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to,0, (int) (O_RDWR | O_BINARY | O_TRUNC | O_TEMPORARY | O_SHORT_LIVED), MYF(MY_WME)); } else { DBUG_PRINT("error",("Got error: %d from tempnam",errno)); } #ifndef OS2 environ=(const char**) old_env; #endif } #else { register long uniq; register int length; my_string pos,end_pos; /* Make an unique number */ pthread_mutex_lock(&THR_LOCK_open); uniq= ((long) getpid() << 20) + (long) _my_tempnam_used++ ; pthread_mutex_unlock(&THR_LOCK_open); if (!dir && !(dir=getenv("TMPDIR"))) /* Use this if possibly */ dir=P_tmpdir; /* Use system default */ length=strlen(dir)+strlen(pfx)+1; DBUG_PRINT("test",("mallocing %d byte",length+8+sizeof(TMP_EXT)+1)); if (length+8+sizeof(TMP_EXT)+1 > FN_REFLENGTH) errno=my_errno= ENAMETOOLONG; else { end_pos=strmov(to,dir); if (end_pos != to && end_pos[-1] != FN_LIBCHAR) *end_pos++=FN_LIBCHAR; end_pos=strmov(end_pos,pfx); for (length=0 ; length < 8 && uniq ; length++) { *end_pos++= _dig_vec[(int) (uniq & 31)]; uniq >>= 5; } (void) strmov(end_pos,TMP_EXT); file=my_create(to,0, (int) (O_RDWR | O_BINARY | O_TRUNC | O_TEMPORARY | O_SHORT_LIVED), MYF(MY_WME)); } } #endif if (file >= 0) thread_safe_increment(my_tmp_file_created,&THR_LOCK_open); DBUG_RETURN(file); }
Datum cdb_set_oid(PG_FUNCTION_ARGS) { int32 maxoid = PG_GETARG_INT32(0); char *tempFileName = tempnam( NULL, "TMPCP" ); /* elog(NOTICE, "tempFileName = %s", tempFileName ); */ StringInfoData buffer; initStringInfo( &buffer ); appendStringInfo( &buffer, "%u\t0\n\\.\n", maxoid ); FILE *fptr = fopen(tempFileName, "w"); if ( strlen(buffer.data) != fwrite( buffer.data, 1, strlen(buffer.data), fptr) ) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("SPI_execute failed in in temp file write in cdb_set_oid" ))); } fclose(fptr); pfree(buffer.data); buffer.data = NULL; if ( SPI_OK_CONNECT != SPI_connect() ) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("SPI_connect failed in cdb_set_oid" ))); } if ( SPI_OK_UTILITY != SPI_execute( "CREATE TEMPORARY TABLE pgdump_oid (dummy integer) WITH OIDS", false, 0 ) ) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("SPI_execute failed in cdb_set_oid" ))); } initStringInfo( &buffer ); appendStringInfo( &buffer, "COPY pgdump_oid WITH OIDS FROM '%s'", tempFileName ); if ( SPI_OK_UTILITY != SPI_execute( buffer.data, false, 0 ) ) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("SPI_execute failed in copy command in cdb_set_oid" ))); } remove( tempFileName ); pfree(buffer.data); if ( SPI_OK_UTILITY != SPI_execute( "DROP TABLE pgdump_oid", false, 0 ) ) { ereport(ERROR, (errcode(ERRCODE_EXTERNAL_ROUTINE_EXCEPTION), errmsg("SPI_execute failed in cdb_set_oid" ))); } SPI_finish(); PG_RETURN_BOOL(true); }
int action_convert ( const class_t* cls, byte_t* buf, size_t len, const char* fn ) { char * tmpfn = NULL, * tmpdir, * fncpy; FILE* tmpfh; size_t fnlen, wlen; if ( cls->has_hdr ) return 0; fnlen = strlen ( fn ); if ( ! ( fncpy = ( char * ) malloc ( fnlen + 1 ) ) ) abort ( ); memcpy ( fncpy, fn, fnlen + 1 ); printf ( "Patching %s ", fn ); PROGRESS_STEP memmove ( buf + HDR_SIZE, buf, len ); memcpy ( buf, cls->num_dsk == 2 ? header_2d : header_1d, HDR_SIZE ); len += HDR_SIZE; PROGRESS_STEP if ( ! ( tmpdir = dirname ( fncpy ) ) ) PROGRESS_FAIL2( "Failed to get dir name of %s\n", fn ); PROGRESS_STEP if ( ! ( tmpfn = tempnam ( tmpdir, "FP" ) ) ) PROGRESS_FAIL1( "Failed to create temp file name\n" ) PROGRESS_STEP if ( ! ( tmpfh = fopen ( tmpfn, "wb" ) ) ) PROGRESS_FAIL2( "Failed to open temp file %s\n", tmpfn ) PROGRESS_STEP if ( ( wlen = fwrite ( buf, 1, len, tmpfh ) ) != len ) PROGRESS_FAIL2( "Failed to write to temp file %s\n", tmpfn ) PROGRESS_STEP if ( fclose ( tmpfh ) ) PROGRESS_FAIL2( "Failed to close temp file %s\n", tmpfn ); PROGRESS_STEP if ( unlink ( fn ) ) PROGRESS_FAIL2( "Failed to remove original %s\n", fn ); PROGRESS_STEP if ( rename ( tmpfn, fn ) ) PROGRESS_FAIL2( "Failed to copy temp file %s over original\n", tmpfn ); printf ( "OK\n" ); return 0; fail: if ( tmpfn ) unlink ( tmpfn ); return 1; }
BOOL runImpCtrl(void) { BOOL ok; USHORT curCmd = 0; char fileDir[256], *tmpNam; #ifdef HAVE_CRYPT char locSalt[3]; #endif ok = FALSE; if (DoDebug) { sprintf(fileDir, "%s/server/%s", FIFO_DIR, IMP_TEST_PORT); } else if (PlayPort[0] != '\0') { sprintf(fileDir, "%s/server/%s", FIFO_DIR, &PlayPort[0]); } else { sprintf(fileDir, "%s/server/%s", FIFO_DIR, IMPERIUM_PORT); } ImperiumPort = open(fileDir, O_WRONLY | O_NDELAY, 0); if (ImperiumPort >= 0) { ISt = ImpAlloc(); if (ISt != NULL) { tmpNam = tempnam(FIFO_DIR, "ictl"); if (tmpNam == NULL) { puts("Unable to allocate memory for temp name"); } else if (mknod(tmpNam, S_IFIFO|0622, 0) == -1) { printf("Unable to create named pipe %s\n", tmpNam); } #ifdef BROKEN_MKNOD else if (chmod(tmpNam, 0622) != 0) { printf("Unable to change mode for named pipe %s\n", tmpNam); } #endif #ifdef BROKEN_PIPE else if ((myPort = open(tmpNam, O_RDWR | O_NDELAY)) == -1) #else else if ((myPort = open(tmpNam, O_RDONLY | O_NDELAY)) == -1) #endif { (void)unlink(tmpNam); printf("Unable to open named pipe %s\n", tmpNam); } else { strcpy(UsePort, tmpNam); IS = ISt; ISt->is_serverRequest = serverRequest; ISt->is_writeUser = writeUser; ISt->is_readUser = readUser; ISt->is_timedReadUser = timedReadUser; ISt->is_echoOff = echoOff; ISt->is_echoOn = echoOn; ISt->is_gotControlC = gotControlC; ISt->is_sleep = locSleep; ISt->is_log = userLog; ISt->is_extEdit = doExtEdit; LogFd = NULL; ISt->is_request.rq_type = rt_startClient; strcpy(&ISt->is_request.rq_text[0], tmpNam); /* Fill in the correct security code */ #ifdef HAVE_CRYPT sprintf(&locSalt[0], "%2.2x", getpid() % 64); sprintf(&ISt->is_request.rq_private[2], "%-.15s", crypt(IMP_CTRL_CODE, &locSalt[0])); #else /* !HAVE_CRYPT */ strcpy(&ISt->is_request.rq_private[2], IMP_CTRL_CODE); #endif serverRequest(); /* Check to see if we were recognized */ if (ISt->is_request.rq_private[2] == '\0') { /* Nope! */ puts("*** outdated/invalid identity code"); } else { /* Yup! */ if (ServLog) { strcpy(&ISt->is_request.rq_private[2], "Imperium control utility started"); ISt->is_request.rq_type = rt_log; serverRequest(); } /* clear out buffer and set up no outside time limit */ memset(&ISt->is_textIn[0], '\0', INPUT_BUFFER_SIZE * sizeof(char)); /* do the init call */ ISt->is_argShort = 0; ImpCntrl(ISt); while (curCmd < NumCmds) { switch(cmds[curCmd]) { case 'p': ISt->is_argShort = IC_POWER; break; case 'u': ISt->is_argShort = IC_UPDATE; break; case 'm': ISt->is_argShort = IC_MINER; break; case 'l': ISt->is_argShort = IC_INCUSR; break; case 'L': ISt->is_argShort = IC_DECUSR; break; case 'f': ISt->is_argShort = IC_DOFLUSH; break; case 's': ISt->is_argShort = IC_PUBLISH; break; case '\x50': /* Get around metaconfig problem */ default: ISt->is_argShort = IC_FPOWER; break; } ISt->is_argBool = ServLog; ImpCntrl(ISt); curCmd++; } if (LogFd != NULL) { logFlush(); fclose(LogFd); } if (ServLog) { strcpy(&ISt->is_request.rq_private[2], "Imperium control utility terminated"); ISt->is_request.rq_type = rt_log; serverRequest(); } ISt->is_request.rq_type = rt_stopClient; serverRequest(); } ImpFree(ISt); ok = TRUE; close(myPort); (void)unlink(tmpNam); } if (tmpNam != NULL) { free(tmpNam); } }
int main(int argc, char** argv) { int worker_limit, browser_limit; srand(98769876); pthread_t workers[8]; char *mutex_name = tempnam(0,"worker1."); mutex_sem = sem_open(mutex_name+4,O_CREAT,0777,1); if(!mutex_sem) { perror("No mutex!\n"); exit(1); } /* TEST 1: several short-duration workers, one browser */ init(); for(int i=0;i<8;i++) { randomize(); worker_limit = 120; pthread_create(&workers[i],0,worker_thread,(void*)&worker_limit); } pthread_t browsers[100]; browser_limit = 960; pthread_create(&browsers[0],0,browser_thread,(void*)&browser_limit); void *result; pthread_join(browsers[0],&result); for(int i=0;i<8;i++) pthread_join(workers[i],&result); if(pairs==960) printf("[PASS] worker1: short-duration workers, one browser.\n"); else printf("[FAIL] worker1: insufficient pairs %d != 960\n",pairs); worker_count=0; browser_count=0; pairs = 0; /* TEST 2: several medium-duration workers, several browsers */ init(); for(int i=0;i<8;i++) { randomize(); worker_limit = 2000; pthread_create(&workers[i],0,worker_thread,(void*)&worker_limit); } browser_limit = 800; for(int i=0;i<20;i++) pthread_create(&browsers[i],0,browser_thread,(void*)&browser_limit); for(int i=0;i<20;i++) pthread_join(browsers[i],&result); for(int i=0;i<8;i++) pthread_join(workers[i],&result); if(pairs==16000) printf("[PASS] worker1: medium-duration workers, 20 browsers.\n"); else printf("[FAIL] warker1: insufficient pairs, %d != 16000\n",pairs); worker_count=0; browser_count=0; pairs = 0; /* TEST 3: one worker, several browsers */ init(); for(int i=0;i<1;i++) { randomize(); worker_limit = 2000; pthread_create(&workers[i],0,worker_thread,(void*)&worker_limit); } browser_limit = 100; for(int i=0;i<20;i++) pthread_create(&browsers[i],0,browser_thread,(void*)&browser_limit); for(int i=0;i<20;i++) pthread_join(browsers[i],&result); for(int i=0;i<1;i++) pthread_join(workers[i],&result); if(pairs==2000) printf("[PASS] worker1: 1 worker, 20 browsers.\n"); else printf("[FAIL] warker1: insufficient pairs, %d != 2000\n",pairs); }
int getremote(char *filename, peer_t *peer, char *range, CURL *curlhandle) { #ifdef TIMEIT struct timeval start_time, end_time; unsigned long long s, e; #endif CURLcode curlcode; struct in_addr in; struct stat buf; FILE *file; useconds_t stall; char *tempfilename; char *dirfile, *basefile; char url[PATH_MAX]; char *dir; char *ptr; #ifdef TIMEIT gettimeofday(&start_time, NULL); #endif in.s_addr = peer->ip; #ifdef DEBUG logmsg("getremote: get file (%s) from (%s)\n", filename, inet_ntoa(in)); #endif status = HTTP_OK; /* * we know the file is not on the local hard disk (because getlocal() * is called before this function), so try to download the file * from a peer */ /* * first, let's see if the file systems have been formatted. if * so, then copy over all the files that were downloaded in the * first part of the installation (e.g., stage2.img, product.img) * and set up a symbolic link from the ramdisk area to the disk. */ if (stat("/mnt/sysimage", &buf) == 0) { if (stat("/mnt/sysimage/install", &buf) != 0) { if (stat("/install", &buf) == 0) { system("/usr/bin/cp -R /install /mnt/sysimage"); system("/usr/bin/rm -rf /install"); } else { mkdir("/mnt/sysimage/install", 0755); } symlink("/mnt/sysimage/install", "/install"); } } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time1: %lld usec\n", (e - s)); #endif /* * make sure the destination directory exists */ if ((dir = strdup(filename)) != NULL) { if ((ptr = rindex(dir, '/')) != NULL) { *ptr = '\0'; if (stat(dir, &buf) != 0) { createdir(dir); } } free(dir); } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time2: %lld usec\n", (e - s)); #endif if ((dirfile = strdup(filename)) == NULL) { logmsg("getremote:strdup failed:errno (%d)\n", errno); return(-1); } if ((basefile = strdup(filename)) == NULL) { logmsg("getremote:strdup failed:errno (%d)\n", errno); return(-1); } if ((tempfilename = tempnam(dirname(dirfile), basename(basefile))) == NULL) { free(dirfile); free(basefile); logmsg("getremote:tempnam():failed\n"); return(-1); } free(dirfile); free(basefile); /* * make a 'http://' url and get the file. */ if ((file = fopen(tempfilename, "w")) == NULL) { logmsg("getremote:fopen():failed\n"); free(tempfilename); return(-1); } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time3: %lld usec\n", (e - s)); #endif /* * tell curl to save it to disk (save it to the file pointed * to by 'file' */ if ((curlcode = curl_easy_setopt(curlhandle, CURLOPT_WRITEDATA, file)) != CURLE_OK) { logmsg("getremote:curl_easy_setopt():failed:(%d)\n", curlcode); free(tempfilename); return(-1); } if (makeurl("http://", filename, inet_ntoa(in), url, sizeof(url)) != 0){ logmsg("getremote:makeurl():failed:(%d)", errno); free(tempfilename); return(-1); } if (fromip != NULL) { free(fromip); } fromip = strdup(inet_ntoa(in)); /* * let's check if this is an rpm file or something else */ int skip = (int)strlen(filename); char * suffix = filename + skip - 4 ; if ( strcmp(suffix, ".rpm") != 0 ){ //this is not an rpm we should calculate the md5sum isRpm = 0; #ifdef DEBUG logmsg("getremote:file %s is not an rpm doing md5sum\n", filename); #endif } else{ isRpm = 1; #ifdef DEBUG logmsg("getremote:file %s is an rpm\n", filename); #endif } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time4: %lld usec\n", (e - s)); #endif stall = 10000; while (stall < 1000000) { if (downloadfile(curlhandle, url, tempfilename, file, filename) < 0) { status = HTTP_NOT_FOUND; } #ifdef DEBUG logmsg("getremote:download status %d : stall %d\n", status, stall); #endif if ((status >= HTTP_OK) && (status <= HTTP_MULTI_STATUS)) { /* * success. break out of loop */ break; } else { logmsg("getremote:downloadfile:failed:url %s\n", url); if (peer->state == DOWNLOADING) { stall *= 10; usleep(stall); } else { /* * don't return on failure here. we still need * to do some cleanup */ status = HTTP_NOT_FOUND; break; } } } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time5: %lld usec\n", (e - s)); #endif /* * we downloaded the file from a peer, so read it and output it * to stdout */ if ((status >= HTTP_OK) && (status <= HTTP_MULTI_STATUS)) { /* * now do an atomic move */ if (rename(tempfilename, filename) < 0) { logmsg("getremote:rename():failed:(%d)\n", errno); free(tempfilename); return(-1); } if (outputfile(filename, range) != 0) { logmsg("getremote:outputfile():failed:(%d)\n", errno); free(tempfilename); return(-1); } } else { /* * on a failure, a zero-byte length file will be * left on the disk -- this is because of the fopen(). * remove this zero-length file. */ unlink(filename); unlink(tempfilename); free(tempfilename); return(-1); } #ifdef TIMEIT gettimeofday(&end_time, NULL); s = (start_time.tv_sec * 1000000) + start_time.tv_usec; e = (end_time.tv_sec * 1000000) + end_time.tv_usec; logmsg("getremote:svc time6: %lld usec\n", (e - s)); #endif free(tempfilename); return(0); }
static int impl_dummy_server(void) { int dummy_server = -1; /* Create our dummy sock. */ struct sockaddr_un dummy_addr; char *socket_path = tempnam("/tmp", ".huptime"); memset(&dummy_addr, 0, sizeof(struct sockaddr_un)); dummy_addr.sun_family = AF_UNIX; strncpy(dummy_addr.sun_path, socket_path, sizeof(dummy_addr.sun_path)-1); /* Create a dummy server. */ dummy_server = socket(AF_UNIX, SOCK_STREAM, 0); if( dummy_server < 0 ) { fprintf(stderr, "Unable to create unix socket?"); return -1; } if( fcntl(dummy_server, F_SETFD, FD_CLOEXEC) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to set cloexec?"); return -1; } if( libc.bind( dummy_server, (struct sockaddr*)&dummy_addr, sizeof(struct sockaddr_un)) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to bind unix socket?"); return -1; } if( libc.listen(dummy_server, 1) < 0 ) { close(dummy_server); fprintf(stderr, "Unable to listen on unix socket?"); return -1; } /* Connect a dummy client. */ int dummy_client = socket(AF_UNIX, SOCK_STREAM, 0); if( dummy_client < 0 ) { close(dummy_server); fprintf(stderr, "Unable to create unix socket?"); return -1; } if( fcntl(dummy_client, F_SETFD, FD_CLOEXEC) < 0 ) { close(dummy_server); close(dummy_client); fprintf(stderr, "Unable to set cloexec?"); return -1; } if( connect( dummy_client, (struct sockaddr*)&dummy_addr, sizeof(struct sockaddr_un)) < 0 ) { close(dummy_server); close(dummy_client); fprintf(stderr, "Unable to connect dummy client?"); return -1; } /* Put the client into an error state. */ int dummy_fd = libc.accept(dummy_server, NULL, 0); if( dummy_fd < 0 ) { fprintf(stderr, "Unable to accept internal client?"); close(dummy_server); close(dummy_client); return -1; } close(dummy_fd); /* Save the dummy info. */ fdinfo_t* dummy_info = alloc_info(DUMMY); if( dummy_info == NULL ) { fprintf(stderr, "Unable to allocate dummy info?"); return -1; } dummy_info->dummy.client = dummy_client; fd_save(dummy_server, dummy_info); inc_ref(dummy_info); fd_save(dummy_client, dummy_info); /* Ensure that it's unlinked. */ unlink(socket_path); free(socket_path); return dummy_server; }
int main() { printf("%s\n", tempnam("/var/tmp", "zorro")); printf("%s\n", tmpnam(NULL)); }
int main(int argc, char *argv[]) { struct sparse_matrix_t *sparseA = NULL; struct vector_t *b = NULL; struct vector_t *x; struct mesh_t *mesh; char *xml_output; long int *compress2fat = NULL; struct vector_t *solution; struct vector_t *std_error_sol; long int fat_sol_nb_col; lsqr_input *input; lsqr_output *output; lsqr_work *work; /* zone temoraire de travail */ lsqr_func *func; /* func->mat_vec_prod -> APROD */ /* cmd line arg */ char *mesh_filename = NULL; char *importfilename = NULL; char *output_filename = NULL; char *sol_error_filename = NULL; char *log_filename = NULL; char *output_type = NULL; int max_iter; double damping, grad_damping; int use_ach = 0; /* ACH : tele-seismic inversion tomography */ int check_sparse = 0; /* check sparse matrix disable by default */ /* velocity model */ char *vmodel = NULL; struct velocity_model_t *vm = NULL; struct mesh_t **imported_mesh = NULL; char **xmlfilelist = NULL; int nb_xmlfile = 0; int i, j; int nb_irm = 0; struct irm_t **irm = NULL; int *nb_metacell = NULL; FILE *logfd; /*************************************************************/ parse_command_line(argc, argv, &mesh_filename, &vmodel, &importfilename, &log_filename, &output_filename, &output_type, &max_iter, &damping, &grad_damping, &use_ach, &check_sparse); if (use_ach) { fprintf(stderr, "Using ACH tomographic inversion\n"); } else { fprintf(stderr, "Using STANDARD tomographic inversion\n"); } /* load the velocity model */ if (vmodel) { char *myfile; vm = load_velocity_model(vmodel); if (!vm) { fprintf(stderr, "Can not initialize velocity model '%s'\n", vmodel); exit(1); } myfile = strdup(vmodel); fprintf(stderr, "Velocity model '%s' loaded\n", basename(myfile)); free(myfile); } else { vm = NULL; } /* Open log file */ if (!log_filename) { logfd = stdout; } else { if (!(logfd = fopen(log_filename, "w"))) { perror(log_filename); exit(1); } } /*check_write_access (output_filename); */ /**************************************/ /* test if we can open file to import */ /**************************************/ if (importfilename) { xmlfilelist = parse_separated_list(importfilename, ","); nb_xmlfile = 0; while (xmlfilelist[nb_xmlfile]) { if (access(xmlfilelist[nb_xmlfile], R_OK) == -1) { perror(xmlfilelist[nb_xmlfile]); exit(1); } nb_xmlfile++; } } else { fprintf(stderr, "No file to import ... exiting\n"); exit(0); } /****************************/ /* main mesh initialization */ /****************************/ mesh = mesh_init_from_file(mesh_filename); if (!mesh) { fprintf(stderr, "Error decoding %s.\n", mesh_filename); exit(1); } fprintf(stderr, "read %s ok\n", mesh_filename); /*****************************************/ /* check and initialize slice xml files */ /*****************************************/ if (nb_xmlfile) { int nb_sparse = 0; int nb_res = 0; int f; imported_mesh = (struct mesh_t **) malloc(sizeof(struct mesh_t *) * nb_xmlfile); assert(imported_mesh); for (i = 0; i < nb_xmlfile; i++) { imported_mesh[i] = mesh_init_from_file(xmlfilelist[i]); if (!imported_mesh[i]) { fprintf(stderr, "Error decoding %s.\n", mesh_filename); exit(1); } for (f = 0; f < NB_MESH_FILE_FORMAT; f++) { /* mandatory field : res, sparse, and irm if provided */ if (f == RES || f == SPARSE || f == IRM) { check_files_access(f, imported_mesh[i]->data[f], xmlfilelist[i]); } } if (imported_mesh[i]->data[SPARSE]) { nb_sparse += imported_mesh[i]->data[SPARSE]->ndatafile; } if (imported_mesh[i]->data[RES]) { nb_res += imported_mesh[i]->data[RES]->ndatafile; } if (imported_mesh[i]->data[IRM]) { nb_irm += imported_mesh[i]->data[IRM]->ndatafile; } } if (!nb_sparse || !nb_res) { fprintf(stderr, "Error no sparse or res file available !\n"); exit(0); } } /*********************************************/ /* read and import the sparse(s) matrix(ces) */ /*********************************************/ for (i = 0; i < nb_xmlfile; i++) { if (!imported_mesh[i]->data[SPARSE]) { continue; } for (j = 0; j < imported_mesh[i]->data[SPARSE]->ndatafile; j++) { sparseA = import_sparse_matrix(sparseA, imported_mesh[i]->data[SPARSE]-> filename[j]); } } if (check_sparse) { if (check_sparse_matrix(sparseA)) { exit(1); } } /*sparse_compute_length(sparseA, "length1.txt"); */ fat_sol_nb_col = sparseA->nb_col; show_sparse_stats(sparseA); /*********************************************/ /* read and import the residual time vector */ /*********************************************/ for (i = 0; i < nb_xmlfile; i++) { if (!imported_mesh[i]->data[RES]) { continue; } for (j = 0; j < imported_mesh[i]->data[RES]->ndatafile; j++) { b = import_vector(b, imported_mesh[i]->data[RES]->filename[j]); } } /*************************************************/ /* check compatibility between matrix and vector */ /*************************************************/ if (sparseA->nb_line != b->length) { fprintf(stderr, "Error, check your matrix/vector sizes (%ld/%ld)\n", sparseA->nb_line, b->length); exit(1); } /********************/ /* show memory used */ /********************/ #ifdef __APPLE__ { struct mstats memusage; memusage = mstats(); fprintf(stderr, "Memory used: %.2f MBytes\n", (float) (memusage.bytes_used) / (1024. * 1024)); } #else { struct mallinfo m_info; m_info = mallinfo(); fprintf(stderr, "Memory used: %.2f MBytes\n", (float) (m_info.uordblks + m_info.usmblks) / (1024. * 1024.)); } #endif /**************************************/ /* relative traveltime mode */ /**************************************/ if (use_ach) { int nb_evt_imported = 0; for (i = 0; i < nb_xmlfile; i++) { if (!imported_mesh[i]->data[EVT]) { continue; } for (j = 0; j < imported_mesh[i]->data[EVT]->ndatafile; j++) { relative_tt(sparseA, b, imported_mesh[i]->data[EVT]->filename[j]); nb_evt_imported++; } } if (!nb_evt_imported) { fprintf(stderr, "Error in ACH mode, can not import any .evt file !\n"); exit(1); } } /************************************************/ /* read the irregular mesh definition if needed */ /* one by layer */ /************************************************/ if (nb_irm) { int cpt = 0; struct mesh_offset_t **offset; int l; irm = (struct irm_t **) malloc(nb_irm * sizeof(struct irm_t *)); assert(irm); nb_metacell = (int *) calloc(nb_irm, sizeof(int)); assert(nb_metacell); make_mesh(mesh); for (i = 0; i < nb_xmlfile; i++) { if (!imported_mesh[i]->data[IRM]) { continue; } /* offset between meshes */ offset = compute_mesh_offset(mesh, imported_mesh[i]); for (l = 0; l < mesh->nlayers; l++) { if (!offset[l]) continue; fprintf(stderr, "\t%s, [%s] offset[layer=%d] : lat=%d lon=%d z=%d\n", xmlfilelist[i], MESH_FILE_FORMAT[IRM], l, offset[l]->lat, offset[l]->lon, offset[l]->z); } for (j = 0; j < imported_mesh[i]->data[IRM]->ndatafile; j++) { /* FIXME: read only once the irm file */ irm[cpt] = read_irm(imported_mesh[i]->data[IRM]->filename[j], &(nb_metacell[cpt])); import2mesh_irm_file(mesh, imported_mesh[i]->data[IRM]-> filename[j], offset); cpt++; } for (l = 0; l < mesh->nlayers; l++) { if (offset[l]) free(offset[l]); } free(offset); } metacell_find_neighbourhood(mesh); } /*sparse_compute_length(sparseA, "length1.txt"); */ fat_sol_nb_col = sparseA->nb_col; show_sparse_stats(sparseA); /***********************/ /* remove empty column */ /***********************/ fprintf(stderr, "starting compression ...\n"); sparse_compress_column(mesh, sparseA, &compress2fat); if (check_sparse) { if (check_sparse_matrix(sparseA)) { exit(1); } } show_sparse_stats(sparseA); /***************************************/ /* add gradient damping regularisation */ /***************************************/ if (fabs(grad_damping) > 1.e-6) { int nb_faces = 6; /* 1 cell may have 6 neighbours */ long int nb_lines = 0; char *regul_name; fprintf(stdout, "using gradient damping : %f\n", grad_damping); /* tmp file name */ regul_name = tempnam("/tmp", "regul"); if (!regul_name) { perror("lsqrsolve: "); exit(1); } if (nb_irm) { create_regul_DtD_irm(sparseA, compress2fat, mesh, regul_name, nb_faces, grad_damping, &nb_lines); } else { create_regul_DtD(sparseA, compress2fat, mesh, regul_name, nb_faces, grad_damping, &nb_lines); } sparse_matrix_resize(sparseA, sparseA->nb_line + sparseA->nb_col, sparseA->nb_col); sparseA = import_sparse_matrix(sparseA, regul_name); if (check_sparse) { if (check_sparse_matrix(sparseA)) { exit(1); } } vector_resize(b, sparseA->nb_line); unlink(regul_name); show_sparse_stats(sparseA); } /*********************************/ /* the real mesh is no more used */ /* keep only the light mesh */ /*********************************/ fprintf(stdout, "Time to free the real mesh and keep only the light structure\n"); free_mesh(mesh); mesh = mesh_init_from_file(mesh_filename); if (!mesh) { fprintf(stderr, "Error decoding %s.\n", mesh_filename); exit(1); } fprintf(stderr, "read %s ok\n", mesh_filename); /********************************/ /* init vector solution to zero */ /********************************/ x = new_vector(sparseA->nb_col); /*************************************************************/ /* solve A.x = B */ /* A = ray length in the cells */ /* B = residual travel time observed - computed */ /* x solution to satisfy the lsqr problem */ /*************************************************************/ /* LSQR alloc */ alloc_lsqr_mem(&input, &output, &work, &func, sparseA->nb_line, sparseA->nb_col); fprintf(stderr, "alloc_lsqr_mem : ok\n"); /* defines the routine Mat.Vect to use */ func->mat_vec_prod = sparseMATRIXxVECTOR; /* Set the input parameters for LSQR */ input->num_rows = sparseA->nb_line; input->num_cols = sparseA->nb_col; input->rel_mat_err = 1.0e-3; /* in km */ input->rel_rhs_err = 1.0e-2; /* in seconde */ /*input->rel_mat_err = 0.; input->rel_rhs_err = 0.; */ input->cond_lim = .0; input->lsqr_fp_out = logfd; /* input->rhs_vec = (dvec *) b; */ dvec_copy((dvec *) b, input->rhs_vec); input->sol_vec = (dvec *) x; /* initial guess */ input->damp_val = damping; if (max_iter == -1) { input->max_iter = 4 * (sparseA->nb_col); } else { input->max_iter = max_iter; } /* catch Ctrl-C signal */ signal(SIGINT, emergency_halt); /******************************/ /* resolution du systeme Ax=b */ /******************************/ lsqr(input, output, work, func, sparseA); fprintf(stderr, "*** lsqr ended (%ld iter) : %s\n", output->num_iters, lsqr_msg[output->term_flag]); if (output->term_flag == 0) { /* solution x=x0 */ exit(0); } /* uncompress the solution */ solution = uncompress_column((struct vector_t *) output->sol_vec, compress2fat, fat_sol_nb_col); /* uncompress the standard error on solution */ std_error_sol = uncompress_column((struct vector_t *) output->std_err_vec, compress2fat, fat_sol_nb_col); /* if irm file was provided, set the right value to each cell * from a given metacell */ if (irm) { irm_update(solution, irm, nb_metacell, nb_irm, mesh); free_irm(irm, nb_irm); free(nb_metacell); } /* write solution */ if (strchr(output_type, 'm')) { export2matlab(solution, output_filename, mesh, vm, output->num_iters, input->damp_val, grad_damping, use_ach); } if (strchr(output_type, 's')) { export2sco(solution, output_filename, mesh, vm, output->num_iters, input->damp_val, grad_damping, use_ach); } if (strchr(output_type, 'g')) { /* solution */ export2gmt(solution, output_filename, mesh, vm, output->num_iters, input->damp_val, grad_damping, use_ach); /* error on solution */ sol_error_filename = (char *) malloc(sizeof(char) * (strlen(output_filename) + strlen(".err") + 1)); sprintf(sol_error_filename, "%s.err", output_filename); export2gmt(std_error_sol, sol_error_filename, mesh, vm, output->num_iters, input->damp_val, grad_damping, use_ach); free(sol_error_filename); } /* save the xml enrichied with sections */ xml_output = (char *) malloc((strlen(output_filename) + strlen(".xml") + 1) * sizeof(char)); assert(xml_output); sprintf(xml_output, "%s.xml", output_filename); mesh2xml(mesh, xml_output); free(xml_output); /******************************************************/ /* variance reduction, ie how the model fits the data */ /* X = the final solution */ /* */ /* ||b-AX||² */ /* VR= 1 - -------- */ /* ||b||² */ /* */ /******************************************************/ { double norm_b; double norm_b_AX; double VR; /* variance reduction */ struct vector_t *rhs; /* right hand side */ rhs = new_vector(sparseA->nb_line); /* use copy */ dvec_copy((dvec *) b, (dvec *) rhs); norm_b = dvec_norm2((dvec *) rhs); /* does rhs = rhs + sparseA . output->sol_vec */ /* here rhs is overwritten */ dvec_scale((-1.0), (dvec *) rhs); sparseMATRIXxVECTOR(0, output->sol_vec, (dvec *) rhs, sparseA); dvec_scale((-1.0), (dvec *) rhs); norm_b_AX = dvec_norm2((dvec *) rhs); VR = 1 - (norm_b_AX * norm_b_AX) / (norm_b * norm_b); fprintf(stdout, "Variance reduction = %.2f%%\n", VR * 100); free_vector(rhs); } /********/ /* free */ /********/ if (vm) { free_velocity_model(vm); } free_mesh(mesh); free_sparse_matrix(sparseA); free_lsqr_mem(input, output, work, func); free_vector(solution); free_vector(std_error_sol); free(compress2fat); for (i = 0; i < nb_xmlfile; i++) { free(xmlfilelist[i]); free_mesh(imported_mesh[i]); } free(xmlfilelist); free(imported_mesh); return (0); }
int main(int argc, char **argv) { char *name; char currev[64], lastrev[64], run[256], *rev; unsigned long urev; FILE *stream = NULL; int gotrev = 0, needupdate = 1; // [BB] Are we working with a SVN checkout? int svnCheckout = 0; char hgdateString[64]; time_t hgdate = 0; char hgHash[13]; hgHash[0] = '\0'; if (argc != 3) { fprintf (stderr, "Usage: %s <repository directory> <path to svnrevision.h>\n", argv[0]); return 1; } // [BB] Try to figure out whether this is a SVN or a Hg checkout. { struct stat st; char filename[1024]; sprintf ( filename, "%s/.svn/entries", argv[1] ); if ( stat ( filename, &st ) == 0 ) svnCheckout = 1; // [BB] If stat failed we have to manually clear errno, otherwise the code below doesn't work. else errno = 0; } // Use svnversion to get the revision number. If that fails, pretend it's // revision 0. Note that this requires you have the command-line svn tools installed. // [BB] Depending on whether this is a SVN or Hg checkout we have to use the appropriate tool. if ( svnCheckout ) sprintf (run, "svnversion -cn %s", argv[1]); else sprintf (run, "hg identify -n"); if ((name = tempnam(NULL, "svnout")) != NULL) { #ifdef __APPLE__ // tempnam will return errno of 2 even though it is successful for our purposes. errno = 0; #endif if((stream = freopen(name, "w+b", stdout)) != NULL && system(run) == 0 && #ifndef __FreeBSD__ errno == 0 && #endif fseek(stream, 0, SEEK_SET) == 0 && fgets(currev, sizeof currev, stream) == currev && (isdigit(currev[0]) || (currev[0] == '-' && currev[1] == '1'))) { gotrev = 1; // [BB] Find the date the revision of the working copy was created. if ( ( svnCheckout == 0 ) && ( system("hg log -r. --template \"{date|hgdate} {node|short}\"") == 0 ) && ( fseek(stream, strlen(currev), SEEK_SET) == 0 ) && ( fgets(hgdateString, sizeof ( hgdateString ), stream) == hgdateString ) ) { // [BB] Find the hash in the output and store it. char *p = strrchr ( hgdateString, ' ' ); strncpy ( hgHash, p ? ( p+1 ) : "hashnotfound" , sizeof( hgHash ) - 1 ); hgHash[ sizeof ( hgHash ) - 1 ] = '\0'; // [BB] Extract the date from the output and store it. hgdate = atoi ( hgdateString ); } } } if (stream != NULL) { fclose (stream); remove (name); } if (name != NULL) { free (name); } if (!gotrev) { fprintf (stderr, "Failed to get current revision: %s\n", strerror(errno)); strcpy (currev, "0"); rev = currev; } else { rev = strchr (currev, ':'); if (rev == NULL) { rev = currev; } else { rev += 1; } } // [BB] Create date version string. if ( gotrev && ( svnCheckout == 0 ) ) { char *endptr; unsigned long parsedRev = strtoul(rev, &endptr, 10); unsigned int localChanges = ( *endptr == '+' ); struct tm *lt = gmtime( &hgdate ); if ( localChanges ) sprintf ( rev, "%d%02d%02d-%02d%02dM", lt->tm_year - 100, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min); else sprintf ( rev, "%d%02d%02d-%02d%02d", lt->tm_year - 100, lt->tm_mon + 1, lt->tm_mday, lt->tm_hour, lt->tm_min); } stream = fopen (argv[2], "r"); if (stream != NULL) { if (!gotrev) { // If we didn't get a revision but the file does exist, leave it alone. fprintf( stderr, "No revision found.\n" ); fclose (stream); return 0; } // Read the revision that's in this file already. If it's the same as // what we've got, then we don't need to modify it and can avoid rebuilding // dependant files. if (fgets(lastrev, sizeof lastrev, stream) == lastrev) { if (lastrev[0] != '\0') { // Strip trailing \n lastrev[strlen(lastrev) - 1] = '\0'; } if (strcmp(rev, lastrev + 3) == 0) { needupdate = 0; } } fclose (stream); } if (needupdate) { stream = fopen (argv[2], "w"); if (stream == NULL) { return 1; } // [BB] Use hgdate as revision number. if ( hgdate ) urev = hgdate; else urev = strtoul(rev, NULL, 10); fprintf (stream, "// %s\n" "//\n" "// This file was automatically generated by the\n" "// updaterevision tool. Do not edit by hand.\n" "\n" "#define SVN_REVISION_STRING \"%s\"\n" "#define SVN_REVISION_NUMBER %lu\n", rev, rev, urev); // [BB] Also save the hg hash. if ( svnCheckout == 0 ) fprintf (stream, "#define HG_REVISION_HASH_STRING \"%s\"\n", hgHash); fclose (stream); fprintf (stderr, "%s updated to revision %s.\n", argv[2], rev); } else { fprintf (stderr, "%s is up to date at revision %s.\n", argv[2], rev); } return 0; }
File create_temp_file(char *to, const char *dir, const char *prefix, int mode __attribute__((unused)), myf MyFlags __attribute__((unused))) { File file= -1; #ifdef __WIN__ TCHAR path_buf[MAX_PATH-14]; #endif DBUG_ENTER("create_temp_file"); DBUG_PRINT("enter", ("dir: %s, prefix: %s", dir, prefix)); #if defined (__WIN__) /* Use GetTempPath to determine path for temporary files. This is because the documentation for GetTempFileName has the following to say about this parameter: "If this parameter is NULL, the function fails." */ if (!dir) { if(GetTempPath(sizeof(path_buf), path_buf) > 0) dir = path_buf; } /* Use GetTempFileName to generate a unique filename, create the file and release it's handle - uses up to the first three letters from prefix */ if (GetTempFileName(dir, prefix, 0, to) == 0) DBUG_RETURN(-1); DBUG_PRINT("info", ("name: %s", to)); /* Open the file without the "open only if file doesn't already exist" since the file has already been created by GetTempFileName */ if ((file= my_open(to, (mode & ~O_EXCL), MyFlags)) < 0) { /* Open failed, remove the file created by GetTempFileName */ int tmp= my_errno; (void) my_delete(to, MYF(0)); my_errno= tmp; } #elif defined(HAVE_MKSTEMP) { char prefix_buff[30]; uint pfx_len; File org_file; pfx_len= (uint) (strmov(strnmov(prefix_buff, prefix ? prefix : "tmp.", sizeof(prefix_buff)-7),"XXXXXX") - prefix_buff); if (!dir && ! (dir =getenv("TMPDIR"))) dir=P_tmpdir; if (strlen(dir)+ pfx_len > FN_REFLEN-2) { errno=my_errno= ENAMETOOLONG; DBUG_RETURN(file); } strmov(convert_dirname(to,dir,NullS),prefix_buff); org_file=mkstemp(to); if (mode & O_TEMPORARY) (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); file=my_register_filename(org_file, to, FILE_BY_MKSTEMP, EE_CANTCREATEFILE, MyFlags); /* If we didn't manage to register the name, remove the temp file */ if (org_file >= 0 && file < 0) { int tmp=my_errno; close(org_file); (void) my_delete(to, MYF(MY_WME | ME_NOINPUT)); my_errno=tmp; } } #elif defined(HAVE_TEMPNAM) { extern char **environ; char *res,**old_env,*temp_env[1]; if (dir && !dir[0]) { /* Change empty string to current dir */ to[0]= FN_CURLIB; to[1]= 0; dir=to; } old_env= (char**) environ; if (dir) { /* Don't use TMPDIR if dir is given */ environ=(const char**) temp_env; temp_env[0]=0; } if ((res=tempnam((char*) dir, (char*) prefix))) { strmake(to,res,FN_REFLEN-1); (*free)(res); file=my_create(to,0, (int) (O_RDWR | O_BINARY | O_TRUNC | O_EXCL | O_NOFOLLOW | O_TEMPORARY | O_SHORT_LIVED), MYF(MY_WME)); } else { DBUG_PRINT("error",("Got error: %d from tempnam",errno)); } environ=(const char**) old_env; } #else #error No implementation found for create_temp_file #endif if (file >= 0) thread_safe_increment(my_tmp_file_created,&THR_LOCK_open); DBUG_RETURN(file); }