MagickExport int AcquireUniqueFileResource(char *path) { #if !defined(O_NOFOLLOW) #define O_NOFOLLOW 0 #endif #if !defined(TMP_MAX) # define TMP_MAX 238328 #endif int c, file; register char *p; register ssize_t i; static const char portable_filename[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"; StringInfo *key; unsigned char *datum; assert(path != (char *) NULL); (void) LogMagickEvent(ResourceEvent,GetMagickModule(),"..."); if (random_info == (RandomInfo *) NULL) { LockSemaphoreInfo(resource_semaphore); if (random_info == (RandomInfo *) NULL) random_info=AcquireRandomInfo(); UnlockSemaphoreInfo(resource_semaphore); } file=(-1); for (i=0; i < (ssize_t) TMP_MAX; i++) { /* Get temporary pathname. */ (void) GetPathTemplate(path); key=GetRandomKey(random_info,6); p=path+strlen(path)-12; datum=GetStringInfoDatum(key); for (i=0; i < (ssize_t) GetStringInfoLength(key); i++) { c=(int) (datum[i] & 0x3f); *p++=portable_filename[c]; } key=DestroyStringInfo(key); #if defined(MAGICKCORE_HAVE_MKSTEMP) file=mkstemp(path); if (file != -1) { #if defined(MAGICKCORE_HAVE_FCHMOD) (void) fchmod(file,0600); #endif #if defined(__OS2__) setmode(file,O_BINARY); #endif break; } #endif key=GetRandomKey(random_info,12); p=path+strlen(path)-12; datum=GetStringInfoDatum(key); for (i=0; i < (ssize_t) GetStringInfoLength(key); i++) { c=(int) (datum[i] & 0x3f); *p++=portable_filename[c]; } key=DestroyStringInfo(key); file=open_utf8(path,O_RDWR | O_CREAT | O_EXCL | O_BINARY | O_NOFOLLOW, S_MODE); if ((file >= 0) || (errno != EEXIST)) break; } (void) LogMagickEvent(ResourceEvent,GetMagickModule(),"%s",path); if (file == -1) return(file); if (resource_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&resource_semaphore); LockSemaphoreInfo(resource_semaphore); if (temporary_resources == (SplayTreeInfo *) NULL) temporary_resources=NewSplayTree(CompareSplayTreeString, DestroyTemporaryResources,(void *(*)(void *)) NULL); UnlockSemaphoreInfo(resource_semaphore); (void) AddValueToSplayTree(temporary_resources,ConstantString(path), (const void *) NULL); return(file); }
FILE * _freopen64_r (struct _reent *ptr, const char *file, const char *mode, register FILE *fp) { register int f; int flags, oflags, oflags2; int e = 0; CHECK_INIT (ptr, fp); /* We can't use the _newlib_flockfile_XXX macros here due to the interlocked locking with the sfp_lock. */ #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT int __oldcancel; pthread_setcancelstate (PTHREAD_CANCEL_DISABLE, &__oldcancel); #endif oflags2 = fp->_flags2; if (!(oflags2 & __SNLK)) _flockfile (fp); if ((flags = __sflags (ptr, mode, &oflags)) == 0) { if (!(oflags2 & __SNLK)) _funlockfile (fp); #ifdef _STDIO_WITH_THREAD_CANCELLATION_SUPPORT pthread_setcancelstate (__oldcancel, &__oldcancel); #endif _fclose_r (ptr, fp); return NULL; } /* * Remember whether the stream was open to begin with, and * which file descriptor (if any) was associated with it. * If it was attached to a descriptor, defer closing it, * so that, e.g., freopen("/dev/stdin", "r", stdin) works. * This is unnecessary if it was not a Unix file. */ if (fp->_flags == 0) fp->_flags = __SEOF; /* hold on to it */ else { if (fp->_flags & __SWR) _fflush_r (ptr, fp); /* * If close is NULL, closing is a no-op, hence pointless. * If file is NULL, the file should not be closed. */ if (fp->_close != NULL && file != NULL) fp->_close (ptr, fp->_cookie); } /* * Now get a new descriptor to refer to the new file, or reuse the * existing file descriptor if file is NULL. */ if (file != NULL) { f = _open64_r (ptr, (char *) file, oflags, 0666); e = __errno_r(ptr); } else { #ifdef HAVE_FCNTL int oldflags; /* * Reuse the file descriptor, but only if the new access mode is * equal or less permissive than the old. F_SETFL correctly * ignores creation flags. */ f = fp->_file; if ((oldflags = _fcntl_r (ptr, f, F_GETFL, 0)) == -1 || ! ((oldflags & O_ACCMODE) == O_RDWR || ((oldflags ^ oflags) & O_ACCMODE) == 0) || _fcntl_r (ptr, f, F_SETFL, oflags) == -1) f = -1; #else /* We cannot modify without fcntl support. */ f = -1; #endif #ifdef __SCLE /* * F_SETFL doesn't change textmode. Don't mess with modes of ttys. */ if (0 <= f && ! isatty (f) && setmode (f, oflags & (O_BINARY | O_TEXT)) == -1) f = -1; #endif if (f < 0) { e = EBADF; if (fp->_close != NULL) fp->_close (ptr, fp->_cookie); } } /* * Finish closing fp. Even if the open succeeded above, * we cannot keep fp->_base: it may be the wrong size. * This loses the effect of any setbuffer calls, * but stdio has always done this before. */ if (fp->_flags & __SMBF) _free_r (ptr, (char *) fp->_bf._base); fp->_w = 0; fp->_r = 0; fp->_p = NULL; fp->_bf._base = NULL; fp->_bf._size = 0; fp->_lbfsize = 0; if (HASUB (fp)) FREEUB (ptr, fp); fp->_ub._size = 0; if (HASLB (fp)) FREELB (ptr, fp); fp->_lb._size = 0; fp->_flags &= ~__SORD; fp->_flags2 &= ~__SWID; memset (&fp->_mbstate, 0, sizeof (_mbstate_t)); if (f < 0) { /* did not get it after all */ __sfp_lock_acquire (); fp->_flags = 0; /* set it free */ __errno_r(ptr) = e; /* restore in case _close clobbered */ if (!(oflags2 & __SNLK)) _funlockfile (fp); #ifndef __SINGLE_THREAD__ __lock_close_recursive (fp->_lock); #endif __sfp_lock_release (); #if !defined (__SINGLE_THREAD__) && defined (_POSIX_THREADS) pthread_setcancelstate (__oldcancel, &__oldcancel); #endif return NULL; } fp->_flags = flags; fp->_file = f; fp->_cookie = (void *) fp; fp->_read = __sread; fp->_write = __swrite64; fp->_seek = __sseek; fp->_seek64 = __sseek64; fp->_close = __sclose; #ifdef __SCLE if (__stextmode(fp->_file)) fp->_flags |= __SCLE; #endif fp->_flags |= __SL64; if (!(oflags2 & __SNLK)) _funlockfile (fp); #if !defined (__SINGLE_THREAD__) && defined (_POSIX_THREADS) pthread_setcancelstate (__oldcancel, &__oldcancel); #endif return fp; }
void main( int argc, char **argv ) { FILE *fp; int ch; format fmt = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; char fmtset = 0; argv = ExpandEnv( &argc, argv ); for( ;; ) { ch = GetOpt( &argc, argv, "bcdDhoOsSxX", usageMsg ); if( ch == -1 ) { break; } if( strchr( "bcdDhoOsSxX", ch ) != NULL ) { fmtset = 1; switch( ch ) { // switch to set format type case 'h': fmt.b_hex = 1; break; case 'b': fmt.b_oct = 1; break; case 'c': fmt.b_asc = 1; break; case 'd': fmt.w_dec = 1; break; case 'D': fmt.dw_dec = 1; break; case 'o': fmt.w_oct = 1; break; case 'O': fmt.dw_oct = 1; break; case 's': fmt.w_sgn = 1; break; case 'S': fmt.dw_sgn = 1; break; case 'x': fmt.w_hex = 1; break; case 'X': fmt.dw_hex = 1; break; } } } if( !fmtset ) { fmt.w_oct = 1; // set default (octal words) } argv++; if( *argv == NULL || **argv == '+' ) { if( *argv != NULL ) { parseOffset( *argv, &fmt ); // get specified offset if( fmt.offset < 0 ) { Die( "od: invalid offset\n" ); // error } } setmode( STDIN_FILENO, O_BINARY ); // switch stdin to binary mode dumpFile( stdin, &fmt ); } else { if( argc == 3 ) { parseOffset( *(argv + 1), &fmt ); // get specified offset if( fmt.offset < 0 ) { Die( "od: invalid offset\n" ); // error } } if( (fp = fopen( *argv, "rb" )) == NULL ) { Die( "od: cannot open input file \"%s\"\n", *argv ); } dumpFile( fp, &fmt ); fclose( fp ); } }
/* * main * * Description: * This is the entry point for the program * * Parameters: * argc: [in] * This is the count of arguments in the argv array * argv: [in] * This is an array of filenames for which to compute message * digests * * Returns: * Nothing. * * Comments: * */ int main(int argc, char *argv[]) { SHA1Context sha; /* SHA-1 context */ FILE *fp; /* File pointer for reading files*/ char c; /* Character read from file */ int i; /* Counter */ int reading_stdin; /* Are we reading standard in? */ int read_stdin = 0; /* Have we read stdin? */ /* * Check the program arguments and print usage information if -? * or --help is passed as the first argument. */ if (argc > 1 && (string_is_equal(argv[1],"-?") || string_is_equal(argv[1],"--help"))) { usage(); return 1; } /* * For each filename passed in on the command line, calculate the * SHA-1 value and display it. */ for(i = 0; i < argc; i++) { /* * We start the counter at 0 to guarantee entry into the for * loop. So if 'i' is zero, we will increment it now. If there * is no argv[1], we will use STDIN below. */ if (i == 0) i++; if (argc == 1 || string_is_equal(argv[i],"-")) { #ifdef WIN32 setmode(fileno(stdin), _O_BINARY); #endif fp = stdin; reading_stdin = 1; } else { if (!(fp = fopen(argv[i],"rb"))) { fprintf(stderr, "sha: unable to open file %s\n", argv[i]); return 2; } reading_stdin = 0; } /* * We do not want to read STDIN multiple times */ if (reading_stdin) { if (read_stdin) continue; read_stdin = 1; } /* * Reset the SHA-1 context and process input */ SHA1Reset(&sha); c = fgetc(fp); while(!feof(fp)) { SHA1Input(&sha, &c, 1); c = fgetc(fp); } if (!reading_stdin) fclose(fp); if (!SHA1Result(&sha)) { fprintf(stderr, "sha: could not compute message digest for %s\n", reading_stdin?"STDIN":argv[i]); } else { printf( "%08X %08X %08X %08X %08X - %s\n", sha.Message_Digest[0], sha.Message_Digest[1], sha.Message_Digest[2], sha.Message_Digest[3], sha.Message_Digest[4], reading_stdin?"STDIN":argv[i]); } } return 0; }
int main( int argc, char * const argv[] ) #endif { libcstring_system_character_t acquiry_operating_system[ 32 ]; libcstring_system_character_t input_buffer[ EWFEXPORT_INPUT_BUFFER_SIZE ]; libcstring_system_character_t * const *argv_filenames = NULL; liberror_error_t *error = NULL; #if !defined( LIBSYSTEM_HAVE_GLOB ) libsystem_glob_t *glob = NULL; #endif libcstring_system_character_t *acquiry_software_version = NULL; libcstring_system_character_t *log_filename = NULL; libcstring_system_character_t *option_additional_digest_types = NULL; libcstring_system_character_t *option_compression_level = NULL; libcstring_system_character_t *option_format = NULL; libcstring_system_character_t *option_header_codepage = NULL; libcstring_system_character_t *option_maximum_segment_size = NULL; libcstring_system_character_t *option_offset = NULL; libcstring_system_character_t *option_process_buffer_size = NULL; libcstring_system_character_t *option_sectors_per_chunk = NULL; libcstring_system_character_t *option_size = NULL; libcstring_system_character_t *option_target_filename = NULL; libcstring_system_character_t *program = _LIBCSTRING_SYSTEM_STRING( "ewfexport" ); libcstring_system_character_t *request_string = NULL; log_handle_t *log_handle = NULL; libcstring_system_integer_t option = 0; size64_t media_size = 0; size_t string_length = 0; uint8_t calculate_md5 = 1; uint8_t print_status_information = 1; uint8_t swap_byte_pairs = 0; uint8_t verbose = 0; uint8_t zero_chunk_on_error = 0; int interactive_mode = 1; int number_of_filenames = 0; int result = 1; libsystem_notify_set_stream( stderr, NULL ); libsystem_notify_set_verbose( 1 ); if( libsystem_initialize( "ewftools", &error ) != 1 ) { ewfoutput_version_fprint( stderr, program ); fprintf( stderr, "Unable to initialize system values.\n" ); goto on_error; } #if defined( WINAPI ) && !defined( __CYGWIN__ ) #if defined( _MSC_VER ) if( _setmode( _fileno( stdout ), _O_BINARY ) == -1 ) #else if( setmode( _fileno( stdout ), _O_BINARY ) == -1 ) #endif { ewfoutput_version_fprint( stderr, program ); fprintf( stderr, "Unable to set stdout to binary mode.\n" ); usage_fprint( stdout ); goto on_error; } #endif while( ( option = libsystem_getopt( argc, argv, _LIBCSTRING_SYSTEM_STRING( "A:b:B:c:d:f:hl:o:p:qsS:t:uvVw" ) ) ) != (libcstring_system_integer_t) -1 ) { switch( option ) { case (libcstring_system_integer_t) '?': default: ewfoutput_version_fprint( stderr, program ); fprintf( stderr, "Invalid argument: %" PRIs_LIBCSTRING_SYSTEM ".\n", argv[ optind - 1 ] ); usage_fprint( stderr ); goto on_error; case (libcstring_system_integer_t) 'A': option_header_codepage = optarg; break; case (libcstring_system_integer_t) 'b': option_sectors_per_chunk = optarg; break; case (libcstring_system_integer_t) 'B': option_size = optarg; break; case (libcstring_system_integer_t) 'c': option_compression_level = optarg; break; case (libcstring_system_integer_t) 'd': option_additional_digest_types = optarg; break; case (libcstring_system_integer_t) 'f': option_format = optarg; break; case (libcstring_system_integer_t) 'h': ewfoutput_version_fprint( stderr, program ); usage_fprint( stderr ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'l': log_filename = optarg; break; case (libcstring_system_integer_t) 'o': option_offset = optarg; break; case (libcstring_system_integer_t) 'p': option_process_buffer_size = optarg; break; case (libcstring_system_integer_t) 'q': print_status_information = 0; break; case (libcstring_system_integer_t) 's': swap_byte_pairs = 1; break; case (libcstring_system_integer_t) 'S': option_maximum_segment_size = optarg; break; case (libcstring_system_integer_t) 't': option_target_filename = optarg; break; case (libcstring_system_integer_t) 'u': interactive_mode = 0; break; case (libcstring_system_integer_t) 'v': verbose = 1; break; case (libcstring_system_integer_t) 'V': ewfoutput_version_fprint( stderr, program ); ewfoutput_copyright_fprint( stderr ); return( EXIT_SUCCESS ); case (libcstring_system_integer_t) 'w': zero_chunk_on_error = 1; break; } } if( optind == argc ) { ewfoutput_version_fprint( stderr, program ); fprintf( stderr, "Missing EWF image file(s).\n" ); usage_fprint( stderr ); goto on_error; } ewfoutput_version_fprint( stderr, program ); libsystem_notify_set_verbose( verbose ); libewf_notify_set_verbose( verbose ); libewf_notify_set_stream( stderr, NULL ); #if !defined( LIBSYSTEM_HAVE_GLOB ) if( libsystem_glob_initialize( &glob, &error ) != 1 ) { fprintf( stderr, "Unable to initialize glob.\n" ); goto on_error; } if( libsystem_glob_resolve( glob, &( argv[ optind ] ), argc - optind, &error ) != 1 ) { fprintf( stderr, "Unable to resolve glob.\n" ); goto on_error; } argv_filenames = glob->result; number_of_filenames = glob->number_of_results; #else argv_filenames = &( argv[ optind ] ); number_of_filenames = argc - optind; #endif if( export_handle_initialize( &ewfexport_export_handle, calculate_md5, &error ) != 1 ) { fprintf( stderr, "Unable to create export handle.\n" ); goto on_error; } if( libsystem_signal_attach( ewfexport_signal_handler, &error ) != 1 ) { fprintf( stderr, "Unable to attach signal handler.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } result = export_handle_open_input( ewfexport_export_handle, argv_filenames, number_of_filenames, &error ); if( ewfexport_abort != 0 ) { goto on_abort; } if( result != 1 ) { fprintf( stderr, "Unable to open EWF file(s).\n" ); goto on_error; } #if !defined( LIBSYSTEM_HAVE_GLOB ) if( libsystem_glob_free( &glob, &error ) != 1 ) { fprintf( stderr, "Unable to free glob.\n" ); goto on_error; } #endif if( export_handle_get_input_media_size( ewfexport_export_handle, &media_size, &error ) != 1 ) { fprintf( stderr, "Unable to retrieve input media size.\n" ); goto on_error; } if( option_header_codepage != NULL ) { result = export_handle_set_header_codepage( ewfexport_export_handle, option_header_codepage, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set header codepage.\n" ); goto on_error; } else if( result == 0 ) { fprintf( stderr, "Unsupported header codepage defaulting to: ascii.\n" ); } } if( option_target_filename != NULL ) { if( export_handle_set_string( ewfexport_export_handle, option_target_filename, &( ewfexport_export_handle->target_filename ), &( ewfexport_export_handle->target_filename_size ), &error ) != 1 ) { fprintf( stderr, "Unable to set target filename.\n" ); goto on_error; } } else if( interactive_mode == 0 ) { /* Make sure the target filename is set in unattended mode */ if( export_handle_set_string( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "export" ), &( ewfexport_export_handle->target_filename ), &( ewfexport_export_handle->target_filename_size ), &error ) != 1 ) { fprintf( stderr, "Unable to set target filename.\n" ); goto on_error; } } if( option_compression_level != NULL ) { result = export_handle_set_compression_values( ewfexport_export_handle, option_compression_level, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set compression values.\n" ); goto on_error; } else if( result == 0 ) { fprintf( stderr, "Unsupported compression level defaulting to: none.\n" ); } } if( option_format != NULL ) { result = export_handle_set_format( ewfexport_export_handle, option_format, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set format.\n" ); goto on_error; } else if( result == 0 ) { fprintf( stderr, "Unsupported output format defaulting to: raw.\n" ); } } if( option_sectors_per_chunk != NULL ) { result = export_handle_set_sectors_per_chunk( ewfexport_export_handle, option_sectors_per_chunk, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set sectors per chunk.\n" ); goto on_error; } else if( result == 0 ) { fprintf( stderr, "Unsupported sectors per chunk defaulting to: 64.\n" ); } } if( option_maximum_segment_size != NULL ) { result = export_handle_set_maximum_segment_size( ewfexport_export_handle, option_maximum_segment_size, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set maximum segment size.\n" ); goto on_error; } if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_EWF ) { if( ( result == 0 ) || ( ewfexport_export_handle->maximum_segment_size < EWFCOMMON_MINIMUM_SEGMENT_FILE_SIZE ) || ( ( ewfexport_export_handle->ewf_format == LIBEWF_FORMAT_ENCASE6 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT ) ) || ( ( ewfexport_export_handle->ewf_format != LIBEWF_FORMAT_ENCASE6 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_32BIT ) ) ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_DEFAULT_SEGMENT_FILE_SIZE; fprintf( stderr, "Unsupported maximum segment size defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->maximum_segment_size ); } } else if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_RAW ) { if( ( result == 0 ) || ( ( ewfexport_export_handle->maximum_segment_size != 0 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT ) ) ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_DEFAULT_SEGMENT_FILE_SIZE; fprintf( stderr, "Unsupported maximum segment size defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->maximum_segment_size ); } } } if( option_offset != NULL ) { string_length = libcstring_system_string_length( option_offset ); if( libsystem_string_to_uint64( option_offset, string_length + 1, &ewfexport_export_handle->export_offset, &error ) != 1 ) { libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); ewfexport_export_handle->export_offset = 0; fprintf( stderr, "Unsupported export offset defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->export_offset ); } } if( option_size != NULL ) { string_length = libcstring_system_string_length( option_size ); if( libsystem_string_to_uint64( option_size, string_length + 1, &ewfexport_export_handle->export_size, &error ) != 1 ) { libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); ewfexport_export_handle->export_size = 0; fprintf( stderr, "Unsupported export size defaulting to: all bytes.\n" ); } } if( option_process_buffer_size != NULL ) { result = export_handle_set_process_buffer_size( ewfexport_export_handle, option_process_buffer_size, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set process buffer size.\n" ); goto on_error; } else if( ( result == 0 ) || ( ewfexport_export_handle->process_buffer_size > (size_t) SSIZE_MAX ) ) { ewfexport_export_handle->process_buffer_size = 0; fprintf( stderr, "Unsupported process buffer size defaulting to: chunk size.\n" ); } } if( option_additional_digest_types != NULL ) { result = export_handle_set_additional_digest_types( ewfexport_export_handle, option_additional_digest_types, &error ); if( result == -1 ) { fprintf( stderr, "Unable to set additional digest types.\n" ); goto on_error; } } /* Initialize values */ if( ( ewfexport_export_handle->export_size == 0 ) || ( ewfexport_export_handle->export_size > ( media_size - ewfexport_export_handle->export_offset ) ) ) { ewfexport_export_handle->export_size = media_size - ewfexport_export_handle->export_offset; } /* Request the necessary case data */ if( interactive_mode != 0 ) { if( libsystem_signal_detach( &error ) != 1 ) { fprintf( stderr, "Unable to detach signal handler.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } fprintf( stderr, "Information for export required, please provide the necessary input\n" ); if( option_format == NULL ) { result = export_handle_prompt_for_format( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "Export to format" ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine format.\n" ); goto on_error; } } if( option_target_filename == NULL ) { if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_EWF ) { request_string = _LIBCSTRING_SYSTEM_STRING( "Target path and filename without extension" ); } else if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_FILES ) { request_string = _LIBCSTRING_SYSTEM_STRING( "Target path" ); } else if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_RAW ) { request_string = _LIBCSTRING_SYSTEM_STRING( "Target path and filename without extension or - for stdout" ); } } if( request_string != NULL ) { do { result = export_handle_prompt_for_string( ewfexport_export_handle, request_string, &( ewfexport_export_handle->target_filename ), &( ewfexport_export_handle->target_filename_size ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine target.\n" ); goto on_error; } else if( result == 0 ) { fprintf( stdout, "Target is required, please try again or terminate using Ctrl^C.\n" ); } } while( result != 1 ); } if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_EWF ) { if( option_compression_level == NULL ) { result = export_handle_prompt_for_compression_level( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "Use compression" ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine compression level.\n" ); goto on_error; } } if( option_maximum_segment_size == NULL ) { result = export_handle_prompt_for_maximum_segment_size( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "Evidence segment file size in bytes" ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine maximum segment size.\n" ); goto on_error; } if( ( ewfexport_export_handle->maximum_segment_size < EWFCOMMON_MINIMUM_SEGMENT_FILE_SIZE ) || ( ( ewfexport_export_handle->ewf_format == LIBEWF_FORMAT_ENCASE6 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT ) ) || ( ( ewfexport_export_handle->ewf_format != LIBEWF_FORMAT_ENCASE6 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_32BIT ) ) ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_DEFAULT_SEGMENT_FILE_SIZE; fprintf( stderr, "Unsupported maximum segment size defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->maximum_segment_size ); } } if( option_sectors_per_chunk == NULL ) { result = export_handle_prompt_for_sectors_per_chunk( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "The number of sectors to read at once" ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine sectors per chunk.\n" ); goto on_error; } } } else if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_RAW ) { if( ( ewfexport_export_handle->target_filename != NULL ) && ( ( ewfexport_export_handle->target_filename )[ 0 ] == (libcstring_system_character_t) '-' ) && ( ( ewfexport_export_handle->target_filename )[ 1 ] == 0 ) ) { /* No need for segment files when exporting to stdout */ } else if( option_maximum_segment_size == NULL ) { result = export_handle_prompt_for_maximum_segment_size( ewfexport_export_handle, _LIBCSTRING_SYSTEM_STRING( "Evidence segment file size in bytes (0 is unlimited)" ), &error ); if( result == -1 ) { fprintf( stderr, "Unable to determine maximum segment size.\n" ); goto on_error; } if( ( ewfexport_export_handle->maximum_segment_size != 0 ) && ( ewfexport_export_handle->maximum_segment_size >= (uint64_t) EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT ) ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_DEFAULT_SEGMENT_FILE_SIZE; fprintf( stderr, "Unsupported maximum segment size defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->maximum_segment_size ); } } } if( ( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_EWF ) || ( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_RAW ) ) { if( option_offset == NULL ) { if( ewfinput_get_size_variable( stderr, input_buffer, EWFEXPORT_INPUT_BUFFER_SIZE, _LIBCSTRING_SYSTEM_STRING( "Start export at offset" ), 0, media_size, ewfexport_export_handle->export_offset, &( ewfexport_export_handle->export_offset ), &error ) == -1 ) { libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); ewfexport_export_handle->export_offset = 0; fprintf( stderr, "Unable to determine export offset defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->export_offset ); } } if( option_size == NULL ) { if( ewfinput_get_size_variable( stderr, input_buffer, EWFEXPORT_INPUT_BUFFER_SIZE, _LIBCSTRING_SYSTEM_STRING( "Number of bytes to export" ), 0, media_size - ewfexport_export_handle->export_offset, ewfexport_export_handle->export_size, &( ewfexport_export_handle->export_size ), &error ) == -1 ) { libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); ewfexport_export_handle->export_size = media_size - ewfexport_export_handle->export_offset; fprintf( stderr, "Unable to determine export size defaulting to: %" PRIu64 ".\n", ewfexport_export_handle->export_size ); } } } if( libsystem_signal_attach( ewfexport_signal_handler, &error ) != 1 ) { fprintf( stderr, "Unable to attach signal handler.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } } else { if( ewfexport_export_handle->maximum_segment_size == 0 ) { if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_EWF ) { if( ewfexport_export_handle->ewf_format == LIBEWF_FORMAT_ENCASE6 ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT; } else { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_32BIT; } } else if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_RAW ) { ewfexport_export_handle->maximum_segment_size = EWFCOMMON_MAXIMUM_SEGMENT_FILE_SIZE_64BIT; } } } fprintf( stderr, "\n" ); if( log_filename != NULL ) { if( log_handle_initialize( &log_handle, &error ) != 1 ) { fprintf( stderr, "Unable to create log handle.\n" ); goto on_error; } if( log_handle_open( log_handle, log_filename, &error ) != 1 ) { fprintf( stderr, "Unable to open log file: %" PRIs_LIBCSTRING_SYSTEM ".\n", log_filename ); goto on_error; } } if( ewfexport_export_handle->output_format == EXPORT_HANDLE_OUTPUT_FORMAT_FILES ) { result = export_handle_export_single_files( ewfexport_export_handle, ewfexport_export_handle->target_filename, print_status_information, log_handle, &error ); if( result != 1 ) { fprintf( stderr, "Unable to export single files.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } } else { if( export_handle_open_output( ewfexport_export_handle, ewfexport_export_handle->target_filename, &error ) != 1 ) { fprintf( stderr, "Unable to open output.\n" ); goto on_error; } if( platform_get_operating_system( acquiry_operating_system, 32, &error ) != 1 ) { fprintf( stderr, "Unable to determine operating system.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); acquiry_operating_system[ 0 ] = 0; } acquiry_software_version = _LIBCSTRING_SYSTEM_STRING( LIBEWF_VERSION_STRING ); if( export_handle_set_output_values( ewfexport_export_handle, acquiry_operating_system, program, acquiry_software_version, zero_chunk_on_error, &error ) != 1 ) { fprintf( stderr, "Unable to set output values.\n" ); goto on_error; } result = export_handle_export_input( ewfexport_export_handle, swap_byte_pairs, print_status_information, log_handle, &error ); if( result != 1 ) { fprintf( stderr, "Unable to export input.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } } if( log_handle != NULL ) { if( log_handle_close( log_handle, &error ) != 0 ) { fprintf( stderr, "Unable to close log file: %" PRIs_LIBCSTRING_SYSTEM ".\n", log_filename ); goto on_error; } if( log_handle_free( &log_handle, &error ) != 1 ) { fprintf( stderr, "Unable to free log handle.\n" ); goto on_error; } } on_abort: if( export_handle_close( ewfexport_export_handle, &error ) != 0 ) { fprintf( stderr, "Unable to close export handle.\n" ); goto on_error; } if( libsystem_signal_detach( &error ) != 1 ) { fprintf( stderr, "Unable to detach signal handler.\n" ); libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } if( export_handle_free( &ewfexport_export_handle, &error ) != 1 ) { fprintf( stderr, "Unable to free export handle.\n" ); goto on_error; } if( ewfexport_abort != 0 ) { fprintf( stdout, "%" PRIs_LIBCSTRING_SYSTEM ": ABORTED\n", program ); return( EXIT_FAILURE ); } if( result != 1 ) { fprintf( stdout, "%" PRIs_LIBCSTRING_SYSTEM ": FAILURE\n", program ); return( EXIT_FAILURE ); } fprintf( stdout, "%" PRIs_LIBCSTRING_SYSTEM ": SUCCESS\n", program ); return( EXIT_SUCCESS ); on_error: if( error != NULL ) { libsystem_notify_print_error_backtrace( error ); liberror_error_free( &error ); } if( log_handle != NULL ) { log_handle_close( log_handle, NULL ); log_handle_free( &log_handle, NULL ); } if( ewfexport_export_handle != NULL ) { export_handle_close( ewfexport_export_handle, NULL ); export_handle_free( &ewfexport_export_handle, NULL ); } #if !defined( LIBSYSTEM_HAVE_GLOB ) if( glob != NULL ) { libsystem_glob_free( &glob, NULL ); } #endif return( EXIT_FAILURE ); }
/* Read the file FNAME or stdin if FNAME is NULL and return a malloced buffer with the content. R_LENGTH received the length of the file. Print a diagnostic and returns NULL on error. */ static char * read_file (const char *fname, size_t *r_length) { FILE *fp; char *buf; size_t buflen; if (!fname) { size_t nread, bufsize = 0; fp = stdin; #ifdef HAVE_DOSISH_SYSTEM setmode (fileno(fp) , O_BINARY ); #endif buf = NULL; buflen = 0; #define NCHUNK 8192 do { bufsize += NCHUNK; if (!buf) buf = xmalloc (bufsize); else buf = xrealloc (buf, bufsize); nread = fread (buf+buflen, 1, NCHUNK, fp); if (nread < NCHUNK && ferror (fp)) { fprintf (stderr, PGM": error reading '[stdin]': %s\n", strerror (errno)); xfree (buf); return NULL; } buflen += nread; } while (nread == NCHUNK); #undef NCHUNK } else { struct stat st; fp = fopen (fname, "rb"); if (!fp) { fprintf (stderr, PGM": can't open '%s': %s\n", fname, strerror (errno)); return NULL; } if (fstat (fileno(fp), &st)) { fprintf (stderr, PGM": can't stat '%s': %s\n", fname, strerror (errno)); fclose (fp); return NULL; } buflen = st.st_size; buf = xmalloc (buflen+1); if (fread (buf, buflen, 1, fp) != 1) { fprintf (stderr, PGM": error reading '%s': %s\n", fname, strerror (errno)); fclose (fp); xfree (buf); return NULL; } fclose (fp); } *r_length = buflen; return buf; }
int main(int argc, char *argv[]) { int conn, c, len, bytesWritten; int port, to_stdout, reload; int ping, pcount; int keep_alive = 0; int opt_noaccept = 0; int opt_verbose = 0; const char *hostname, *localhost; char url[BUFSIZ], msg[BUFSIZ], buf[BUFSIZ]; char extra_hdrs[BUFSIZ]; const char *method = "GET"; extern char *optarg; time_t ims = 0; int max_forwards = -1; struct timeval tv1, tv2; int i = 0, loops; long ping_int; long ping_min = 0, ping_max = 0, ping_sum = 0, ping_mean = 0; char *proxy_user = NULL; char *proxy_password = NULL; char *www_user = NULL; char *www_password = NULL; /* set the defaults */ hostname = "localhost"; localhost = NULL; extra_hdrs[0] = '\0'; port = CACHE_HTTP_PORT; to_stdout = 1; reload = 0; ping = 0; pcount = 0; ping_int = 1 * 1000; if (argc < 2) { usage(argv[0]); /* need URL */ } else if (argc >= 2) { strncpy(url, argv[argc - 1], BUFSIZ); url[BUFSIZ - 1] = '\0'; if (url[0] == '-') usage(argv[0]); while ((c = getopt(argc, argv, "ah:l:P:i:km:p:rsvt:g:p:I:H:T:u:U:w:W:?")) != -1) switch (c) { case 'a': opt_noaccept = 1; break; case 'h': /* remote host */ if (optarg != NULL) hostname = optarg; break; case 'l': /* local host */ if (optarg != NULL) localhost = optarg; break; case 's': /* silent */ to_stdout = 0; break; case 'k': /* backward compat */ keep_alive = 1; break; case 'r': /* reload */ reload = 1; break; case 'p': /* port number */ sscanf(optarg, "%d", &port); if (port < 1) port = CACHE_HTTP_PORT; /* default */ break; case 'P': put_file = xstrdup(optarg); break; case 'i': /* IMS */ ims = (time_t) atoi(optarg); break; case 'm': method = xstrdup(optarg); break; case 't': method = xstrdup("TRACE"); max_forwards = atoi(optarg); break; case 'g': ping = 1; pcount = atoi(optarg); to_stdout = 0; break; case 'I': if ((ping_int = atoi(optarg) * 1000) <= 0) usage(argv[0]); break; case 'H': if (strlen(optarg)) { char *t; strncpy(extra_hdrs, optarg, sizeof(extra_hdrs)); while ((t = strstr(extra_hdrs, "\\n"))) *t = '\r', *(t + 1) = '\n'; } break; case 'T': io_timeout = atoi(optarg); break; case 'u': proxy_user = optarg; break; case 'w': proxy_password = optarg; break; case 'U': www_user = optarg; break; case 'W': www_password = optarg; break; case 'v': /* undocumented: may increase verb-level by giving more -v's */ opt_verbose++; break; case '?': /* usage */ default: usage(argv[0]); break; } } #ifdef _SQUID_MSWIN_ { WSADATA wsaData; WSAStartup(2, &wsaData); } #endif /* Build the HTTP request */ if (strncmp(url, "mgr:", 4) == 0) { char *t = xstrdup(url + 4); snprintf(url, BUFSIZ, "cache_object://%s/%s", hostname, t); xfree(t); } if (put_file) { put_fd = open(put_file, O_RDONLY); set_our_signal(); if (put_fd < 0) { fprintf(stderr, "%s: can't open file (%s)\n", argv[0], xstrerror()); exit(-1); } #ifdef _SQUID_WIN32_ setmode(put_fd, O_BINARY); #endif fstat(put_fd, &sb); } snprintf(msg, BUFSIZ, "%s %s HTTP/1.0\r\n", method, url); if (reload) { snprintf(buf, BUFSIZ, "Pragma: no-cache\r\n"); strcat(msg, buf); } if (put_fd > 0) { snprintf(buf, BUFSIZ, "Content-length: %d\r\n", (int) sb.st_size); strcat(msg, buf); } if (opt_noaccept == 0) { snprintf(buf, BUFSIZ, "Accept: */*\r\n"); strcat(msg, buf); } if (ims) { snprintf(buf, BUFSIZ, "If-Modified-Since: %s\r\n", mkrfc1123(ims)); strcat(msg, buf); } if (max_forwards > -1) { snprintf(buf, BUFSIZ, "Max-Forwards: %d\r\n", max_forwards); strcat(msg, buf); } if (proxy_user) { char *user = proxy_user; char *password = proxy_password; #if HAVE_GETPASS if (!password) password = getpass("Proxy password: "******"ERROR: Proxy password missing\n"); exit(1); } snprintf(buf, BUFSIZ, "%s:%s", user, password); snprintf(buf, BUFSIZ, "Proxy-Authorization: Basic %s\r\n", base64_encode(buf)); strcat(msg, buf); } if (www_user) { char *user = www_user; char *password = www_password; #if HAVE_GETPASS if (!password) password = getpass("WWW password: "******"ERROR: WWW password missing\n"); exit(1); } snprintf(buf, BUFSIZ, "%s:%s", user, password); snprintf(buf, BUFSIZ, "Authorization: Basic %s\r\n", base64_encode(buf)); strcat(msg, buf); } if (keep_alive) { if (port != 80) snprintf(buf, BUFSIZ, "Proxy-Connection: keep-alive\r\n"); else snprintf(buf, BUFSIZ, "Connection: keep-alive\r\n"); strcat(msg, buf); } strcat(msg, extra_hdrs); snprintf(buf, BUFSIZ, "\r\n"); strcat(msg, buf); if (opt_verbose) fprintf(stderr, "headers: '%s'\n", msg); if (ping) { #if HAVE_SIGACTION struct sigaction sa, osa; if (sigaction(SIGINT, NULL, &osa) == 0 && osa.sa_handler == SIG_DFL) { sa.sa_handler = catchSignal; sa.sa_flags = 0; sigemptyset(&sa.sa_mask); (void) sigaction(SIGINT, &sa, NULL); } #else void (*osig) (); if ((osig = signal(SIGINT, catchSignal)) != SIG_DFL) (void) signal(SIGINT, osig); #endif } loops = ping ? pcount : 1; for (i = 0; loops == 0 || i < loops; i++) { squid_off_t fsize = 0; /* Connect to the server */ if ((conn = socket(PF_INET, SOCK_STREAM, 0)) < 0) { perror("client: socket"); exit(1); } if (localhost && client_comm_bind(conn, localhost) < 0) { perror("client: bind"); exit(1); } if (client_comm_connect(conn, hostname, port, (ping || opt_verbose) ? &tv1 : NULL) < 0) { if (errno == 0) { fprintf(stderr, "client: ERROR: Cannot connect to %s:%d: Host unknown.\n", hostname, port); } else { char tbuf[BUFSIZ]; snprintf(tbuf, BUFSIZ, "client: ERROR: Cannot connect to %s:%d", hostname, port); perror(tbuf); } exit(1); } /* Send the HTTP request */ bytesWritten = mywrite(conn, msg, strlen(msg)); if (bytesWritten < 0) { perror("client: ERROR: write"); exit(1); } else if (bytesWritten != strlen(msg)) { fprintf(stderr, "client: ERROR: Cannot send request?: %s\n", msg); exit(1); } if (put_file) { int x; lseek(put_fd, 0, SEEK_SET); #ifdef _SQUID_MSWIN_ while ((x = read(put_fd, buf, sizeof(buf))) > 0) { #else while ((x = myread(put_fd, buf, sizeof(buf))) > 0) { #endif x = mywrite(conn, buf, x); total_bytes += x; if (x <= 0) break; } if (x != 0) fprintf(stderr, "client: ERROR: Cannot send file.\n"); } /* Read the data */ #ifdef _SQUID_MSWIN_ setmode(1, O_BINARY); #endif while ((len = myread(conn, buf, sizeof(buf))) > 0) { fsize += len; if (to_stdout) fwrite(buf, len, 1, stdout); } #ifdef _SQUID_MSWIN_ setmode(1, O_TEXT); #endif (void) close(conn); /* done with socket */ if (interrupted) break; if (ping || opt_verbose) { struct tm *tmp; time_t t2s; long elapsed_msec; (void) Now(&tv2); elapsed_msec = tvSubMsec(tv1, tv2); t2s = tv2.tv_sec; tmp = localtime(&t2s); fprintf(stderr, "%d-%02d-%02d %02d:%02d:%02d [%d]: %ld.%03ld secs, %f KB/s (%" PRINTF_OFF_T "KB)\n", tmp->tm_year + 1900, tmp->tm_mon + 1, tmp->tm_mday, tmp->tm_hour, tmp->tm_min, tmp->tm_sec, i + 1, elapsed_msec / 1000, elapsed_msec % 1000, elapsed_msec ? (double) fsize / elapsed_msec * 1000 / 1024 : -1.0, (fsize + 1023) / 1024); if (i == 0 || elapsed_msec < ping_min) ping_min = elapsed_msec; if (i == 0 || elapsed_msec > ping_max) ping_max = elapsed_msec; ping_sum += elapsed_msec; /* Delay until next "ping_int" boundary */ if (ping && (loops == 0 || i + 1 < loops) && elapsed_msec < ping_int) { struct timeval tvs; long msec_left = ping_int - elapsed_msec; tvs.tv_sec = msec_left / 1000; tvs.tv_usec = (msec_left % 1000) * 1000; select(0, NULL, NULL, NULL, &tvs); } } } if (ping && i) { ping_mean = ping_sum / i; fprintf(stderr, "%d requests, round-trip (secs) min/avg/max = " "%ld.%03ld/%ld.%03ld/%ld.%03ld\n", i, ping_min / 1000, ping_min % 1000, ping_mean / 1000, ping_mean % 1000, ping_max / 1000, ping_max % 1000); } exit(0); /*NOTREACHED */ return 0; } static int client_comm_bind(int sock, const char *local_host) { static const struct hostent *hp = NULL; static struct sockaddr_in from_addr; /* Set up the source socket address from which to send. */ if (hp == NULL) { from_addr.sin_family = AF_INET; if ((hp = gethostbyname(local_host)) == 0) { return (-1); } xmemcpy(&from_addr.sin_addr, hp->h_addr, hp->h_length); from_addr.sin_port = 0; } return bind(sock, (struct sockaddr *) &from_addr, sizeof(struct sockaddr_in)); } static int client_comm_connect(int sock, const char *dest_host, u_short dest_port, struct timeval *tvp) { static const struct hostent *hp = NULL; static struct sockaddr_in to_addr; /* Set up the destination socket address for message to send to. */ if (hp == NULL) { to_addr.sin_family = AF_INET; if ((hp = gethostbyname(dest_host)) == 0) { return (-1); } xmemcpy(&to_addr.sin_addr, hp->h_addr, hp->h_length); to_addr.sin_port = htons(dest_port); } if (tvp) (void) Now(tvp); return connect(sock, (struct sockaddr *) &to_addr, sizeof(struct sockaddr_in)); } static int Now(struct timeval *tp) { #if GETTIMEOFDAY_NO_TZP return gettimeofday(tp); #else return gettimeofday(tp, NULL); #endif } /* ARGSUSED */ static void catchSignal(int sig) { interrupted = 1; fprintf(stderr, "Interrupted.\n"); }
EMBED_SAPI_API int php_embed_init(int argc, char **argv) { zend_llist global_vars; #ifdef HAVE_SIGNAL_H #if defined(SIGPIPE) && defined(SIG_IGN) signal(SIGPIPE, SIG_IGN); /* ignore SIGPIPE in standalone mode so that sockets created via fsockopen() don't kill PHP if the remote site closes it. in apache|apxs mode apache does that for us! [email protected] 20000419 */ #endif #endif #ifdef ZTS tsrm_startup(1, 1, 0, NULL); (void)ts_resource(0); ZEND_TSRMLS_CACHE_UPDATE(); #endif #ifdef ZEND_SIGNALS zend_signal_startup(); #endif sapi_startup(&php_embed_module); #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif php_embed_module.ini_entries = malloc(sizeof(HARDCODED_INI)); memcpy(php_embed_module.ini_entries, HARDCODED_INI, sizeof(HARDCODED_INI)); php_embed_module.additional_functions = additional_functions; if (argv) { php_embed_module.executable_location = argv[0]; } if (php_embed_module.startup(&php_embed_module)==FAILURE) { return FAILURE; } zend_llist_init(&global_vars, sizeof(char *), NULL, 0); /* Set some Embedded PHP defaults */ SG(options) |= SAPI_OPTION_NO_CHDIR; SG(request_info).argc=argc; SG(request_info).argv=argv; if (php_request_startup()==FAILURE) { php_module_shutdown(); return FAILURE; } SG(headers_sent) = 1; SG(request_info).no_headers = 1; php_register_variable("PHP_SELF", "-", NULL); return SUCCESS; }
/* write ind file */ void indwrite(char *filename, struct index *ind, int pagenum) { int i,j,hpoint=0; char datama[2048],lbuff[BUFFERLEN]; FILE *fp; int conv_euc_to_euc; if (filename && kpse_out_name_ok(filename)) fp=fopen(filename,"wb"); else { fp=stdout; #ifdef WIN32 setmode(fileno(fp), _O_BINARY); #endif } conv_euc_to_euc = is_internalUPTEX() ? 1 : 0; if (conv_euc_to_euc) set_enc_string(NULL, "euc"); convert(atama,datama); if (conv_euc_to_euc) set_enc_string(NULL, "uptex"); fputs(preamble,fp); if (fpage>0) { fprintf(fp,"%s%d%s",setpage_prefix,pagenum,setpage_suffix); } for (i=line_length=0;i<lines;i++) { if (i==0) { if (!((alphabet(ind[i].dic[0][0]))||(japanese(ind[i].dic[0])))) { if (lethead_flag) { if (symbol_flag && strlen(symbol)) { fprintf(fp,"%s%s%s",lethead_prefix,symbol,lethead_suffix); } else if (lethead_flag>0) { fprintf(fp,"%s%s%s",lethead_prefix,symhead_positive,lethead_suffix); } else if (lethead_flag<0) { fprintf(fp,"%s%s%s",lethead_prefix,symhead_negative,lethead_suffix); } } SPRINTF(lbuff,"%s%s",item_0,ind[i].idx[0]); } else if (alphabet(ind[i].dic[0][0])) { if (lethead_flag>0) { fprintf(fp,"%s%c%s",lethead_prefix,ind[i].dic[0][0],lethead_suffix); } else if (lethead_flag<0) { fprintf(fp,"%s%c%s",lethead_prefix,ind[i].dic[0][0]+32,lethead_suffix); } SPRINTF(lbuff,"%s%s",item_0,ind[i].idx[0]); } else if (japanese(ind[i].dic[0])) { if (lethead_flag) { fputs(lethead_prefix,fp); for (j=hpoint;j<(strlen(datama)/2);j++) { if ((unsigned char)ind[i].dic[0][1]<(unsigned char)datama[j*2+1]) { fprint_euc_char(fp,atama[(j-1)*2],atama[(j-1)*2+1]); hpoint=j; break; } } if (j==(strlen(datama)/2)) { fprint_euc_char(fp,atama[(j-1)*2],atama[(j-1)*2+1]); } fputs(lethead_suffix,fp); } SPRINTF(lbuff,"%s%s",item_0,ind[i].idx[0]); for (hpoint=0;hpoint<(strlen(datama)/2);hpoint++) { if ((unsigned char)ind[i].dic[0][1]<(unsigned char)datama[hpoint*2+1]) { break; } } } switch (ind[i].words) { case 1: SAPPENDF(lbuff,"%s",delim_0); break; case 2: SAPPENDF(lbuff,"%s%s",item_x1,ind[i].idx[1]); SAPPENDF(lbuff,"%s",delim_1); break; case 3: SAPPENDF(lbuff,"%s%s",item_x1,ind[i].idx[1]); SAPPENDF(lbuff,"%s%s",item_x2,ind[i].idx[2]); SAPPENDF(lbuff,"%s",delim_2); break; default: break; } printpage(ind,fp,i,lbuff); } else { if (!((alphabet(ind[i].dic[0][0]))||(japanese(ind[i].dic[0])))) { if ((alphabet(ind[i-1].dic[0][0]))||(japanese(ind[i-1].dic[0]))){ fputs(group_skip,fp); if (lethead_flag && symbol_flag) { fprintf(fp,"%s%s%s",lethead_prefix,symbol,lethead_suffix); } } } else if (alphabet(ind[i].dic[0][0])) { if (ind[i].dic[0][0]!=ind[i-1].dic[0][0]) { fputs(group_skip,fp); if (lethead_flag>0) { fprintf(fp,"%s%c%s",lethead_prefix,ind[i].dic[0][0],lethead_suffix); } else if (lethead_flag<0) { fprintf(fp,"%s%c%s",lethead_prefix,ind[i].dic[0][0]+32,lethead_suffix); } } } else if (japanese(ind[i].dic[0])) { for (j=hpoint;j<(strlen(datama)/2);j++) { if ((unsigned char)(ind[i].dic[0][0]<=(unsigned char)datama[j*2])&&((unsigned char)ind[i].dic[0][1]<(unsigned char)datama[j*2+1])) { break; } } if ((j!=hpoint)||(j==0)) { hpoint=j; fputs(group_skip,fp); if (lethead_flag!=0) { fputs(lethead_prefix,fp); fprint_euc_char(fp,atama[(j-1)*2],atama[(j-1)*2+1]); fputs(lethead_suffix,fp); } } } switch (ind[i].words) { case 1: SAPPENDF(lbuff,"%s%s%s",item_0,ind[i].idx[0],delim_0); break; case 2: if (strcmp(ind[i-1].idx[0],ind[i].idx[0])!=0 || strcmp(ind[i-1].dic[0],ind[i].dic[0])!=0) { SAPPENDF(lbuff,"%s%s%s",item_0,ind[i].idx[0],item_x1); } else { if (ind[i-1].words==1) { SAPPENDF(lbuff,"%s",item_01); } else { SAPPENDF(lbuff,"%s",item_1); } } SAPPENDF(lbuff,"%s",ind[i].idx[1]); SAPPENDF(lbuff,"%s",delim_1); break; case 3: if (strcmp(ind[i-1].idx[0],ind[i].idx[0])!=0 || strcmp(ind[i-1].dic[0],ind[i].dic[0])!=0) { SAPPENDF(lbuff,"%s%s",item_0,ind[i].idx[0]); SAPPENDF(lbuff,"%s%s%s",item_x1,ind[i].idx[1],item_x2); } else if (ind[i-1].words==1) { SAPPENDF(lbuff,"%s%s%s",item_01,ind[i].idx[1],item_x2); } else if (strcmp(ind[i-1].idx[1],ind[i].idx[1])!=0 || strcmp(ind[i-1].dic[1],ind[i].dic[1])!=0) { if (ind[i-1].words==2) SAPPENDF(lbuff,"%s%s%s",item_1,ind[i].idx[1],item_12); else SAPPENDF(lbuff,"%s%s%s",item_1,ind[i].idx[1],item_x2); } else { SAPPENDF(lbuff,"%s",item_2); } SAPPENDF(lbuff,"%s%s",ind[i].idx[2],delim_2); break; default: break; } printpage(ind,fp,i,lbuff); } } fputs(postamble,fp); if (filename) fclose(fp); }
int archive_read_open_filename(struct archive *a, const char *filename, size_t block_size) { struct stat st; struct read_file_data *mine; void *b; int fd; archive_clear_error(a); if (filename == NULL || filename[0] == '\0') { /* We used to invoke archive_read_open_fd(a,0,block_size) * here, but that doesn't (and shouldn't) handle the * end-of-file flush when reading stdout from a pipe. * Basically, read_open_fd() is intended for folks who * are willing to handle such details themselves. This * API is intended to be a little smarter for folks who * want easy handling of the common case. */ filename = ""; /* Normalize NULL to "" */ fd = 0; #if defined(__CYGWIN__) || defined(_WIN32) setmode(0, O_BINARY); #endif } else { fd = open(filename, O_RDONLY | O_BINARY); if (fd < 0) { archive_set_error(a, errno, "Failed to open '%s'", filename); return (ARCHIVE_FATAL); } } if (fstat(fd, &st) != 0) { archive_set_error(a, errno, "Can't stat '%s'", filename); return (ARCHIVE_FATAL); } mine = (struct read_file_data *)calloc(1, sizeof(*mine) + strlen(filename)); b = malloc(block_size); if (mine == NULL || b == NULL) { archive_set_error(a, ENOMEM, "No memory"); free(mine); free(b); return (ARCHIVE_FATAL); } strcpy(mine->filename, filename); mine->block_size = block_size; mine->buffer = b; mine->fd = fd; /* Remember mode so close can decide whether to flush. */ mine->st_mode = st.st_mode; /* If we're reading a file from disk, ensure that we don't overwrite it with an extracted file. */ if (S_ISREG(st.st_mode)) { archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); /* * Enabling skip here is a performance optimization * for anything that supports lseek(). On FreeBSD * (and probably many other systems), only regular * files and raw disk devices support lseek() (on * other input types, lseek() returns success but * doesn't actually change the file pointer, which * just completely screws up the position-tracking * logic). In addition, I've yet to find a portable * way to determine if a device is a raw disk device. * So I don't see a way to do much better than to only * enable this optimization for regular files. */ mine->can_skip = 1; } return (archive_read_open2(a, mine, NULL, file_read, file_skip, file_close)); }
static int cli_main( int argc, char * argv[] ) { static const char * ini_defaults[] = { "report_zend_debug", "0", "display_errors", "1", "register_argc_argv", "1", "html_errors", "0", "implicit_flush", "1", "output_buffering", "0", "max_execution_time", "0", "max_input_time", "-1", NULL }; const char ** ini; char ** p = &argv[1]; char ** argend= &argv[argc]; int ret = -1; int c; zend_string *psKey; lsapi_mode = 0; /* enter CLI mode */ #ifdef PHP_WIN32 _fmode = _O_BINARY; /*sets default for file streams to binary */ setmode(_fileno(stdin), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stdout), O_BINARY); /* make the stdio mode be binary */ setmode(_fileno(stderr), O_BINARY); /* make the stdio mode be binary */ #endif zend_first_try { SG(server_context) = (void *) 1; zend_uv.html_errors = 0; /* tell the engine we're in non-html mode */ CG(in_compilation) = 0; /* not initialized but needed for several options */ SG(options) |= SAPI_OPTION_NO_CHDIR; #if PHP_MAJOR_VERSION < 7 EG(uninitialized_zval_ptr) = NULL; #endif for( ini = ini_defaults; *ini; ini+=2 ) { psKey = zend_string_init(*ini, strlen( *ini ), 1); zend_alter_ini_entry_chars(psKey, (char *)*(ini+1), strlen( *(ini+1) ), PHP_INI_SYSTEM, PHP_INI_STAGE_ACTIVATE); zend_string_release(psKey); } while (( p < argend )&&(**p == '-' )) { c = *((*p)+1); ++p; switch( c ) { case 'q': break; case 'i': if (php_request_startup() != FAILURE) { php_print_info(0xFFFFFFFF); #ifdef PHP_OUTPUT_NEWAPI php_output_end_all(); #else php_end_ob_buffers(1); #endif php_request_shutdown( NULL ); ret = 0; } break; case 'v': if (php_request_startup() != FAILURE) { #if ZEND_DEBUG php_printf("PHP %s (%s) (built: %s %s) (DEBUG)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #else php_printf("PHP %s (%s) (built: %s %s)\nCopyright (c) 1997-2018 The PHP Group\n%s", PHP_VERSION, sapi_module.name, __DATE__, __TIME__, get_zend_version()); #endif #ifdef PHP_OUTPUT_NEWAPI php_output_end_all(); #else php_end_ob_buffers(1); #endif php_request_shutdown( NULL ); ret = 0; } break; case 'c': ++p; /* fall through */ case 's': break; case 'l': source_highlight = 2; break; case 'h': case '?': default: cli_usage(); ret = 0; break; } } if ( ret == -1 ) { if ( *p ) { zend_file_handle file_handle; memset(&file_handle, 0, sizeof(file_handle)); file_handle.type = ZEND_HANDLE_FP; file_handle.handle.fp = VCWD_FOPEN(*p, "rb"); if ( file_handle.handle.fp ) { script_filename = *p; php_self = *p; SG(request_info).path_translated = estrdup(*p); SG(request_info).argc = argc - (p - argv); SG(request_info).argv = p; if (php_request_startup() == FAILURE ) { fclose( file_handle.handle.fp ); ret = 2; } else { if (source_highlight == 1) { zend_syntax_highlighter_ini syntax_highlighter_ini; php_get_highlight_struct(&syntax_highlighter_ini); highlight_file(SG(request_info).path_translated, &syntax_highlighter_ini); } else if (source_highlight == 2) { file_handle.filename = *p; file_handle.free_filename = 0; file_handle.opened_path = NULL; ret = php_lint_script(&file_handle); if (ret==SUCCESS) { zend_printf("No syntax errors detected in %s\n", file_handle.filename); } else { zend_printf("Errors parsing %s\n", file_handle.filename); } } else { file_handle.filename = *p; file_handle.free_filename = 0; file_handle.opened_path = NULL; php_execute_script(&file_handle); ret = EG(exit_status); } php_request_shutdown( NULL ); } } else { php_printf("Could not open input file: %s.\n", *p); } } else { cli_usage(); } } }zend_end_try(); php_module_shutdown(); #ifdef ZTS tsrm_shutdown(); #endif return ret; }
int main (int argc, char **argv) { register long address; char string[18]; FILE *fp; progname = *argv++; --argc; /* ** -hex hex dump ** -oct Octal dump ** -group-by-8-bits ** -group-by-16-bits ** -group-by-32-bits ** -group-by-64-bits ** -iso iso character set. ** -big-endian Big Endian ** -little-endian Little Endian ** -un || -de from hexl format to binary. ** -- End switch list. ** <filename> dump filename ** - (as filename == stdin) */ while (*argv && *argv[0] == '-' && (*argv)[1]) { /* A switch! */ if (!strcmp (*argv, "--")) { --argc; argv++; break; } else if (!strcmp (*argv, "-un") || !strcmp (*argv, "-de")) { un_flag = TRUE; --argc; argv++; } else if (!strcmp (*argv, "-hex")) { base = 16; --argc; argv++; } else if (!strcmp (*argv, "-iso")) { iso_flag = TRUE; --argc; argv++; } else if (!strcmp (*argv, "-oct")) { base = 8; --argc; argv++; } else if (!strcmp (*argv, "-big-endian")) { endian = 1; --argc; argv++; } else if (!strcmp (*argv, "-little-endian")) { endian = 0; --argc; argv++; } else if (!strcmp (*argv, "-group-by-8-bits")) { group_by = 0x00; --argc; argv++; } else if (!strcmp (*argv, "-group-by-16-bits")) { group_by = 0x01; --argc; argv++; } else if (!strcmp (*argv, "-group-by-32-bits")) { group_by = 0x03; --argc; argv++; } else if (!strcmp (*argv, "-group-by-64-bits")) { group_by = 0x07; endian = 0; --argc; argv++; } else { fprintf (stderr, "%s: invalid switch: \"%s\".\n", progname, *argv); usage (); } } do { if (*argv == NULL) fp = stdin; else { char *filename = *argv++; if (!strcmp (filename, "-")) fp = stdin; else if ((fp = fopen (filename, "r")) == NULL) { perror (filename); continue; } } if (un_flag) { char buf[18]; #ifdef DOS_NT #if (__DJGPP__ >= 2) || (defined WINDOWSNT) if (!isatty (fileno (stdout))) setmode (fileno (stdout), O_BINARY); #else (stdout)->_flag &= ~_IOTEXT; /* print binary */ _setmode (fileno (stdout), O_BINARY); #endif #endif for (;;) { register int i, c = 0, d; #define hexchar(x) (isdigit (x) ? x - '0' : x - 'a' + 10) fread (buf, 1, 10, fp); /* skip 10 bytes */ for (i=0; i < 16; ++i) { if ((c = getc (fp)) == ' ' || c == EOF) break; d = getc (fp); c = hexchar (c) * 0x10 + hexchar (d); putchar (c); if ((i&group_by) == group_by) getc (fp); } if (c == ' ') { while ((c = getc (fp)) != '\n' && c != EOF) ; if (c == EOF) break; } else { if (i < 16) break; fread (buf, 1, 18, fp); /* skip 18 bytes */ } } } else { #ifdef DOS_NT #if (__DJGPP__ >= 2) || (defined WINDOWSNT) if (!isatty (fileno (fp))) setmode (fileno (fp), O_BINARY); #else (fp)->_flag &= ~_IOTEXT; /* read binary */ _setmode (fileno (fp), O_BINARY); #endif #endif address = 0; string[0] = ' '; string[17] = '\0'; for (;;) { register int i, c = 0; for (i=0; i < 16; ++i) { if ((c = getc (fp)) == EOF) { if (!i) break; fputs (" ", stdout); string[i+1] = '\0'; } else { if (!i) printf ("%08lx: ", address); if (iso_flag) string[i+1] = (c < 0x20 || (c >= 0x7F && c < 0xa0)) ? '.' :c; else string[i+1] = (c < 0x20 || c >= 0x7F) ? '.' : c; printf ("%02x", c); } if ((i&group_by) == group_by) putchar (' '); } if (i) puts (string); if (c == EOF) break; address += 0x10; } } if (fp != stdin) fclose (fp); } while (*argv != NULL); return EXIT_SUCCESS; }
int main(int argc, char *argv[]) { FTS *ftsp; FTSENT *p; void *set; int Hflag, Lflag, Rflag, ch, fflag; int fts_options, hflag, rval, vflag; char *mode; mode_t newmode; Hflag = Lflag = Rflag = fflag = hflag = vflag = 0; while ((ch = getopt(argc, argv, "HLPRXfghorstuvwx")) != -1) switch (ch) { case 'H': Hflag = 1; Lflag = 0; break; case 'L': Lflag = 1; Hflag = 0; break; case 'P': Hflag = Lflag = 0; break; case 'R': Rflag = 1; break; case 'f': fflag = 1; break; case 'h': /* * In System V the -h option causes chmod to change the * mode of the symbolic link. 4.4BSD's symbolic links * didn't have modes, so it was an undocumented noop. * In FreeBSD 3.0, lchmod(2) is introduced and this * option does real work. */ hflag = 1; break; /* * XXX * "-[rwx]" are valid mode commands. If they are the entire * argument, getopt has moved past them, so decrement optind. * Regardless, we're done argument processing. */ case 'g': case 'o': case 'r': case 's': case 't': case 'u': case 'w': case 'X': case 'x': if (argv[optind - 1][0] == '-' && argv[optind - 1][1] == ch && argv[optind - 1][2] == '\0') --optind; goto done; case 'v': vflag++; break; case '?': default: usage(); } done: argv += optind; argc -= optind; if (argc < 2) usage(); if (Rflag) { if (hflag) errx(1, "the -R and -h options may not be " "specified together."); if (Lflag) { fts_options = FTS_LOGICAL; } else { fts_options = FTS_PHYSICAL; if (Hflag) { fts_options |= FTS_COMFOLLOW; } } } else if (hflag) { fts_options = FTS_PHYSICAL; } else { fts_options = FTS_LOGICAL; } mode = *argv; errno = 0; if ((set = setmode(mode)) == NULL) { if (!errno) errx(1, "invalid file mode: %s", mode); else /* malloc for setmode() failed */ err(1, "setmode failed"); } if ((ftsp = fts_open(++argv, fts_options, 0)) == NULL) err(1, "fts_open"); for (rval = 0; (p = fts_read(ftsp)) != NULL;) { int atflag; if ((fts_options & FTS_LOGICAL) || ((fts_options & FTS_COMFOLLOW) && p->fts_level == FTS_ROOTLEVEL)) atflag = 0; else atflag = AT_SYMLINK_NOFOLLOW; switch (p->fts_info) { case FTS_D: if (!Rflag) fts_set(ftsp, p, FTS_SKIP); break; case FTS_DNR: /* Warn, chmod. */ warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); rval = 1; break; case FTS_DP: /* Already changed at FTS_D. */ continue; case FTS_ERR: /* Warn, continue. */ case FTS_NS: warnx("%s: %s", p->fts_path, strerror(p->fts_errno)); rval = 1; continue; default: break; } newmode = getmode(set, p->fts_statp->st_mode); if ((newmode & ALLPERMS) == (p->fts_statp->st_mode & ALLPERMS)) continue; if (fchmodat(AT_FDCWD, p->fts_accpath, newmode, atflag) == -1 && !fflag) { warn("%s", p->fts_path); rval = 1; } else if (vflag) { printf("%s", p->fts_path); if (vflag > 1) { char m1[12], m2[12]; strmode(p->fts_statp->st_mode, m1); strmode((p->fts_statp->st_mode & S_IFMT) | newmode, m2); printf(": 0%o [%s] -> 0%o [%s]", p->fts_statp->st_mode, m1, (p->fts_statp->st_mode & S_IFMT) | newmode, m2); } printf("\n"); } } if (errno) err(1, "fts_read"); exit(rval); }
int main(int argc, char *argv[]) { FILE *in=NULL,*out=NULL; char *infile=NULL,*outfile=NULL,*keystr=NULL; RC4_KEY key; char buf[BUFSIZ]; int badops=0,i; char **pp; unsigned char md[MD5_DIGEST_LENGTH]; argc--; argv++; while (argc >= 1) { if (strcmp(*argv,"-in") == 0) { if (--argc < 1) goto bad; infile= *(++argv); } else if (strcmp(*argv,"-out") == 0) { if (--argc < 1) goto bad; outfile= *(++argv); } else if (strcmp(*argv,"-key") == 0) { if (--argc < 1) goto bad; keystr= *(++argv); } else { fprintf(stderr,"unknown option %s\n",*argv); badops=1; break; } argc--; argv++; } if (badops) { bad: for (pp=usage; (*pp != NULL); pp++) fprintf(stderr,"%s",*pp); exit(1); } if (infile == NULL) in=stdin; else { in=fopen(infile,"r"); if (in == NULL) { perror("open"); exit(1); } } if (outfile == NULL) out=stdout; else { out=fopen(outfile,"w"); if (out == NULL) { perror("open"); exit(1); } } #ifdef OPENSSL_SYS_MSDOS /* This should set the file to binary mode. */ { #include <fcntl.h> setmode(fileno(in),O_BINARY); setmode(fileno(out),O_BINARY); } #endif if (keystr == NULL) { /* get key */ i=EVP_read_pw_string(buf,BUFSIZ,"Enter RC4 password:"******"bad password read\n"); exit(1); } keystr=buf; } EVP_Digest((unsigned char *)keystr,(unsigned long)strlen(keystr),md,NULL,EVP_md5()); OPENSSL_cleanse(keystr,strlen(keystr)); RC4_set_key(&key,MD5_DIGEST_LENGTH,md); for(;;) { i=fread(buf,1,BUFSIZ,in); if (i == 0) break; if (i < 0) { perror("read"); exit(1); } RC4(&key,(unsigned int)i,(unsigned char *)buf, (unsigned char *)buf); i=fwrite(buf,(unsigned int)i,1,out); if (i != 1) { perror("write"); exit(1); } } fclose(out); fclose(in); exit(0); return(1); }
int main(int argc, char *argv[]) { FTS *ftsp; FTSENT *p; void *set; unsigned long val; int oct; mode_t omode; int Hflag, Lflag, Rflag, ch, fflag, fts_options, hflag, rval, atflags; uid_t uid; gid_t gid; u_int32_t fclear, fset; char *ep, *mode, *cp, *flags; if (strlen(__progname) > 2) { ischown = __progname[2] == 'o'; ischgrp = __progname[2] == 'g'; ischmod = __progname[2] == 'm'; ischflags = __progname[2] == 'f'; } uid = (uid_t)-1; gid = (gid_t)-1; Hflag = Lflag = Rflag = fflag = hflag = 0; while ((ch = getopt(argc, argv, "HLPRXfghorstuwx")) != -1) switch (ch) { case 'H': Hflag = 1; Lflag = 0; break; case 'L': Lflag = 1; Hflag = 0; break; case 'P': Hflag = Lflag = 0; break; case 'R': Rflag = 1; break; case 'f': /* no longer documented. */ fflag = 1; break; case 'h': hflag = 1; break; /* * If this is a symbolic mode argument rather than * an option, we are done with option processing. */ case 'g': case 'o': case 'r': case 's': case 't': case 'u': case 'w': case 'X': case 'x': if (!ischmod) usage(); /* * If getopt() moved past the argument, back up. * If the argument contains option letters before * mode letters, setmode() will catch them. */ if (optind > 1) { cp = argv[optind - 1]; if (cp[strlen(cp) - 1] == ch) --optind; } goto done; default: usage(); } done: argv += optind; argc -= optind; if (argc < 2) usage(); /* * We alter the symlink itself if doing -h or -RP, or * if doing -RH and the symlink wasn't a command line arg. */ atflags = AT_SYMLINK_NOFOLLOW; fts_options = FTS_PHYSICAL; if (Rflag) { if (hflag) errx(1, "the -R and -h options may not be specified together."); if (Hflag) fts_options |= FTS_COMFOLLOW; if (Lflag) { fts_options &= ~FTS_PHYSICAL; fts_options |= FTS_LOGICAL; atflags = 0; } } else if (!hflag) { fts_options |= FTS_COMFOLLOW; atflags = 0; } if (ischflags) { if (pledge("stdio rpath fattr", NULL) == -1) err(1, "pledge"); flags = *argv; if (*flags >= '0' && *flags <= '7') { errno = 0; val = strtoul(flags, &ep, 8); if (val > UINT_MAX) errno = ERANGE; if (errno) err(1, "invalid flags: %s", flags); if (*ep) errx(1, "invalid flags: %s", flags); fset = val; oct = 1; } else { if (strtofflags(&flags, &fset, &fclear)) errx(1, "invalid flag: %s", flags); fclear = ~fclear; oct = 0; } } else if (ischmod) { mode = *argv; if (*mode >= '0' && *mode <= '7') { errno = 0; val = strtoul(mode, &ep, 8); if (val > INT_MAX) errno = ERANGE; if (errno) err(1, "invalid file mode: %s", mode); if (*ep) errx(1, "invalid file mode: %s", mode); omode = val; oct = 1; } else { if ((set = setmode(mode)) == NULL) errx(1, "invalid file mode: %s", mode); oct = 0; } } else if (ischown) { /* Both UID and GID are given. */ if ((cp = strchr(*argv, ':')) != NULL) { *cp++ = '\0'; gid = a_gid(cp); } /* * UID and GID are separated by a dot and UID exists. * required for backwards compatibility pre-dating POSIX.2 * likely to stay here forever */ else if ((cp = strchr(*argv, '.')) != NULL && (uid = a_uid(*argv, 1)) == (uid_t)-1) { *cp++ = '\0'; gid = a_gid(cp); } if (uid == (uid_t)-1) uid = a_uid(*argv, 0); } else gid = a_gid(*argv); if ((ftsp = fts_open(++argv, fts_options, 0)) == NULL) err(1, NULL); for (rval = 0; (p = fts_read(ftsp)) != NULL;) { switch (p->fts_info) { case FTS_D: if (!Rflag) fts_set(ftsp, p, FTS_SKIP); if (ischmod) break; else continue; case FTS_DNR: /* Warn, chmod, continue. */ warnc(p->fts_errno, "%s", p->fts_path); rval = 1; break; case FTS_DP: /* Already changed at FTS_D. */ if (ischmod) continue; else break; case FTS_ERR: /* Warn, continue. */ case FTS_NS: warnc(p->fts_errno, "%s", p->fts_path); rval = 1; continue; case FTS_SL: /* Ignore. */ case FTS_SLNONE: /* * The only symlinks that end up here are ones that * don't point to anything or that loop and ones * that we found doing a physical walk. */ if (!hflag && (fts_options & FTS_LOGICAL)) continue; break; default: break; } /* * For -RH, the decision of how to handle symlinks depends * on the level: follow it iff it's a command line arg. */ if (fts_options & FTS_COMFOLLOW) { atflags = p->fts_level == FTS_ROOTLEVEL ? 0 : AT_SYMLINK_NOFOLLOW; } if (ischmod) { if (!fchmodat(AT_FDCWD, p->fts_accpath, oct ? omode : getmode(set, p->fts_statp->st_mode), atflags) || fflag) continue; } else if (!ischflags) { if (!fchownat(AT_FDCWD, p->fts_accpath, uid, gid, atflags) || fflag) continue; } else { if (!chflagsat(AT_FDCWD, p->fts_accpath, oct ? fset : (p->fts_statp->st_flags | fset) & fclear, atflags)) continue; } /* error case */ warn("%s", p->fts_path); rval = 1; } if (errno) err(1, "fts_read"); fts_close(ftsp); return (rval); }
int main(int argc, char *argv[]) { FILE *fp_rd = stdin; FILE *fp_wr = stdout; FILE *fp_al = NULL; BOOL raw = TRUE; BOOL alpha = FALSE; int argi; for (argi = 1; argi < argc; argi++) { if (argv[argi][0] == '-') { switch (argv[argi][1]) { case 'n': raw = FALSE; break; case 'r': raw = TRUE; break; case 'a': alpha = TRUE; argi++; if ((fp_al = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNM2PNG\n"); fprintf (stderr, "Error: can not create alpha-channel file %s\n", argv[argi]); exit (1); } break; case 'h': case '?': usage(); exit(0); break; default: fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unknown option %s\n", argv[argi]); usage(); exit(1); break; } /* end switch */ } else if (fp_rd == stdin) { if ((fp_rd = fopen (argv[argi], "rb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: file %s does not exist\n", argv[argi]); exit (1); } } else if (fp_wr == stdout) { if ((fp_wr = fopen (argv[argi], "wb")) == NULL) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: can not create file %s\n", argv[argi]); exit (1); } } else { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: too many parameters\n"); usage(); exit(1); } } /* end for */ #ifdef __TURBOC__ /* set stdin/stdout if required to binary */ if (fp_rd == stdin) { setmode (STDIN, O_BINARY); } if ((raw) && (fp_wr == stdout)) { setmode (STDOUT, O_BINARY); } #endif /* call the conversion program itself */ if (png2pnm (fp_rd, fp_wr, fp_al, raw, alpha) == FALSE) { fprintf (stderr, "PNG2PNM\n"); fprintf (stderr, "Error: unsuccessful convertion of PNG-image\n"); exit(1); } /* close input file */ fclose (fp_rd); /* close output file */ fclose (fp_wr); /* close alpha file */ if (alpha) fclose (fp_al); return 0; }
void CharsetFold ( CSphIndex * pIndex, FILE * fp ) { CSphVector<BYTE> sBuf1 ( 16384 ); CSphVector<BYTE> sBuf2 ( 16384 ); bool bUtf = pIndex->GetTokenizer()->IsUtf8(); if ( !bUtf ) sphDie ( "sorry, --fold vs SBCS is not supported just yet" ); CSphLowercaser tLC = pIndex->GetTokenizer()->GetLowercaser(); #if USE_WINDOWS setmode ( fileno(stdout), O_BINARY ); #endif int iBuf1 = 0; // how many leftover bytes from previous iteration while ( !feof(fp) ) { int iGot = fread ( sBuf1.Begin()+iBuf1, 1, sBuf1.GetLength()-iBuf1, fp ); if ( iGot<0 ) sphDie ( "read error: %s", strerror(errno) ); if ( iGot==0 ) if ( feof(fp) ) if ( iBuf1==0 ) break; const BYTE * pIn = sBuf1.Begin(); const BYTE * pInMax = pIn + iBuf1 + iGot; if ( pIn==pInMax && feof(fp) ) break; // tricky bit // on full buffer, and not an eof, terminate a bit early // to avoid codepoint vs buffer boundary issue if ( ( iBuf1+iGot )==sBuf1.GetLength() && iGot!=0 ) pInMax -= 16; // do folding BYTE * pOut = sBuf2.Begin(); BYTE * pOutMax = pOut + sBuf2.GetLength() - 16; while ( pIn < pInMax ) { int iCode = sphUTF8Decode ( pIn ); if ( iCode==0 ) pIn++; // decoder does not do that! assert ( iCode>=0 ); if ( iCode!=0x09 && iCode!=0x0A && iCode!=0x0D ) { iCode = tLC.ToLower ( iCode ) & 0xffffffUL; if ( !iCode ) iCode = 0x20; } pOut += sphUTF8Encode ( pOut, iCode ); if ( pOut>=pOutMax ) { fwrite ( sBuf2.Begin(), 1, pOut-sBuf2.Begin(), stdout ); pOut = sBuf2.Begin(); } } fwrite ( sBuf2.Begin(), 1, pOut-sBuf2.Begin(), stdout ); // now move around leftovers BYTE * pRealEnd = sBuf1.Begin() + iBuf1 + iGot; if ( pIn < pRealEnd ) { iBuf1 = pRealEnd - pIn; memmove ( sBuf1.Begin(), pIn, iBuf1 ); } } }
int main(int argc, char **argv) { int k, ec=0; FILE *f=NULL; bfspace *p=NULL; ip *i=NULL; cell w,h; int ssize = DEFAULT_STACK_SIZE; int sssize = DEFAULT_STACKSTACK_SIZE; global_argv = argv; global_argc = argc; if (argc < 2) usage(); fungeprog_arg = -1; for(k=1; k<argc; k++) { #ifndef FBBI_MINIMAL if((!strcmp(argv[k], "-F")) || (!strcmp(argv[k], "-not-fast")) || (!strcmp(argv[k], "--not-fast"))) fast=0; if((!strcmp(argv[k], "-f")) || (!strcmp(argv[k], "-fast")) || (!strcmp(argv[k], "--fast"))) fast=1; if((!strcmp(argv[k], "-w")) || (!strcmp(argv[k], "-warn")) || (!strcmp(argv[k], "--warn"))) warn=1; if((!strcmp(argv[k], "-t")) || (!strcmp(argv[k], "-trace")) || (!strcmp(argv[k], "--trace"))) trace=1; if((!strcmp(argv[k], "-s")) || (!strcmp(argv[k], "-script")) || (!strcmp(argv[k], "--script"))) script = 1; if((!strcmp(argv[k], "-u")) || (!strcmp(argv[k], "-unefunge")) || (!strcmp(argv[k], "--unefunge"))) une = 1; if((!strcmp(argv[k], "-93")) || (!strcmp(argv[k], "-befunge93")) || (!strcmp(argv[k], "--befunge-93")) || (!strcmp(argv[k], "--befunge93"))) b93 = 1; if((!strcmp(argv[k], "-mc")) || (!strcmp(argv[k], "-maxcells")) || (!strcmp(argv[k], "--max-cells")) || (!strcmp(argv[k], "--maxcells"))) { ssize = atoi(argv[++k]); } else if((!strcmp(argv[k], "-ms")) || (!strcmp(argv[k], "-maxstacks")) || (!strcmp(argv[k], "--max-stacks")) || (!strcmp(argv[k], "--maxstacks"))) { sssize = atoi(argv[++k]); } else #endif if(argv[k][0] != '-') { fungeprog_arg = k; break; } } if (fungeprog_arg == -1) usage(); /* initialize */ srand(time(0)); DEBUG("Allocating Funge-Space"); if ((p = bfspace_alloc(NULL)) != NULL) { DEBUG("Allocating IP"); if ((i = ip_alloc(p, ssize, sssize)) != NULL) { DEBUG("Opening Source File"); if ((f=fopen(argv[fungeprog_arg],"r")) != NULL) { #ifdef FBBI_MSDOS #ifndef FBBI_ANSI setmode(fileno(f), O_BINARY); #endif #endif DEBUG("Reading Source File"); if (bfspace_fread(i->bs, f, 0, 0, &w, &h, 0)) { fclose(f); #ifndef FBBI_MINIMAL if ((w > 79) || (h > 24)) { if(b93 && warn) fprintf(stderr, "fbbi warning: " "source too large for Befunge-93-Space (%ld x %ld)\n", w+1, h+1); } if (h >= 1) { if(une && warn) fprintf(stderr, "fbbi warning: " "source too large for Unefunge-98-Space (%ld x %ld)\n", w+1, h+1); } if (script) { while (bfspace_fetch(i->bs, 0, i->y) == ((long)0 | (long)'#')) i->y++; } #endif DEBUG("* Begin Interpret *"); while (!i->hm) { DEBUG("Moving IP"); ip_move(i); #ifndef FBBI_MINIMAL if(bpt && i->x == bx && i->y == by) trace=1; #endif DEBUG("Getting Instruction"); i->ir = bfspace_fetch(i->bs, i->x, i->y); #ifndef FBBI_MINIMAL if (b93 && ((i->x < 0) || (i->y < 0) || (i->x > 79) || (i->y > 24)) ) { if(warn) fprintf(stderr, "fbbi warning: " "beyond Befunge-93-Space at (%ld,%ld)\n", i->x, i->y); } if (trace) { perform_trace(i); if (i->hm) break; } #endif DEBUG("Executing Instruction"); if (i->sm && ((char)i->ir != '"')) { ip_push(i, i->ir); } else { if ((i->ir < 32) || (i->ir > 126)) { fi_unimp(i); } else { #ifndef FBBI_MINIMAL if(b93) b93instable[(char)i->ir-32](i); else #endif instable[(char)i->ir-32](i); } } } DEBUG("* End Interpret *"); ec = (int)i->ec; DEBUG("Freeing IP"); ip_free(i); DEBUG("Freeing Funge-Space"); bfspace_free(p); } else { DEBUG("Freeing IP"); ip_free(i); DEBUG("Freeing Funge-Space"); bfspace_free(p); fclose(f); #ifndef FBBI_MINIMAL fprintf(stderr, "fbbi error: can't load file\n"); #endif exit(1); } } else { DEBUG("Freeing IP"); ip_free(i); DEBUG("Freeing Funge-Space"); bfspace_free(p); #ifndef FBBI_MINIMAL fprintf(stderr, "fbbi error: can't open file\n"); #endif exit(1); } } else { DEBUG("Freeing Funge-Space"); bfspace_free(p); #ifndef FBBI_MINIMAL fprintf(stderr, "fbbi error: can't allocate ip\n"); #endif exit(1); } } else { #ifndef FBBI_MINIMAL fprintf(stderr, "fbbi error: can't allocate befunge-space\n"); #endif exit(1); } return ec; }
int sftp_server_main(int argc, char **argv, struct passwd *user_pw) { fd_set *rset, *wset; int in, out, max, ch, skipargs = 0, log_stderr = 0; ssize_t len, olen, set_size; SyslogFacility log_facility = SYSLOG_FACILITY_AUTH; char *cp, buf[4*4096]; const char *errmsg; mode_t mask; extern char *optarg; extern char *__progname; __progname = ssh_get_progname(argv[0]); log_init(__progname, log_level, log_facility, log_stderr); fake_permissions = 0; while (!skipargs && (ch = getopt(argc, argv, "f:l:u:cehRU")) != -1) { switch (ch) { case 'R': readonly = 1; break; case 'c': /* * Ignore all arguments if we are invoked as a * shell using "sftp-server -c command" */ skipargs = 1; break; case 'e': log_stderr = 1; break; case 'l': log_level = log_level_number(optarg); if (log_level == SYSLOG_LEVEL_NOT_SET) error("Invalid log level \"%s\"", optarg); break; case 'f': log_facility = log_facility_number(optarg); if (log_facility == SYSLOG_FACILITY_NOT_SET) error("Invalid log facility \"%s\"", optarg); break; case 'u': mask = (mode_t)strtonum(optarg, 0, 0777, &errmsg); if (errmsg != NULL) fatal("Invalid umask \"%s\": %s", optarg, errmsg); (void)umask(mask); break; case 'U': /* Fake permissions */ fake_permissions = 1; break; case 'h': default: sftp_server_usage(); } } log_init(__progname, log_level, log_facility, log_stderr); if ((cp = getenv("SSH_CONNECTION")) != NULL) { client_addr = xstrdup(cp); if ((cp = strchr(client_addr, ' ')) == NULL) { error("Malformed SSH_CONNECTION variable: \"%s\"", getenv("SSH_CONNECTION")); sftp_server_cleanup_exit(255); } *cp = '\0'; } else client_addr = xstrdup("UNKNOWN"); pw = pwcopy(user_pw); logit("session opened for local user %s from [%s]", pw->pw_name, client_addr); in = STDIN_FILENO; out = STDOUT_FILENO; #ifdef HAVE_CYGWIN setmode(in, O_BINARY); setmode(out, O_BINARY); #endif max = 0; if (in > max) max = in; if (out > max) max = out; buffer_init(&iqueue); buffer_init(&oqueue); set_size = howmany(max + 1, NFDBITS) * sizeof(fd_mask); rset = (fd_set *)xmalloc(set_size); wset = (fd_set *)xmalloc(set_size); for (;;) { memset(rset, 0, set_size); memset(wset, 0, set_size); /* * Ensure that we can read a full buffer and handle * the worst-case length packet it can generate, * otherwise apply backpressure by stopping reads. */ if (buffer_check_alloc(&iqueue, sizeof(buf)) && buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) FD_SET(in, rset); olen = buffer_len(&oqueue); if (olen > 0) FD_SET(out, wset); if (select(max+1, rset, wset, NULL, NULL) < 0) { if (errno == EINTR) continue; error("select: %s", strerror(errno)); sftp_server_cleanup_exit(2); } /* copy stdin to iqueue */ if (FD_ISSET(in, rset)) { len = read(in, buf, sizeof buf); if (len == 0) { debug("read eof"); sftp_server_cleanup_exit(0); } else if (len < 0) { error("read: %s", strerror(errno)); sftp_server_cleanup_exit(1); } else { buffer_append(&iqueue, buf, len); } } /* send oqueue to stdout */ if (FD_ISSET(out, wset)) { len = write(out, buffer_ptr(&oqueue), olen); if (len < 0) { error("write: %s", strerror(errno)); sftp_server_cleanup_exit(1); } else { buffer_consume(&oqueue, len); } } /* * Process requests from client if we can fit the results * into the output buffer, otherwise stop processing input * and let the output queue drain. */ if (buffer_check_alloc(&oqueue, SFTP_MAX_MSG_LENGTH)) process(); } }
static void set_binary_mode(FILE *fp) { #if defined(WIN32) || defined(__WIN32__) setmode(fp == stdout ? 1 : 0, O_BINARY); #endif }
static int file_open(struct archive *a, void *client_data) { struct stat st; struct read_file_data *mine = (struct read_file_data *)client_data; void *buffer; const char *filename = NULL; const wchar_t *wfilename = NULL; int fd; int is_disk_like = 0; #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) off_t mediasize = 0; /* FreeBSD-specific, so off_t okay here. */ #elif defined(__NetBSD__) || defined(__OpenBSD__) struct disklabel dl; #elif defined(__DragonFly__) struct partinfo pi; #endif archive_clear_error(a); if (mine->filename_type == FNT_STDIN) { /* We used to delegate stdin support by * directly calling archive_read_open_fd(a,0,block_size) * here, but that doesn't (and shouldn't) handle the * end-of-file flush when reading stdout from a pipe. * Basically, read_open_fd() is intended for folks who * are willing to handle such details themselves. This * API is intended to be a little smarter for folks who * want easy handling of the common case. */ fd = 0; #if defined(__CYGWIN__) || defined(_WIN32) setmode(0, O_BINARY); #endif filename = ""; } else if (mine->filename_type == FNT_MBS) { filename = mine->filename.m; fd = open(filename, O_RDONLY | O_BINARY | O_CLOEXEC); __archive_ensure_cloexec_flag(fd); if (fd < 0) { archive_set_error(a, errno, "Failed to open '%s'", filename); return (ARCHIVE_FATAL); } } else { #if defined(_WIN32) && !defined(__CYGWIN__) wfilename = mine->filename.w; fd = _wopen(wfilename, O_RDONLY | O_BINARY); if (fd < 0 && errno == ENOENT) { wchar_t *fullpath; fullpath = __la_win_permissive_name_w(wfilename); if (fullpath != NULL) { fd = _wopen(fullpath, O_RDONLY | O_BINARY); free(fullpath); } } if (fd < 0) { archive_set_error(a, errno, "Failed to open '%S'", wfilename); return (ARCHIVE_FATAL); } #else archive_set_error(a, ARCHIVE_ERRNO_MISC, "Unexpedted operation in archive_read_open_filename"); return (ARCHIVE_FATAL); #endif } if (fstat(fd, &st) != 0) { if (mine->filename_type == FNT_WCS) archive_set_error(a, errno, "Can't stat '%S'", wfilename); else archive_set_error(a, errno, "Can't stat '%s'", filename); return (ARCHIVE_FATAL); } /* * Determine whether the input looks like a disk device or a * tape device. The results are used below to select an I/O * strategy: * = "disk-like" devices support arbitrary lseek() and will * support I/O requests of any size. So we get easy skipping * and can cheat on block sizes to get better performance. * = "tape-like" devices require strict blocking and use * specialized ioctls for seeking. * = "socket-like" devices cannot seek at all but can improve * performance by using nonblocking I/O to read "whatever is * available right now". * * Right now, we only specially recognize disk-like devices, * but it should be straightforward to add probes and strategy * here for tape-like and socket-like devices. */ if (S_ISREG(st.st_mode)) { /* Safety: Tell the extractor not to overwrite the input. */ archive_read_extract_set_skip_file(a, st.st_dev, st.st_ino); /* Regular files act like disks. */ is_disk_like = 1; } #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) /* FreeBSD: if it supports DIOCGMEDIASIZE ioctl, it's disk-like. */ else if (S_ISCHR(st.st_mode) && ioctl(fd, DIOCGMEDIASIZE, &mediasize) == 0 && mediasize > 0) { is_disk_like = 1; } #elif defined(__NetBSD__) || defined(__OpenBSD__) /* Net/OpenBSD: if it supports DIOCGDINFO ioctl, it's disk-like. */ else if ((S_ISCHR(st.st_mode) || S_ISBLK(st.st_mode)) && ioctl(fd, DIOCGDINFO, &dl) == 0 && dl.d_partitions[DISKPART(st.st_rdev)].p_size > 0) { is_disk_like = 1; } #elif defined(__DragonFly__) /* DragonFly BSD: if it supports DIOCGPART ioctl, it's disk-like. */ else if (S_ISCHR(st.st_mode) && ioctl(fd, DIOCGPART, &pi) == 0 && pi.media_size > 0) { is_disk_like = 1; } #elif defined(__linux__) /* Linux: All block devices are disk-like. */ else if (S_ISBLK(st.st_mode) && lseek(fd, 0, SEEK_CUR) == 0 && lseek(fd, 0, SEEK_SET) == 0 && lseek(fd, 0, SEEK_END) > 0 && lseek(fd, 0, SEEK_SET) == 0) { is_disk_like = 1; } #endif /* TODO: Add an "is_tape_like" variable and appropriate tests. */ /* Disk-like devices prefer power-of-two block sizes. */ /* Use provided block_size as a guide so users have some control. */ if (is_disk_like) { size_t new_block_size = 64 * 1024; while (new_block_size < mine->block_size && new_block_size < 64 * 1024 * 1024) new_block_size *= 2; mine->block_size = new_block_size; } buffer = malloc(mine->block_size); if (mine == NULL || buffer == NULL) { archive_set_error(a, ENOMEM, "No memory"); free(mine); free(buffer); return (ARCHIVE_FATAL); } mine->buffer = buffer; mine->fd = fd; /* Remember mode so close can decide whether to flush. */ mine->st_mode = st.st_mode; /* Disk-like inputs can use lseek(). */ if (is_disk_like) mine->use_lseek = 1; return (ARCHIVE_OK); }
int main(int argc, char **argv) { int ch, fflag, tflag, status, n; char *targ, **newargv; const char *errstr; extern char *optarg; extern int optind; /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ sanitise_stdfd(); /* Copy argv, because we modify it */ newargv = xcalloc(MAX(argc + 1, 1), sizeof(*newargv)); for (n = 0; n < argc; n++) newargv[n] = xstrdup(argv[n]); argv = newargv; __progname = ssh_get_progname(argv[0]); memset(&args, '\0', sizeof(args)); memset(&remote_remote_args, '\0', sizeof(remote_remote_args)); args.list = remote_remote_args.list = NULL; addargs(&args, "%s", ssh_program); addargs(&args, "-x"); addargs(&args, "-oForwardAgent=no"); addargs(&args, "-oPermitLocalCommand=no"); addargs(&args, "-oClearAllForwardings=yes"); fflag = tflag = 0; while ((ch = getopt(argc, argv, "dfl:prtvBCc:i:P:q12346S:o:F:")) != -1) switch (ch) { /* User-visible flags. */ case '1': case '2': case '4': case '6': case 'C': addargs(&args, "-%c", ch); addargs(&remote_remote_args, "-%c", ch); break; case '3': throughlocal = 1; break; case 'o': case 'c': case 'i': case 'F': addargs(&remote_remote_args, "-%c", ch); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-%c", ch); addargs(&args, "%s", optarg); break; case 'P': addargs(&remote_remote_args, "-p"); addargs(&remote_remote_args, "%s", optarg); addargs(&args, "-p"); addargs(&args, "%s", optarg); break; case 'B': addargs(&remote_remote_args, "-oBatchmode=yes"); addargs(&args, "-oBatchmode=yes"); break; case 'l': limit_kbps = strtonum(optarg, 1, 100 * 1024 * 1024, &errstr); if (errstr != NULL) usage(); limit_kbps *= 1024; /* kbps */ bandwidth_limit_init(&bwlimit, limit_kbps, COPY_BUFLEN); break; case 'p': pflag = 1; break; case 'r': iamrecursive = 1; break; case 'S': ssh_program = xstrdup(optarg); break; case 'v': addargs(&args, "-v"); addargs(&remote_remote_args, "-v"); verbose_mode = 1; break; case 'q': addargs(&args, "-q"); addargs(&remote_remote_args, "-q"); showprogress = 0; break; /* Server options. */ case 'd': targetshouldbedirectory = 1; break; case 'f': /* "from" */ iamremote = 1; fflag = 1; break; case 't': /* "to" */ iamremote = 1; tflag = 1; #ifdef HAVE_CYGWIN setmode(0, O_BINARY); #endif break; default: usage(); } argc -= optind; argv += optind; if ((pwd = getpwuid(userid = getuid())) == NULL) fatal("unknown user %u", (u_int) userid); if (!isatty(STDOUT_FILENO)) showprogress = 0; remin = STDIN_FILENO; remout = STDOUT_FILENO; if (fflag) { /* Follow "protocol", send data. */ (void) response(); source(argc, argv); exit(errs != 0); } if (tflag) { /* Receive data. */ sink(argc, argv); exit(errs != 0); } if (argc < 2) usage(); if (argc > 2) targetshouldbedirectory = 1; remin = remout = -1; do_cmd_pid = -1; /* Command to be executed on remote system using "ssh". */ (void) snprintf(cmd, sizeof cmd, "scp%s%s%s%s", verbose_mode ? " -v" : "", iamrecursive ? " -r" : "", pflag ? " -p" : "", targetshouldbedirectory ? " -d" : ""); (void) signal(SIGPIPE, lostconn); if ((targ = colon(argv[argc - 1]))) /* Dest is remote host. */ toremote(targ, argc, argv); else { if (targetshouldbedirectory) verifydir(argv[argc - 1]); tolocal(argc, argv); /* Dest is local host. */ } /* * Finally check the exit status of the ssh process, if one was forked * and no error has occurred yet */ if (do_cmd_pid != -1 && errs == 0) { if (remin != -1) (void) close(remin); if (remout != -1) (void) close(remout); if (waitpid(do_cmd_pid, &status, 0) == -1) errs = 1; else { if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) errs = 1; } } exit(errs != 0); }
int fbset_main(int argc, char **argv) #endif { struct fb_var_screeninfo var, varset; int fh, i; const char *fbdev = DEFAULTFBDEV; const char *modefile = DEFAULTFBMODE; char *thisarg, *mode = NULL; memset(&varset, 0xFF, sizeof(varset)); /* parse cmd args.... why do they have to make things so difficult? */ argv++; argc--; for (; argc > 0 && (thisarg = *argv); argc--, argv++) { for (i = 0; g_cmdoptions[i].name[0]; i++) { if (strcmp(thisarg, g_cmdoptions[i].name)) continue; if (argc-1 < g_cmdoptions[i].param_count) bb_show_usage(); switch (g_cmdoptions[i].code) { case CMD_FB: fbdev = argv[1]; break; case CMD_DB: modefile = argv[1]; break; case CMD_GEOMETRY: varset.xres = xatou32(argv[1]); varset.yres = xatou32(argv[2]); varset.xres_virtual = xatou32(argv[3]); varset.yres_virtual = xatou32(argv[4]); varset.bits_per_pixel = xatou32(argv[5]); break; case CMD_TIMING: varset.pixclock = xatou32(argv[1]); varset.left_margin = xatou32(argv[2]); varset.right_margin = xatou32(argv[3]); varset.upper_margin = xatou32(argv[4]); varset.lower_margin = xatou32(argv[5]); varset.hsync_len = xatou32(argv[6]); varset.vsync_len = xatou32(argv[7]); break; case CMD_ALL: g_options |= OPT_ALL; break; case CMD_CHANGE: g_options |= OPT_CHANGE; break; #if ENABLE_FEATURE_FBSET_FANCY case CMD_XRES: varset.xres = xatou32(argv[1]); break; case CMD_YRES: varset.yres = xatou32(argv[1]); break; case CMD_DEPTH: varset.bits_per_pixel = xatou32(argv[1]); break; #endif } argc -= g_cmdoptions[i].param_count; argv += g_cmdoptions[i].param_count; break; } if (!g_cmdoptions[i].name[0]) { if (argc != 1) bb_show_usage(); mode = *argv; g_options |= OPT_READMODE; } } fh = xopen(fbdev, O_RDONLY); xioctl(fh, FBIOGET_VSCREENINFO, &var); if (g_options & OPT_READMODE) { if (!readmode(&var, modefile, mode)) { bb_error_msg_and_die("unknown video mode '%s'", mode); } } setmode(&var, &varset); if (g_options & OPT_CHANGE) { if (g_options & OPT_ALL) var.activate = FB_ACTIVATE_ALL; xioctl(fh, FBIOPUT_VSCREENINFO, &var); } showmode(&var); /* Don't close the file, as exiting will take care of that */ /* close(fh); */ return EXIT_SUCCESS; }
// Convert a file from one encoding to another static UBool convertFile(const char *pname, const char *fromcpage, UConverterToUCallback toucallback, const void *touctxt, const char *tocpage, UConverterFromUCallback fromucallback, const void *fromuctxt, int fallback, size_t bufsz, const char *translit, const char *infilestr, FILE * outfile, int verbose) { FILE *infile; UBool ret = TRUE; UConverter *convfrom = 0; UConverter *convto = 0; UErrorCode err = U_ZERO_ERROR; UBool flush; const char *cbufp; char *bufp; char *buf = 0; uint32_t infoffset = 0, outfoffset = 0; /* Where we are in the file, for error reporting. */ const UChar *unibufbp; UChar *unibufp; UChar *unibuf = 0; int32_t *fromoffsets = 0, *tooffsets = 0; size_t rd, wr, tobufsz; #if !UCONFIG_NO_TRANSLITERATION Transliterator *t = 0; // Transliterator acting on Unicode data. #endif UnicodeString u; // String to do the transliteration. // Open the correct input file or connect to stdin for reading input if (infilestr != 0 && strcmp(infilestr, "-")) { infile = fopen(infilestr, "rb"); if (infile == 0) { UnicodeString str1(infilestr, ""); str1.append((UChar32) 0); UnicodeString str2(strerror(errno), ""); str2.append((UChar32) 0); initMsg(pname); u_wmsg(stderr, "cantOpenInputF", str1.getBuffer(), str2.getBuffer()); return FALSE; } } else { infilestr = "-"; infile = stdin; #ifdef WIN32 if (setmode(fileno(stdin), O_BINARY) == -1) { initMsg(pname); u_wmsg(stderr, "cantSetInBinMode"); return FALSE; } #endif } if (verbose) { fprintf(stderr, "%s:\n", infilestr); } #if !UCONFIG_NO_TRANSLITERATION // Create transliterator as needed. if (translit != NULL && *translit) { UParseError parse; UnicodeString str(translit), pestr; /* Create from rules or by ID as needed. */ parse.line = -1; if (uprv_strchr(translit, ':') || uprv_strchr(translit, '>') || uprv_strchr(translit, '<') || uprv_strchr(translit, '>')) { t = Transliterator::createFromRules("Uconv", str, UTRANS_FORWARD, parse, err); } else { t = Transliterator::createInstance(translit, UTRANS_FORWARD, err); } if (U_FAILURE(err)) { str.append((UChar32) 0); initMsg(pname); if (parse.line >= 0) { UChar linebuf[20], offsetbuf[20]; uprv_itou(linebuf, 20, parse.line, 10, 0); uprv_itou(offsetbuf, 20, parse.offset, 10, 0); u_wmsg(stderr, "cantCreateTranslitParseErr", str.getBuffer(), u_wmsg_errorName(err), linebuf, offsetbuf); } else { u_wmsg(stderr, "cantCreateTranslit", str.getBuffer(), u_wmsg_errorName(err)); } if (t) { delete t; t = 0; } goto error_exit; } } #endif // Create codepage converter. If the codepage or its aliases weren't // available, it returns NULL and a failure code. We also set the // callbacks, and return errors in the same way. convfrom = ucnv_open(fromcpage, &err); if (U_FAILURE(err)) { UnicodeString str(fromcpage, (int32_t)(uprv_strlen(fromcpage) + 1)); initMsg(pname); u_wmsg(stderr, "cantOpenFromCodeset", str.getBuffer(), u_wmsg_errorName(err)); goto error_exit; } ucnv_setToUCallBack(convfrom, toucallback, touctxt, 0, 0, &err); if (U_FAILURE(err)) { initMsg(pname); u_wmsg(stderr, "cantSetCallback", u_wmsg_errorName(err)); goto error_exit; } convto = ucnv_open(tocpage, &err); if (U_FAILURE(err)) { UnicodeString str(tocpage, (int32_t)(uprv_strlen(tocpage) + 1)); initMsg(pname); u_wmsg(stderr, "cantOpenToCodeset", str.getBuffer(), u_wmsg_errorName(err)); goto error_exit; } ucnv_setFromUCallBack(convto, fromucallback, fromuctxt, 0, 0, &err); if (U_FAILURE(err)) { initMsg(pname); u_wmsg(stderr, "cantSetCallback", u_wmsg_errorName(err)); goto error_exit; } ucnv_setFallback(convto, fallback); // To ensure that the buffer always is of enough size, we // must take the worst case scenario, that is the character in // the codepage that uses the most bytes and multiply it against // the buffer size. // use bufsz+1 to allow for additional BOM/signature character (U+FEFF) tobufsz = (bufsz+1) * ucnv_getMaxCharSize(convto); buf = new char[tobufsz]; unibuf = new UChar[bufsz]; fromoffsets = new int32_t[bufsz]; tooffsets = new int32_t[tobufsz]; // OK, we can convert now. do { char willexit = 0; rd = fread(buf, 1, bufsz, infile); if (ferror(infile) != 0) { UnicodeString str(strerror(errno)); str.append((UChar32) 0); initMsg(pname); u_wmsg(stderr, "cantRead", str.getBuffer()); goto error_exit; } // Convert the read buffer into the new coding // After the call 'unibufp' will be placed on the last // character that was converted in the 'unibuf'. // Also the 'cbufp' is positioned on the last converted // character. // At the last conversion in the file, flush should be set to // true so that we get all characters converted // // The converter must be flushed at the end of conversion so // that characters on hold also will be written. unibufp = unibuf; cbufp = buf; flush = rd != bufsz; ucnv_toUnicode(convfrom, &unibufp, unibufp + bufsz, &cbufp, cbufp + rd, fromoffsets, flush, &err); infoffset += (uint32_t)(cbufp - buf); if (U_FAILURE(err)) { char pos[32]; sprintf(pos, "%u", infoffset - 1); UnicodeString str(pos, (int32_t)(uprv_strlen(pos) + 1)); initMsg(pname); u_wmsg(stderr, "problemCvtToU", str.getBuffer(), u_wmsg_errorName(err)); willexit = 1; err = U_ZERO_ERROR; /* reset the error for the rest of the conversion. */ } // At the last conversion, the converted characters should be // equal to number of chars read. if (flush && !willexit && cbufp != (buf + rd)) { char pos[32]; sprintf(pos, "%u", infoffset); UnicodeString str(pos, (int32_t)(uprv_strlen(pos) + 1)); initMsg(pname); u_wmsg(stderr, "premEndInput", str.getBuffer()); willexit = 1; } // Prepare to transliterate and convert. Transliterate if needed. #if !UCONFIG_NO_TRANSLITERATION if (t) { u.setTo(unibuf, (int32_t)(unibufp - unibuf)); // Copy into string. t->transliterate(u); } else #endif { u.setTo(unibuf, (int32_t)(unibufp - unibuf), (int32_t)(bufsz)); // Share the buffer. } int32_t ulen = u.length(); // Convert the Unicode buffer into the destination codepage // Again 'bufp' will be placed on the last converted character // And 'unibufbp' will be placed on the last converted unicode character // At the last conversion flush should be set to true to ensure that // all characters left get converted const UChar *unibufu = unibufbp = u.getBuffer(); do { int32_t len = ulen > (int32_t)bufsz ? (int32_t)bufsz : ulen; bufp = buf; unibufp = (UChar *) (unibufbp + len); ucnv_fromUnicode(convto, &bufp, bufp + tobufsz, &unibufbp, unibufp, tooffsets, flush, &err); if (U_FAILURE(err)) { const char *errtag; char pos[32]; uint32_t erroffset = dataOffset((int32_t)(bufp - buf - 1), fromoffsets, (int32_t)(bufsz), tooffsets, (int32_t)(tobufsz)); int32_t ferroffset = (int32_t)(infoffset - (unibufp - unibufu) + erroffset); if ((int32_t) ferroffset < 0) { ferroffset = (int32_t)(outfoffset + (bufp - buf)); errtag = "problemCvtFromUOut"; } else { errtag = "problemCvtFromU"; } sprintf(pos, "%u", ferroffset); UnicodeString str(pos, (int32_t)(uprv_strlen(pos) + 1)); initMsg(pname); u_wmsg(stderr, errtag, str.getBuffer(), u_wmsg_errorName(err)); willexit = 1; } // At the last conversion, the converted characters should be equal to number // of consumed characters. if (flush && !willexit && unibufbp != (unibufu + (size_t) (unibufp - unibufu))) { char pos[32]; sprintf(pos, "%u", infoffset); UnicodeString str(pos, (int32_t)(uprv_strlen(pos) + 1)); initMsg(pname); u_wmsg(stderr, "premEnd", str.getBuffer()); willexit = 1; } // Finally, write the converted buffer to the output file rd = (size_t) (bufp - buf); outfoffset += (int32_t)(wr = fwrite(buf, 1, rd, outfile)); if (wr != rd) { UnicodeString str(strerror(errno), ""); initMsg(pname); u_wmsg(stderr, "cantWrite", str.getBuffer()); willexit = 1; } if (willexit) { goto error_exit; } } while ((ulen -= (int32_t)(bufsz)) > 0); } while (!flush); // Stop when we have flushed the // converters (this means that it's // the end of output) goto normal_exit; error_exit: ret = FALSE; normal_exit: // Cleanup. if (convfrom) ucnv_close(convfrom); if (convto) ucnv_close(convto); #if !UCONFIG_NO_TRANSLITERATION if (t) delete t; #endif if (buf) delete[] buf; if (unibuf) delete[] unibuf; if (fromoffsets) delete[] fromoffsets; if (tooffsets) delete[] tooffsets; if (infile != stdin) { fclose(infile); } return ret; }
int main(int argc, char *argv[]) { int ch, exitval, success, pflag; mode_t omode, *set = (mode_t *)NULL; char *mode; pflag = 0; mode = NULL; while ((ch = getopt(argc, argv, "m:pv")) != -1) switch(ch) { case 'm': mode = optarg; break; case 'p': pflag = 1; break; case 'v': vflag = 1; break; case '?': default: usage(); } // argc -= optind; argv += optind; if (argv[0] == NULL) usage(); if (mode == NULL) { omode = S_IRWXU | S_IRWXG | S_IRWXO; } else { if ((set = setmode(mode)) == NULL) errx(1, "invalid file mode: %s", mode); omode = getmode(set, S_IRWXU | S_IRWXG | S_IRWXO); free(set); } for (exitval = 0; *argv != NULL; ++argv) { success = 1; if (pflag) { int status = mkpath_np(*argv, omode); if (status && status != EEXIST) { warnc(status, "%s", *argv); success = 0; } } else if (mkdir(*argv, omode) < 0) { if (errno == ENOTDIR || errno == ENOENT) warn("%s", dirname(*argv)); else warn("%s", *argv); success = 0; } else if (vflag) (void)printf("mkdir: created directory '%s'\n", *argv); if (!success) exitval = 1; /* * The mkdir() and umask() calls both honor only the low * nine bits, so if you try to set a mode including the * sticky, setuid, setgid bits you lose them. Don't do * this unless the user has specifically requested a mode, * as chmod will (obviously) ignore the umask. */ if (success && mode != NULL && chmod(*argv, omode) == -1) { warn("%s", *argv); exitval = 1; } } exit(exitval); }
int main(int argc, char **argv) { FILE *outfile; int ret = 0; int seenf = 0; size_t bufsz = DEFAULT_BUFSZ; const char *fromcpage = 0; const char *tocpage = 0; const char *translit = 0; const char *outfilestr = 0; int fallback = 0; UConverterFromUCallback fromucallback = UCNV_FROM_U_CALLBACK_STOP; const void *fromuctxt = 0; UConverterToUCallback toucallback = UCNV_TO_U_CALLBACK_STOP; const void *touctxt = 0; char **iter; char **end = argv + argc; const char *pname; int printConvs = 0, printCanon = 0; const char *printName = 0; int printTranslits = 0; int verbose = 0; // Get and prettify pname. pname = uprv_strrchr(*argv, U_FILE_SEP_CHAR); #ifdef WIN32 if (!pname) { pname = uprv_strrchr(*argv, '/'); } #endif if (!pname) { pname = *argv; } else { ++pname; } // First, get the arguments from command-line // to know the codepages to convert between // XXX When you add to this loop, you need to add to the similar loop // below. for (iter = argv + 1; iter != end; iter++) { // Check for from charset if (strcmp("-f", *iter) == 0 || !strcmp("--from-code", *iter)) { iter++; if (iter != end) fromcpage = *iter; else usage(pname, 1); } else if (strcmp("-t", *iter) == 0 || !strcmp("--to-code", *iter)) { iter++; if (iter != end) tocpage = *iter; else usage(pname, 1); } else if (strcmp("-x", *iter) == 0) { iter++; if (iter != end) translit = *iter; else usage(pname, 1); } else if (!strcmp("--fallback", *iter)) { fallback = 1; } else if (!strcmp("--no-fallback", *iter)) { fallback = 0; } else if (strcmp("-b", *iter) == 0 || !strcmp("--block-size", *iter)) { iter++; if (iter != end) { bufsz = atoi(*iter); if ((int) bufsz <= 0) { initMsg(pname); UnicodeString str(*iter); initMsg(pname); u_wmsg(stderr, "badBlockSize", str.getBuffer()); return 3; } } else { usage(pname, 1); } } else if (strcmp("-l", *iter) == 0 || !strcmp("--list", *iter)) { if (printTranslits) { usage(pname, 1); } printConvs = 1; } else if (strcmp("--default-code", *iter) == 0) { if (printTranslits) { usage(pname, 1); } printName = ucnv_getDefaultName(); } else if (strcmp("--list-code", *iter) == 0) { if (printTranslits) { usage(pname, 1); } iter++; if (iter != end) { UErrorCode e = U_ZERO_ERROR; printName = ucnv_getAlias(*iter, 0, &e); if (U_FAILURE(e) || !printName) { UnicodeString str(*iter); initMsg(pname); u_wmsg(stderr, "noSuchCodeset", str.getBuffer()); return 2; } } else usage(pname, 1); } else if (strcmp("--canon", *iter) == 0) { printCanon = 1; } else if (strcmp("-L", *iter) == 0 || !strcmp("--list-transliterators", *iter)) { if (printConvs) { usage(pname, 1); } printTranslits = 1; } else if (strcmp("-h", *iter) == 0 || !strcmp("-?", *iter) || !strcmp("--help", *iter)) { usage(pname, 0); } else if (!strcmp("-c", *iter)) { fromucallback = UCNV_FROM_U_CALLBACK_SKIP; } else if (!strcmp("--to-callback", *iter)) { iter++; if (iter != end) { const struct callback_ent *cbe = findCallback(*iter); if (cbe) { fromucallback = cbe->fromu; fromuctxt = cbe->fromuctxt; } else { UnicodeString str(*iter); initMsg(pname); u_wmsg(stderr, "unknownCallback", str.getBuffer()); return 4; } } else { usage(pname, 1); } } else if (!strcmp("--from-callback", *iter)) { iter++; if (iter != end) { const struct callback_ent *cbe = findCallback(*iter); if (cbe) { toucallback = cbe->tou; touctxt = cbe->touctxt; } else { UnicodeString str(*iter); initMsg(pname); u_wmsg(stderr, "unknownCallback", str.getBuffer()); return 4; } } else { usage(pname, 1); } } else if (!strcmp("-i", *iter)) { toucallback = UCNV_TO_U_CALLBACK_SKIP; } else if (!strcmp("--callback", *iter)) { iter++; if (iter != end) { const struct callback_ent *cbe = findCallback(*iter); if (cbe) { fromucallback = cbe->fromu; fromuctxt = cbe->fromuctxt; toucallback = cbe->tou; touctxt = cbe->touctxt; } else { UnicodeString str(*iter); initMsg(pname); u_wmsg(stderr, "unknownCallback", str.getBuffer()); return 4; } } else { usage(pname, 1); } } else if (!strcmp("-s", *iter) || !strcmp("--silent", *iter)) { verbose = 0; } else if (!strcmp("-v", *iter) || !strcmp("--verbose", *iter)) { verbose = 1; } else if (!strcmp("-V", *iter) || !strcmp("--version", *iter)) { printf("%s v2.0\n", pname); return 0; } else if (!strcmp("-o", *iter) || !strcmp("--output", *iter)) { ++iter; if (iter != end && !outfilestr) { outfilestr = *iter; } else { usage(pname, 1); } } else if (**iter == '-' && (*iter)[1]) { usage(pname, 1); } } if (printConvs || printName) { return printConverters(pname, printName, printCanon) ? 2 : 0; } else if (printTranslits) { return printTransliterators(printCanon) ? 3 : 0; } if (!fromcpage || !uprv_strcmp(fromcpage, "-")) { fromcpage = ucnv_getDefaultName(); } if (!tocpage || !uprv_strcmp(tocpage, "-")) { tocpage = ucnv_getDefaultName(); } // Open the correct output file or connect to stdout for reading input if (outfilestr != 0 && strcmp(outfilestr, "-")) { outfile = fopen(outfilestr, "wb"); if (outfile == 0) { UnicodeString str1(outfilestr, ""); UnicodeString str2(strerror(errno), ""); initMsg(pname); u_wmsg(stderr, "cantCreateOutputF", str1.getBuffer(), str2.getBuffer()); return 1; } } else { outfilestr = "-"; outfile = stdout; #ifdef WIN32 if (setmode(fileno(outfile), O_BINARY) == -1) { u_wmsg(stderr, "cantSetOutBinMode"); exit(-1); } #endif } /* Loop again on the arguments to find all the input files, and convert them. XXX Cheap and sloppy. */ for (iter = argv + 1; iter != end; iter++) { if (strcmp("-f", *iter) == 0 || !strcmp("--from-code", *iter)) { iter++; } else if (strcmp("-t", *iter) == 0 || !strcmp("--to-code", *iter)) { iter++; } else if (strcmp("-x", *iter) == 0) { iter++; } else if (!strcmp("--fallback", *iter)) { ; } else if (!strcmp("--no-fallback", *iter)) { ; } else if (strcmp("-b", *iter) == 0 || !strcmp("--block-size", *iter)) { iter++; } else if (strcmp("-l", *iter) == 0 || !strcmp("--list", *iter)) { ; } else if (strcmp("--default-code", *iter) == 0) { ; } else if (strcmp("--list-code", *iter) == 0) { ; } else if (strcmp("--canon", *iter) == 0) { ; } else if (strcmp("-L", *iter) == 0 || !strcmp("--list-transliterators", *iter)) { ; } else if (strcmp("-h", *iter) == 0 || !strcmp("-?", *iter) || !strcmp("--help", *iter)) { ; } else if (!strcmp("-c", *iter)) { ; } else if (!strcmp("--to-callback", *iter)) { iter++; } else if (!strcmp("--from-callback", *iter)) { iter++; } else if (!strcmp("-i", *iter)) { ; } else if (!strcmp("--callback", *iter)) { iter++; } else if (!strcmp("-s", *iter) || !strcmp("--silent", *iter)) { ; } else if (!strcmp("-v", *iter) || !strcmp("--verbose", *iter)) { ; } else if (!strcmp("-V", *iter) || !strcmp("--version", *iter)) { ; } else if (!strcmp("-o", *iter) || !strcmp("--output", *iter)) { ++iter; } else { seenf = 1; if (!convertFile (pname, fromcpage, toucallback, touctxt, tocpage, fromucallback, fromuctxt, fallback, bufsz, translit, *iter, outfile, verbose)) { goto error_exit; } } } if (!seenf) { if (!convertFile (pname, fromcpage, toucallback, touctxt, tocpage, fromucallback, fromuctxt, fallback, bufsz, translit, 0, outfile, verbose)) { goto error_exit; } } goto normal_exit; error_exit: ret = 1; normal_exit: if (outfile != stdout) fclose(outfile); return ret; }
static void initialize_mousetype(SCREEN *sp) { T((T_CALLED("initialize_mousetype()"))); /* Try gpm first, because gpm may be configured to run in xterm */ #if USE_GPM_SUPPORT if (allow_gpm_mouse()) { if (!sp->_mouse_gpm_loaded) { #ifdef HAVE_LIBDL load_gpm_library(sp); #else /* !HAVE_LIBDL */ sp->_mouse_gpm_found = TRUE; sp->_mouse_gpm_loaded = TRUE; #endif } /* * The gpm_fd file-descriptor may be negative (xterm). So we have to * maintain our notion of whether the mouse connection is active * without testing the file-descriptor. */ if (sp->_mouse_gpm_found && enable_gpm_mouse(sp, TRUE)) { sp->_mouse_type = M_GPM; sp->_mouse_fd = *(my_gpm_fd); T(("GPM mouse_fd %d", sp->_mouse_fd)); returnVoid; } } #endif /* USE_GPM_SUPPORT */ /* OS/2 VIO */ #if USE_EMX_MOUSE if (!sp->_emxmouse_thread && strstr(TerminalOf(sp)->type.term_names, "xterm") == 0 && key_mouse) { int handles[2]; if (pipe(handles) < 0) { perror("mouse pipe error"); returnVoid; } else { int rc; if (!sp->_emxmouse_buttons[0]) { char *s = getenv("MOUSE_BUTTONS_123"); sp->_emxmouse_buttons[0] = 1; if (s && strlen(s) >= 3) { sp->_emxmouse_buttons[1] = s[0] - '0'; sp->_emxmouse_buttons[2] = s[1] - '0'; sp->_emxmouse_buttons[3] = s[2] - '0'; } else { sp->_emxmouse_buttons[1] = 1; sp->_emxmouse_buttons[2] = 3; sp->_emxmouse_buttons[3] = 2; } } sp->_emxmouse_wfd = handles[1]; M_FD(sp) = handles[0]; /* Needed? */ setmode(handles[0], O_BINARY); setmode(handles[1], O_BINARY); /* Do not use CRT functions, we may single-threaded. */ rc = DosCreateThread((unsigned long *) &sp->_emxmouse_thread, mouse_server, (long) sp, 0, 8192); if (rc) { printf("mouse thread error %d=%#x", rc, rc); } else { sp->_mouse_type = M_XTERM; } returnVoid; } } #endif /* USE_EMX_MOUSE */ #if USE_SYSMOUSE { struct mouse_info the_mouse; char *the_device = 0; if (isatty(sp->_ifd)) the_device = ttyname(sp->_ifd); if (the_device == 0) the_device = "/dev/tty"; sp->_mouse_fd = open(the_device, O_RDWR); if (sp->_mouse_fd >= 0) { /* * sysmouse does not have a usable user interface for obtaining * mouse events. The logical way to proceed (reading data on a * stream) only works if one opens the device as root. Even in * that mode, careful examination shows we lose events * occasionally. The interface provided for user programs is to * establish a signal handler. really. * * Take over SIGUSR2 for this purpose since SIGUSR1 is more * likely to be used by an application. getch() will have to * handle the misleading EINTR's. */ signal(SIGUSR2, SIG_IGN); the_mouse.operation = MOUSE_MODE; the_mouse.u.mode.mode = 0; the_mouse.u.mode.signal = SIGUSR2; if (ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse) != -1) { signal(SIGUSR2, handle_sysmouse); the_mouse.operation = MOUSE_SHOW; ioctl(sp->_mouse_fd, CONS_MOUSECTL, &the_mouse); #if defined(FBIO_MODEINFO) || defined(CONS_MODEINFO) /* FreeBSD > 2.x */ { #ifndef FBIO_GETMODE /* FreeBSD 3.x */ #define FBIO_GETMODE CONS_GET #define FBIO_MODEINFO CONS_MODEINFO #endif /* FBIO_GETMODE */ video_info_t the_video; if (ioctl(sp->_mouse_fd, FBIO_GETMODE, &the_video.vi_mode) != -1 && ioctl(sp->_mouse_fd, FBIO_MODEINFO, &the_video) != -1) { sp->_sysmouse_char_width = the_video.vi_cwidth; sp->_sysmouse_char_height = the_video.vi_cheight; } } #endif /* defined(FBIO_MODEINFO) || defined(CONS_MODEINFO) */ if (sp->_sysmouse_char_width <= 0) sp->_sysmouse_char_width = 8; if (sp->_sysmouse_char_height <= 0) sp->_sysmouse_char_height = 16; sp->_mouse_type = M_SYSMOUSE; returnVoid; } } } #endif /* USE_SYSMOUSE */ #ifdef USE_TERM_DRIVER CallDriver(sp, initmouse); #else /* we know how to recognize mouse events under "xterm" */ if (key_mouse != 0) { if (!strcmp(key_mouse, xterm_kmous) || strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) { init_xterm_mouse(sp); } } else if (strstr(TerminalOf(sp)->type.term_names, "xterm") != 0) { if (_nc_add_to_try(&(sp->_keytry), xterm_kmous, KEY_MOUSE) == OK) init_xterm_mouse(sp); } #endif returnVoid; }
int pipe2 (int fd[2], int flags) { /* Mingw _pipe() corrupts fd on failure; also, if we succeed at creating the pipe but later fail at changing fcntl, we want to leave fd unchanged: http://austingroupbugs.net/view.php?id=467 */ int tmp[2]; tmp[0] = fd[0]; tmp[1] = fd[1]; #if HAVE_PIPE2 # undef pipe2 /* Try the system call first, if it exists. (We may be running with a glibc that has the function but with an older kernel that lacks it.) */ { /* Cache the information whether the system call really exists. */ static int have_pipe2_really; /* 0 = unknown, 1 = yes, -1 = no */ if (have_pipe2_really >= 0) { int result = pipe2 (fd, flags); if (!(result < 0 && errno == ENOSYS)) { have_pipe2_really = 1; return result; } have_pipe2_really = -1; } } #endif /* Check the supported flags. */ if ((flags & ~(O_CLOEXEC | O_NONBLOCK | O_BINARY | O_TEXT)) != 0) { errno = EINVAL; return -1; } #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__ /* Native Woe32 API. */ if (_pipe (fd, 4096, flags & ~O_NONBLOCK) < 0) { fd[0] = tmp[0]; fd[1] = tmp[1]; return -1; } /* O_NONBLOCK handling. On native Windows platforms, O_NONBLOCK is defined by gnulib. Use the functions defined by the gnulib module 'nonblocking'. */ # if GNULIB_defined_O_NONBLOCK if (flags & O_NONBLOCK) { if (set_nonblocking_flag (fd[0], true) != 0 || set_nonblocking_flag (fd[1], true) != 0) goto fail; } # else { verify (O_NONBLOCK == 0); } # endif return 0; #else /* Unix API. */ if (pipe (fd) < 0) return -1; /* POSIX <http://www.opengroup.org/onlinepubs/9699919799/functions/pipe.html> says that initially, the O_NONBLOCK and FD_CLOEXEC flags are cleared on both fd[0] and fd[1]. */ /* O_NONBLOCK handling. On Unix platforms, O_NONBLOCK is defined by the system. Use fcntl(). */ if (flags & O_NONBLOCK) { int fcntl_flags; if ((fcntl_flags = fcntl (fd[1], F_GETFL, 0)) < 0 || fcntl (fd[1], F_SETFL, fcntl_flags | O_NONBLOCK) == -1 || (fcntl_flags = fcntl (fd[0], F_GETFL, 0)) < 0 || fcntl (fd[0], F_SETFL, fcntl_flags | O_NONBLOCK) == -1) goto fail; } if (flags & O_CLOEXEC) { int fcntl_flags; if ((fcntl_flags = fcntl (fd[1], F_GETFD, 0)) < 0 || fcntl (fd[1], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1 || (fcntl_flags = fcntl (fd[0], F_GETFD, 0)) < 0 || fcntl (fd[0], F_SETFD, fcntl_flags | FD_CLOEXEC) == -1) goto fail; } # if O_BINARY if (flags & O_BINARY) { setmode (fd[1], O_BINARY); setmode (fd[0], O_BINARY); } else if (flags & O_TEXT) { setmode (fd[1], O_TEXT); setmode (fd[0], O_TEXT); } # endif return 0; #endif #if GNULIB_defined_O_NONBLOCK || \ !((defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__) fail: { int saved_errno = errno; close (fd[0]); close (fd[1]); fd[0] = tmp[0]; fd[1] = tmp[1]; errno = saved_errno; return -1; } #endif }
int main(int argc, char** argv) { size_t _i = 0, _j = 0; size_t _read_len = 0; char *_file_in = NULL, *_file_out = NULL, *_file_k = NULL; int _op = 0; FILE *_f_in = stdin, *_f_out = stdout, *_f_k = NULL; do_block _b[OAES_THREADS]; fprintf( stderr, "\n" "*******************************************************************************\n" "* OpenAES %-10s *\n" "* Copyright (c) 2013, Nabil S. Al Ramli, www.nalramli.com *\n" "*******************************************************************************\n\n", OAES_VERSION ); // pad the key for( _j = 0; _j < 32; _j++ ) _key_data[_j] = _j + 1; if( argc < 2 ) { usage( argv[0] ); return EXIT_FAILURE; } if( 0 == strcmp( argv[1], "gen-key" ) ) { OAES_CTX *_oaes = NULL; uint8_t _buf[16384]; size_t _buf_len = sizeof(_buf); OAES_RET _rc = OAES_RET_SUCCESS; _i++; _i++; // key_length _i++; // key_file if( _i >= argc ) { fprintf( stderr, "Error: No value specified for '%s'.\n", argv[1] ); usage( argv[0] ); return EXIT_FAILURE; } _key_data_len = atoi( argv[_i - 1] ); _file_k = argv[_i]; _oaes = oaes_alloc(); if( NULL == _oaes ) { fprintf(stderr, "Error: Failed to initialize OAES.\n"); return OAES_RET_MEM; } switch( _key_data_len ) { case 128: _rc = oaes_key_gen_128(_oaes); break; case 192: _rc = oaes_key_gen_192(_oaes); break; case 256: _rc = oaes_key_gen_256(_oaes); break; default: fprintf( stderr, "Error: Invalid value [%s] specified for '%s'.\n", argv[_i - 1], argv[_i - 2] ); oaes_free(&_oaes); return EXIT_FAILURE; } if( OAES_RET_SUCCESS != _rc ) { fprintf( stderr, "Error: Failed to generate OAES %lu bit key.\n", _key_data_len ); oaes_free(&_oaes); return EXIT_FAILURE; } if( OAES_RET_SUCCESS != oaes_key_export(_oaes, _buf, &_buf_len) ) { fprintf( stderr, "Error: Failed to retrieve key length %lu.\n", _key_data_len ); oaes_free(&_oaes); return EXIT_FAILURE; } oaes_free(&_oaes); if( 0 == access(_file_k, 00) ) { fprintf(stderr, "Error: '%s' already exists.\n", _file_k); return EXIT_FAILURE; } _f_k = fopen(_file_k, "wb"); if( NULL == _f_k ) { fprintf(stderr, "Error: Failed to open '%s' for writing.\n", _file_k); return EXIT_FAILURE; } fwrite(_buf, sizeof(uint8_t), _buf_len, _f_k); fclose(_f_k); return EXIT_SUCCESS; } else if( 0 == strcmp( argv[1], "base64-enc" ) ) { _op = 0; _read_len = OAES_BASE64_LEN_ENC; } else if( 0 == strcmp( argv[1], "base64-dec" ) ) { _op = 1; _read_len = OAES_BASE64_LEN_DEC; } else if( 0 == strcmp( argv[1], "aes-enc" ) ) { _op = 2; _read_len = OAES_AES_LEN_ENC; } else if( 0 == strcmp( argv[1], "aes-dec" ) ) { _op = 3; _read_len = OAES_AES_LEN_DEC; } else { fprintf(stderr, "Error: Unknown command '%s'.", argv[1]); usage( argv[0] ); return EXIT_FAILURE; } for( _i = 2; _i < argc; _i++ ) { int _found = 0; if( 0 == strcmp( argv[_i], "--ecb" ) ) { _found = 1; _is_ecb = 1; } if( 0 == strcmp( argv[_i], "--key" ) ) { uint8_t *_buf = NULL; size_t _buf_len = 0; _found = 1; _i++; // base64_encoded_key_data if( _i >= argc ) { fprintf(stderr, "Error: No value specified for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } if( oaes_base64_decode(argv[_i], strlen(argv[_i]), NULL, &_buf_len) ) { fprintf(stderr, "Error: Invalid value for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _buf = (uint8_t *) calloc(_buf_len, sizeof(uint8_t)); if( NULL == _buf ) { fprintf(stderr, "Error: Failed to allocate memory.\n"); return EXIT_FAILURE; } if( oaes_base64_decode(argv[_i], strlen(argv[_i]), _buf, &_buf_len) ) { free(_buf); fprintf(stderr, "Error: Invalid value for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _key_data_len = _buf_len; if( 16 >= _key_data_len ) _key_data_len = 16; else if( 24 >= _key_data_len ) _key_data_len = 24; else _key_data_len = 32; memcpy(_key_data, _buf, __min(32, _buf_len)); for( _j = 0; _j < _buf_len; _j++ ) { _key_data[_j % 32] ^= _buf[_j]; } free(_buf); } if( 0 == strcmp( argv[_i], "--key-file" ) ) { OAES_CTX *_ctx = NULL; uint8_t _buf[16384]; size_t _read = 0; _found = 1; _i++; // key_file if( _i >= argc ) { fprintf(stderr, "Error: No value specified for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _file_k = argv[_i]; _ctx = oaes_alloc(); if( NULL == _ctx ) { fprintf(stderr, "Error: Failed to initialize OAES.\n"); return OAES_RET_MEM; } _f_k = fopen(_file_k, "rb"); if( NULL == _f_k ) { fprintf(stderr, "Error: Failed to open '%s' for reading.\n", _file_k); oaes_free(&_ctx); return EXIT_FAILURE; } _read = fread(_buf, sizeof(uint8_t), sizeof(_buf), _f_k); fclose(_f_k); if( OAES_RET_SUCCESS != oaes_key_import(_ctx, _buf, _read) ) { fprintf(stderr, "Error: Failed to import '%s'.\n", _file_k); oaes_free(&_ctx); return EXIT_FAILURE; } _key_data_len = sizeof(_key_data); if( OAES_RET_SUCCESS != oaes_key_export_data(_ctx, _key_data, &_key_data_len) ) { fprintf(stderr, "Error: Failed to export '%s' data.\n", _file_k); oaes_free(&_ctx); return EXIT_FAILURE; } oaes_free(&_ctx); } if( 0 == strcmp( argv[_i], "--in" ) ) { _found = 1; _i++; // path_in if( _i >= argc ) { fprintf(stderr, "Error: No value specified for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _file_in = argv[_i]; } if( 0 == strcmp( argv[_i], "--out" ) ) { _found = 1; _i++; // path_out if( _i >= argc ) { fprintf(stderr, "Error: No value specified for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _file_out = argv[_i]; } if( 0 == _found ) { fprintf(stderr, "Error: Invalid option '%s'.\n", argv[_i]); usage( argv[0] ); return EXIT_FAILURE; } } switch(_op) { case 0: case 1: break; case 2: case 3: if( 0 == _key_data_len ) { char _key_data_ent[8193] = ""; uint8_t *_buf = NULL; size_t _buf_len = 0; fprintf(stderr, "Enter base64-encoded key: "); scanf("%8192s", _key_data_ent); if( oaes_base64_decode( _key_data_ent, strlen(_key_data_ent), NULL, &_buf_len ) ) { fprintf(stderr, "Error: Invalid value for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _buf = (uint8_t *) calloc(_buf_len, sizeof(uint8_t)); if( NULL == _buf ) { fprintf(stderr, "Error: Failed to allocate memory.\n"); return EXIT_FAILURE; } if( oaes_base64_decode( _key_data_ent, strlen(_key_data_ent), _buf, &_buf_len ) ) { free(_buf); fprintf(stderr, "Error: Invalid value for '%s'.\n", argv[_i - 1]); usage( argv[0] ); return EXIT_FAILURE; } _key_data_len = _buf_len; if( 16 >= _key_data_len ) _key_data_len = 16; else if( 24 >= _key_data_len ) _key_data_len = 24; else _key_data_len = 32; memcpy(_key_data, _buf, __min(32, _buf_len)); for( _j = 0; _j < _buf_len; _j++ ) { _key_data[_j % 32] ^= _buf[_j]; } free(_buf); } break; default: break; } if( _file_in ) { _f_in = fopen(_file_in, "rb"); if( NULL == _f_in ) { fprintf(stderr, "Error: Failed to open '%s' for reading.\n", _file_in); return EXIT_FAILURE; } } else { if( setmode(fileno(stdin), 0x8000) < 0 ) fprintf(stderr,"Error: Failed in setmode().\n"); _f_in = stdin; } if( _file_out ) { if( 0 == access(_file_out, 00) ) { fprintf(stderr, "Error: '%s' already exists.\n", _file_out); return EXIT_FAILURE; } _f_out = fopen(_file_out, "wb"); if( NULL == _f_out ) { fprintf(stderr, "Error: Failed to open '%s' for writing.\n", _file_out); if( _file_in ) fclose(_f_in); return EXIT_FAILURE; } } else { if( setmode(fileno(stdout), 0x8000) < 0 ) fprintf(stderr, "Error: Failed in setmode().\n"); _f_out = stdout; } _i = 0; while( _b[_i].in_len = fread(_b[_i].in, sizeof(uint8_t), _read_len, _f_in) ) { switch(_op) { case 0: _b[_i].id = start_thread(_do_base64_encode, &(_b[_i])); if( NULL == _b[_i].id ) fprintf(stderr, "Error: Failed to start encryption.\n"); break; case 1: _b[_i].id = start_thread(_do_base64_decode, &(_b[_i])); if( NULL == _b[_i].id ) fprintf(stderr, "Error: Failed to start decryption.\n"); break; case 2: _b[_i].id = start_thread(_do_aes_encrypt, &(_b[_i])); if( NULL == _b[_i].id ) fprintf(stderr, "Error: Failed to start encryption.\n"); break; case 3: _b[_i].id = start_thread(_do_aes_decrypt, &(_b[_i])); if( NULL == _b[_i].id ) fprintf(stderr, "Error: Failed to start decryption.\n"); break; default: break; } if( OAES_THREADS == _i + 1 ) { for( _j = 0; _j < OAES_THREADS; _j++ ) { if( _b[_j].id ) { join_thread(_b[_j].id); _b[_j].id = 0; if( _b[_j].out ) { fwrite(_b[_j].out, sizeof(uint8_t), _b[_j].out_len, _f_out); free(_b[_j].out); _b[_j].out = NULL; } } } } _i = (_i + 1) % OAES_THREADS; } for( _j = 0; _j < _i; _j++ ) { if( _b[_j].id ) { join_thread(_b[_j].id); _b[_j].id = 0; if( _b[_j].out ) { fwrite(_b[_j].out, sizeof(uint8_t), _b[_j].out_len, _f_out); free(_b[_j].out); _b[_j].out = NULL; } } } if( _file_in ) fclose(_f_in); if( _file_out ) fclose(_f_out); fprintf(stderr, "done.\n"); return (EXIT_SUCCESS); }
/* Set binary mode on fd. Does nothing in Unix. Returns negative number on failure. */ int sg_set_binary_mode(int fd) { return setmode(fd, O_BINARY); }